diff --git a/.circleci/config.yml b/.circleci/config.yml index c5b0d3dc6f1..c3611c57351 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -82,7 +82,6 @@ jobs: - ~/.bundle - ~/.go_workspace - ~/.gradle - - ~/.pub-cache - ~/.cache/bower - ".git" - ~/.stack diff --git a/.gitattributes b/.gitattributes index def43c73b65..86e3f4ed4b1 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1 +1,2 @@ **/*.mustache linguist-vendored=true +* text=auto eol=lf diff --git a/.github/actions/run-samples/action.yaml b/.github/actions/run-samples/action.yaml new file mode 100644 index 00000000000..64bc7745862 --- /dev/null +++ b/.github/actions/run-samples/action.yaml @@ -0,0 +1,19 @@ +name: 'Run samples' +description: 'Runs sample integration test profile with Maven' +inputs: + name: + description: 'The Maven profile name' + required: true + goal: + description: 'Maven goal' + required: false + default: 'verify' + args: + description: 'Additional maven arguments' + required: false + default: '' +runs: + using: "composite" + steps: + - run: mvn --no-snapshot-updates --batch-mode --quiet ${{ inputs.goal }} -P${{ inputs.name }} -Dintegration-test -Dmaven.javadoc.skip=true ${{ inputs.args }} + shell: bash \ No newline at end of file diff --git a/.github/workflows/check-supported-versions.yaml b/.github/workflows/check-supported-versions.yaml index 56992b9811e..3702fd30fb4 100644 --- a/.github/workflows/check-supported-versions.yaml +++ b/.github/workflows/check-supported-versions.yaml @@ -29,14 +29,14 @@ jobs: distribution: 'adopt' java-version: ${{ matrix.java }} - - uses: actions/cache@v2.1.5 + - uses: actions/cache@v2.1.6 with: path: ~/.m2/repository key: ${{ runner.os }}-maven-${{ hashFiles('pom.xml', 'modules/**/pom.xml') }} restore-keys: | ${{ runner.os }}-maven- - - uses: actions/cache@v2.1.5 + - uses: actions/cache@v2.1.6 with: path: | ~/.gradle/caches @@ -50,7 +50,7 @@ jobs: run: mvn -nsu -B --quiet -Djacoco.skip=true -Dorg.slf4j.simpleLogger.defaultLogLevel=error --no-transfer-progress clean install --file pom.xml ${{ matrix.flags }} - name: Upload Maven build artifact - uses: actions/upload-artifact@v2.2.3 + uses: actions/upload-artifact@v2.2.4 if: matrix.java == '8' && matrix.os == 'ubuntu-latest' with: name: artifact @@ -81,7 +81,7 @@ jobs: - name: Check out code uses: actions/checkout@v2 - name: Download build artifact - uses: actions/download-artifact@v2.0.8 + uses: actions/download-artifact@v2.0.10 with: name: artifact - name: Run Ensures Script @@ -90,6 +90,6 @@ jobs: git config --global core.fileMode false git config --global core.safecrlf false git config --global core.autocrlf true - mkdir -p modules/openapi-generator-cli/target/ - mv artifact/openapi-generator-cli.jar modules/openapi-generator-cli/target/ - ./bin/utils/ensure-up-to-date ${{ matrix.flags }} + mvn clean package -Dmaven.test.skip=true -Dmaven.javadoc.skip=true + # test with java (jersey2) client generation only as ensure-uptodate script is run in another job instead + ./bin/generate-samples.sh ./bin/configs/java-jersey2-8.yaml diff --git a/.github/workflows/openapi-generator-test-results.yaml b/.github/workflows/openapi-generator-test-results.yaml new file mode 100644 index 00000000000..f246b16c36b --- /dev/null +++ b/.github/workflows/openapi-generator-test-results.yaml @@ -0,0 +1,19 @@ +name: OpenAPI Generator Test Report + +on: + workflow_run: + workflows: ['OpenAPI Generator'] + types: + - completed + +# separate workflow required due to https://github.com/dorny/test-reporter#recommended-setup-for-public-repositories +jobs: + report: + runs-on: ubuntu-latest + steps: + - uses: dorny/test-reporter@v1 + with: + artifact: surefire-test-results + name: JUnit Test results + path: '**/surefire-reports/TEST-*.xml' + reporter: java-junit diff --git a/.github/workflows/openapi-generator.yaml b/.github/workflows/openapi-generator.yaml new file mode 100644 index 00000000000..aa1a94e21e9 --- /dev/null +++ b/.github/workflows/openapi-generator.yaml @@ -0,0 +1,214 @@ +name: OpenAPI Generator + +on: + push: + branches: + - master + - '[5-9]+.[0-9]+.x' + pull_request: + branches: + - master + - '[5-9]+.[0-9]+.x' + +jobs: + build: + name: Build + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - name: Set up JDK 8 + uses: actions/setup-java@v1 + with: + java-version: 8 + - name: Cache maven dependencies + uses: actions/cache@v2.1.6 + env: + cache-name: cache-maven-repository + with: + path: | + ~/.m2/repository + ~/.gradle + !~/.gradle/caches/*/plugin-resolution/ + !~/.m2/repository/org/openapitools/ + key: ${{ runner.os }}-build-${{ env.cache-name }}-${{ hashFiles('**/pom.xml') }} + restore-keys: | + ${{ runner.os }}-build-${{ env.cache-name }}- + ${{ runner.os }}-build- + - name: Run maven + run: mvn --no-snapshot-updates --batch-mode --quiet install -DskipTests -Dorg.slf4j.simpleLogger.defaultLogLevel=error + - run: ls -la modules/openapi-generator-cli/target + - name: Upload openapi-generator-cli.jar artifact + uses: actions/upload-artifact@v2.2.4 + with: + name: openapi-generator-cli.jar + path: modules/openapi-generator-cli/target/openapi-generator-cli.jar + retention-days: 1 + + test: + name: Unit tests + runs-on: ubuntu-latest + needs: + - build + steps: + - uses: actions/checkout@v2 + - name: Set up JDK 8 + uses: actions/setup-java@v1 + with: + java-version: 8 + - name: Cache maven dependencies + uses: actions/cache@v2.1.6 + env: + cache-name: cache-maven-repository + with: + path: | + ~/.m2/repository + ~/.gradle + !~/.gradle/caches/*/plugin-resolution/ + !~/.m2/repository/org/openapitools/ + key: ${{ runner.os }}-test-${{ env.cache-name }}-${{ hashFiles('**/pom.xml') }} + restore-keys: | + ${{ runner.os }}-build-${{ env.cache-name }}- + ${{ runner.os }}-build- + - name: Run unit tests + run: mvn --no-snapshot-updates --batch-mode --quiet --fail-at-end test -Dorg.slf4j.simpleLogger.defaultLogLevel=error + - name: Publish unit test reports + if: ${{ always() }} + uses: actions/upload-artifact@v2.2.4 + with: + name: surefire-test-results + path: '**/surefire-reports/TEST-*.xml' + + documentation: + name: Docs up-to-date + runs-on: ubuntu-latest + needs: + - build + steps: + - uses: actions/checkout@v2 + - name: Set up JDK 8 + uses: actions/setup-java@v1 + with: + java-version: 8 + - name: Download openapi-generator-cli.jar artifact + uses: actions/download-artifact@v2.0.10 + with: + name: openapi-generator-cli.jar + path: modules/openapi-generator-cli/target + - name: Generate docs + run: | + bash bin/meta-codegen.sh + bash bin/utils/export_docs_generators.sh + bash bin/utils/copy-to-website.sh + bash bin/utils/export_generators_readme.sh + - name: Verify git status + run: | + if [[ "$(git status --porcelain)" != "" ]]; then + echo "UNCOMMITTED CHANGES ERROR" + echo "There are uncommitted changes in working tree after execution of 'bin/ensure-up-to-date'" + echo "Perform git diff" + git --no-pager diff + echo "Perform git status" + git status + echo -e "\nThis script runs in pull requests against the anticipated merge commit (as if the PR was merged now)." + echo "When you see unexpected files here, it likely means that there are newer commits in master that you need to " + echo -e "rebase or merge into your branch.\n" + echo "Please run 'bin/utils/ensure-up-to-date' locally and commit changes (UNCOMMITTED CHANGES ERROR)" + exit 1 + fi + + samples: + name: Samples up-to-date + needs: + - build + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - name: Set up JDK 8 + uses: actions/setup-java@v1 + with: + java-version: 8 + - name: Download openapi-generator-cli.jar artifact + uses: actions/download-artifact@v2.0.10 + with: + name: openapi-generator-cli.jar + path: modules/openapi-generator-cli/target + - name: Generate samples + run: bash bin/generate-samples.sh + - name: Verify git status + run: | + if [[ "$(git status --porcelain)" != "" ]]; then + echo "UNCOMMITTED CHANGES ERROR" + echo "There are uncommitted changes in working tree after execution of 'bin/generate-samples.sh'" + echo "Perform git diff" + git --no-pager diff + echo "Perform git status" + git status + echo -e "\nThis script runs in pull requests against the anticipated merge commit (as if the PR was merged now)." + echo "When you see unexpected files here, it likely means that there are newer commits in master that you need to " + echo -e "rebase or merge into your branch.\n" + echo "Please run 'bin/generate-samples.sh' locally and commit changes (UNCOMMITTED CHANGES ERROR)" + exit 1 + fi + + test-maven-plugin: + name: Maven plugin tests + runs-on: ubuntu-latest + needs: + - build + steps: + - uses: actions/checkout@v2 + - name: Set up JDK 11 + uses: actions/setup-java@v1 + with: + java-version: 11 + - name: Cache maven dependencies + uses: actions/cache@v2.1.6 + env: + cache-name: cache-maven-repository + with: + path: | + ~/.m2/repository + ~/.gradle + !~/.gradle/caches/*/plugin-resolution/ + !~/.m2/repository/org/openapitools/ + key: ${{ runner.os }}-build-${{ env.cache-name }}-${{ hashFiles('**/pom.xml') }} + restore-keys: | + ${{ runner.os }}-test-maven-plugin-${{ env.cache-name }}- + ${{ runner.os }}-test-maven-plugin- + - name: Run tests + run: | + mvn --no-snapshot-updates --quiet clean compile -f modules/openapi-generator-maven-plugin/examples/java-client.xml -Dorg.slf4j.simpleLogger.defaultLogLevel=error + mvn --no-snapshot-updates --quiet clean compile -f modules/openapi-generator-maven-plugin/examples/multi-module/pom.xml -Dorg.slf4j.simpleLogger.defaultLogLevel=error + mvn --no-snapshot-updates --quiet clean compile -f modules/openapi-generator-maven-plugin/examples/kotlin.xml -Dorg.slf4j.simpleLogger.defaultLogLevel=error + mvn --no-snapshot-updates --quiet clean compile -f modules/openapi-generator-maven-plugin/examples/spring.xml -Dorg.slf4j.simpleLogger.defaultLogLevel=error + + test-gradle-plugin: + name: Gradle plugin tests + runs-on: ubuntu-latest + needs: + - build + steps: + - uses: actions/checkout@v2 + - name: Set up JDK 11 + uses: actions/setup-java@v1 + with: + java-version: 11 + - name: Cache maven dependencies + uses: actions/cache@v2.1.6 + env: + cache-name: cache-maven-repository + with: + path: | + ~/.m2/repository + ~/.gradle + !~/.gradle/caches/modules-2/modules-2.lock + !~/.gradle/caches/*/plugin-resolution/ + !~/.m2/repository/org/openapitools/ + key: ${{ runner.os }}-build-${{ env.cache-name }}-${{ hashFiles('**/pom.xml') }} + restore-keys: | + ${{ runner.os }}-test-gradle-plugin-${{ env.cache-name }}- + ${{ runner.os }}-test-gradle-plugin- + - name: Run tests + run: | + (cd modules/openapi-generator-gradle-plugin/samples/local-spec && ./gradlew buildGoSdk) + (cd modules/openapi-generator-gradle-plugin/samples/local-spec && ./gradlew openApiGenerate) diff --git a/.github/workflows/samples-dart.yaml b/.github/workflows/samples-dart.yaml new file mode 100644 index 00000000000..47ae424394d --- /dev/null +++ b/.github/workflows/samples-dart.yaml @@ -0,0 +1,80 @@ +name: Samples Dart + +on: + push: + branches: + - master + - '[5-9]+.[0-9]+.x' + pull_request: + branches: + - master + - '[5-9]+.[0-9]+.x' + paths: + - 'samples/openapi3/client/petstore/dart*/**' + +jobs: + tests-dart-2-10: + name: Tests Dart 2.10 + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - uses: actions/setup-java@v2 + with: + distribution: 'adopt' + java-version: 8 + - name: Cache maven dependencies + uses: actions/cache@v2.1.6 + env: + cache-name: maven-repository + with: + path: | + ~/.m2/repository + ~/.gradle + key: ${{ runner.os }}-${{ github.job }}-${{ env.cache-name }}-${{ hashFiles('**/pom.xml') }} + - name: Cache test dependencies + uses: actions/cache@v2.1.6 + env: + cache-name: pub-cache + with: + path: $PUB_CACHE + key: ${{ runner.os }}-${{ github.job }}-${{ env.cache-name }}-${{ hashFiles('samples/**/pubspec.yaml') }} + - uses: dart-lang/setup-dart@v1 + with: + sdk: 2.10.5 + - name: Run tests + uses: ./.github/actions/run-samples + with: + name: samples.dart-2.10 + + tests-dart-2-13: + name: Tests Dart 2.13 + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - uses: actions/setup-java@v2 + with: + distribution: 'adopt' + java-version: 8 + - name: Cache maven dependencies + uses: actions/cache@v2.1.6 + env: + cache-name: maven-repository + with: + path: | + ~/.m2/repository + ~/.gradle + key: ${{ runner.os }}-${{ github.job }}-${{ env.cache-name }}-${{ hashFiles('**/pom.xml') }} + - name: Cache test dependencies + uses: actions/cache@v2.1.6 + env: + cache-name: pub-cache + with: + path: $PUB_CACHE + key: ${{ runner.os }}-${{ github.job }}-${{ env.cache-name }}-${{ hashFiles('samples/**/pubspec.yaml') }} + - uses: dart-lang/setup-dart@v1 + with: + sdk: 2.13.0 + - name: Run tests + uses: ./.github/actions/run-samples + with: + name: samples.dart-2.13 diff --git a/.github/workflows/samples-kotlin.yaml b/.github/workflows/samples-kotlin.yaml new file mode 100644 index 00000000000..46c944fd74e --- /dev/null +++ b/.github/workflows/samples-kotlin.yaml @@ -0,0 +1,66 @@ +name: Samples Kotlin + +on: + push: + branches: + - master + - '[5-9]+.[0-9]+.x' + pull_request: + branches: + - master + - '[5-9]+.[0-9]+.x' + paths: + - 'samples/client/petstore/kotlin*/**' + +env: + GRADLE_VERSION: 6.9 + +jobs: + build: + name: Build Kotlin + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + sample: + - samples/client/petstore/kotlin + - samples/client/petstore/kotlin-gson + - samples/client/petstore/kotlin-jackson + # needs Android configured + #- samples/client/petstore/kotlin-json-request-string + - samples/client/petstore/kotlin-jvm-okhttp4-coroutines + - samples/client/petstore/kotlin-moshi-codegen + # need some special setup + #- samples/client/petstore/kotlin-multiplatform + - 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-rx3 + - samples/client/petstore/kotlin-string + - samples/client/petstore/kotlin-threetenbp + - samples/client/petstore/kotlin-uppercase-enum + steps: + - uses: actions/checkout@v2 + - uses: actions/setup-java@v2 + with: + distribution: 'adopt' + java-version: 8 + - name: Cache maven dependencies + uses: actions/cache@v2.1.6 + env: + cache-name: maven-repository + with: + path: | + ~/.gradle + key: ${{ runner.os }}-${{ github.job }}-${{ env.cache-name }}-${{ hashFiles('**/pom.xml') }} + - name: Install Gradle wrapper + uses: eskatos/gradle-command-action@v1 + with: + gradle-version: ${{ env.GRADLE_VERSION }} + build-root-directory: ${{ matrix.sample }} + arguments: wrapper + - name: Build + working-directory: ${{ matrix.sample }} + run: ./gradlew build -x test diff --git a/.gitignore b/.gitignore index b56824e26e3..9ce6c04e156 100644 --- a/.gitignore +++ b/.gitignore @@ -177,7 +177,6 @@ samples/client/petstore/python-tornado/.venv/ # PHP samples/client/petstore/php/OpenAPIClient-php/composer.lock samples/openapi3/server/petstore/php-symfony/SymfonyBundle-php/composer.lock -samples/openapi3/server/petstore/php-mezzio-ph/composer.lock samples/server/petstore/php-laravel/lib/composer.lock samples/server/petstore/php-lumen/lib/composer.lock samples/server/petstore/php-slim4/composer.lock @@ -213,6 +212,7 @@ cabal.project.local samples/client/petstore/haskell-http-client/docs/haddock-bundle.min.js samples/client/petstore/haskell-http-client/docs/meta.json samples/client/petstore/haskell-http-client/docs/quick-jump.css +samples/server/petstore/haskell-servant/stack.yaml.lock # R .Rproj.user diff --git a/.travis.yml b/.travis.yml index cc1f953acaa..7deb298f0fa 100644 --- a/.travis.yml +++ b/.travis.yml @@ -76,11 +76,11 @@ before_install: - docker run -d -e SWAGGER_HOST=http://petstore.swagger.io -e SWAGGER_BASE_PATH=/v2 -p 80:8080 swaggerapi/petstore - docker ps -a # install crystal - - curl -sSL https://dist.crystal-lang.org/apt/setup.sh | sudo bash - - curl -sL "https://keybase.io/crystal/pgp_keys.asc" | sudo apt-key add - - - echo "deb https://dist.crystal-lang.org/apt crystal main" | sudo tee /etc/apt/sources.list.d/crystal.list - - sudo apt-get update + - echo 'deb http://download.opensuse.org/repositories/devel:/languages:/crystal/xUbuntu_16.04/ /' | sudo tee /etc/apt/sources.list.d/devel:languages:crystal.list + - curl -fsSL https://download.opensuse.org/repositories/devel:languages:crystal/xUbuntu_16.04/Release.key | gpg --dearmor | sudo tee /etc/apt/trusted.gpg.d/devel_languages_crystal.gpg > /dev/null + - sudo apt update - sudo apt install crystal + - crystal --version - curl -o- -L https://yarnpkg.com/install.sh | bash -s -- --version 1.22.0 - export PATH="$HOME/.yarn/bin:$PATH" # install rust diff --git a/CI/.drone.yml b/CI/.drone.yml index 032d64b9e15..073d7332a43 100644 --- a/CI/.drone.yml +++ b/CI/.drone.yml @@ -7,8 +7,6 @@ steps: commands: - ./mvnw --quiet clean install -Dorg.slf4j.simpleLogger.defaultLogLevel=error - ./mvnw --quiet verify -Psamples.droneio -Dorg.slf4j.simpleLogger.defaultLogLevel=error - # run ensure up-to-date - - /bin/bash bin/utils/ensure-up-to-date # 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 diff --git a/CI/circle_parallel.sh b/CI/circle_parallel.sh index b647131c7d7..f1a5a529a79 100755 --- a/CI/circle_parallel.sh +++ b/CI/circle_parallel.sh @@ -14,17 +14,6 @@ function cleanup { trap cleanup EXIT -function installDart { - # install dart2 - sudo apt-get update - sudo apt-get install apt-transport-https - sudo sh -c 'wget -qO- https://dl-ssl.google.com/linux/linux_signing_key.pub | apt-key add -' - sudo sh -c 'wget -qO- https://storage.googleapis.com/download.dartlang.org/linux/debian/dart_stable.list > /etc/apt/sources.list.d/dart_stable.list' - sudo apt-get update - sudo apt-get install dart - export PATH="$PATH:/usr/lib/dart/bin" -} - if [ "$NODE_INDEX" = "1" ]; then echo "Running node $NODE_INDEX to test 'samples.circleci' defined in pom.xml ..." java -version @@ -35,21 +24,6 @@ if [ "$NODE_INDEX" = "1" ]; then ls -l /home/circleci/.ivy2/cache elif [ "$NODE_INDEX" = "2" ]; then - installDart - - # run ensure-up-to-date sample script on SNAPSHOT version only - project_version=`mvn org.apache.maven.plugins:maven-help-plugin:3.1.0:evaluate -Dexpression=project.version -q -DforceStdout` - if [[ $project_version == *"-SNAPSHOT" ]]; then - echo "Running node $NODE_INDEX to test ensure-up-to-date" - java -version - - # clear any changes to the samples - git checkout -- . - - # look for outdated samples - #./bin/utils/ensure-up-to-date - # UPDATE: moved to drone.io - fi echo "Running node $NODE_INDEX to test haskell" # install haskell curl -sSL https://get.haskellstack.org/ | sh diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 0fe833163af..4e59158cdb8 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -88,12 +88,10 @@ To add test cases (optional) covering the change in the code generator, please r To test the templates, please perform the following: -- Update the Petstore sample by running the shell scripts under the `bin` folder. For example, run `./bin/generate-samples.sh . -/bin/configs/python*` to update the Python-related samples under [`samples`](https://github.com/openapitools/openapi-generator/tree/master/samples). For Windows, please install [GIT bash](https://gitforwindows.org/). (If you find that there are new files generated or unexpected changes as a result of the update, that's not unusual as the test cases are added to the OpenAPI spec from time to time. If you've questions or concerns, please open a ticket to start a discussion) -- During development it can be helpful to quickly regenerate the samples without recompiling all of openapi-generator, e.g. when you have only updated the mustache templates. This can be done by passing the `-t` parameter: `-t modules/openapi-generator/src/main/resources/python`. +- Update the Petstore sample by running the shell scripts under the `bin` folder. For example, run `./bin/generate-samples.sh ./bin/configs/python*` to update the Python-related samples under [`samples`](https://github.com/openapitools/openapi-generator/tree/master/samples). For Windows, please install [GIT bash](https://gitforwindows.org/). (If you find that there are new files generated or unexpected changes as a result of the update, that's not unusual as the test cases are added to the OpenAPI spec from time to time. If you've questions or concerns, please open a ticket to start a discussion) +- During development, it can be helpful to quickly regenerate the samples without recompiling all of openapi-generator, e.g. when you have only updated the mustache templates. This can be done by passing the `-t` parameter: `-t modules/openapi-generator/src/main/resources/python`. - Run the tests in the sample folder using maven `mvn integration-test -f /path/to/pom.xml`, e.g. `mvn integration-test -f samples/client/petstore/python/pom.xml`. (some languages may not contain unit testing for Petstore and we're looking for contribution from the community to implement those tests) -- Finally, git commit the updated samples files: `git commit -a` - (`git add -A` if added files with new test cases) +- Finally, git commit the updated samples files: `git commit -a` (`git add -A` if added files with new test cases) - For new test cases, please add to the [Fake Petstore spec](https://github.com/OpenAPITools/openapi-generator/blob/master/modules/openapi-generator/src/test/resources/3_0/petstore-with-fake-endpoints-models-for-testing.yaml) To start the CI tests, you can: diff --git a/README.md b/README.md index 97e01df1c97..76fdb0d8d86 100644 --- a/README.md +++ b/README.md @@ -9,18 +9,26 @@
-[Master](https://github.com/OpenAPITools/openapi-generator/tree/master) (`5.2.0`): -[![Build Status](https://img.shields.io/travis/OpenAPITools/openapi-generator/master.svg?label=Integration%20Test)](https://travis-ci.org/OpenAPITools/openapi-generator) +[Master](https://github.com/OpenAPITools/openapi-generator/tree/master) (`5.2.1`): +[![Build Status](https://img.shields.io/travis/OpenAPITools/openapi-generator/master.svg?label=Integration%20Test)](https://travis-ci.com/OpenAPITools/openapi-generator) [![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-wh2wu) +[![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) [![JDK11 Build](https://cloud.drone.io/api/badges/OpenAPITools/openapi-generator/status.svg?ref=refs/heads/master)](https://cloud.drone.io/OpenAPITools/openapi-generator) [![Bitrise](https://img.shields.io/bitrise/4a2b10a819d12b67/master?label=bitrise%3A%20Swift+4,5&token=859FMDR8QHwabCzwvZK6vQ)](https://app.bitrise.io/app/4a2b10a819d12b67) [![GitHub Workflow Status (branch)](https://img.shields.io/github/workflow/status/openapitools/openapi-generator/Check%20Supported%20Java%20Versions/master?label=Check%20Supported%20Java%20Versions&logo=github&logoColor=green)](https://github.com/OpenAPITools/openapi-generator/actions?query=workflow%3A%22Check+Supported+Java+Versions%22) + +[5.3.x](https://github.com/OpenAPITools/openapi-generator/tree/5.3.x) (`5.3.x`): +[![Build Status](https://img.shields.io/travis/OpenAPITools/openapi-generator/5.3.x.svg?label=Integration%20Test)](https://travis-ci.com/OpenAPITools/openapi-generator) +[![Integration Test2](https://circleci.com/gh/OpenAPITools/openapi-generator/tree/5.3.x.svg?style=shield)](https://circleci.com/gh/OpenAPITools/openapi-generator) +[![Windows Test](https://ci.appveyor.com/api/projects/status/github/openapitools/openapi-generator?branch=5.3.x&svg=true&passingText=Windows%20Test%20-%20OK&failingText=Windows%20Test%20-%20Fails)](https://ci.appveyor.com/project/WilliamCheng/openapi-generator) +[![JDK11 Build](https://cloud.drone.io/api/badges/OpenAPITools/openapi-generator/status.svg?ref=refs/heads/5.3.x)](https://cloud.drone.io/OpenAPITools/openapi-generator) +[![Bitrise](https://img.shields.io/bitrise/4a2b10a819d12b67/5.3.x?label=bitrise%3A%20Swift+4,5&token=859FMDR8QHwabCzwvZK6vQ)](https://app.bitrise.io/app/4a2b10a819d12b67) + [6.0.x](https://github.com/OpenAPITools/openapi-generator/tree/6.0.x) (`6.0.x`): -[![Build Status](https://img.shields.io/travis/OpenAPITools/openapi-generator/6.0.x.svg?label=Integration%20Test)](https://travis-ci.org/OpenAPITools/openapi-generator) +[![Build Status](https://img.shields.io/travis/OpenAPITools/openapi-generator/6.0.x.svg?label=Integration%20Test)](https://travis-ci.com/OpenAPITools/openapi-generator) [![Integration Test2](https://circleci.com/gh/OpenAPITools/openapi-generator/tree/6.0.x.svg?style=shield)](https://circleci.com/gh/OpenAPITools/openapi-generator) -[![Windows Test](https://ci.appveyor.com/api/projects/status/github/openapitools/openapi-generator?branch=6.0.x&svg=true&passingText=Windows%20Test%20-%20OK&failingText=Windows%20Test%20-%20Fails)](https://ci.appveyor.com/project/WilliamCheng/openapi-generator-wh2wu) +[![Windows Test](https://ci.appveyor.com/api/projects/status/github/openapitools/openapi-generator?branch=6.0.x&svg=true&passingText=Windows%20Test%20-%20OK&failingText=Windows%20Test%20-%20Fails)](https://ci.appveyor.com/project/WilliamCheng/openapi-generator) [![JDK11 Build](https://cloud.drone.io/api/badges/OpenAPITools/openapi-generator/status.svg?ref=refs/heads/6.0.x)](https://cloud.drone.io/OpenAPITools/openapi-generator) [![Bitrise](https://img.shields.io/bitrise/4a2b10a819d12b67/6.0.x?label=bitrise%3A%20Swift+4,5&token=859FMDR8QHwabCzwvZK6vQ)](https://app.bitrise.io/app/4a2b10a819d12b67) @@ -67,11 +75,11 @@ OpenAPI Generator allows generation of API client libraries (SDK generation), se | | Languages/Frameworks | | -------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| **API clients** | **ActionScript**, **Ada**, **Apex**, **Bash**, **C**, **C#** (.net 2.0, 3.5 or later, .NET Standard 1.3 - 2.0, .NET Core 2.0, .NET 5.0. Libraries: RestSharp, HttpClient), **C++** (cpp-restsdk, Qt5, Tizen, Unreal Engine 4), **Clojure**, **Crystal**, **Dart**, **Elixir**, **Elm**, **Eiffel**, **Erlang**, **Go**, **Groovy**, **Haskell** (http-client, Servant), **Java** (Jersey1.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), **k6**, **Kotlin**, **Lua**, **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 (2.x - 11.x), Aurelia, Axios, Fetch, Inversify, jQuery, Nestjs, Node, redux-query, Rxjs) | -| **Server stubs** | **Ada**, **C#** (ASP.NET Core, NancyFx), **C++** (Pistache, Restbed, Qt5 QHTTPEngine), **Erlang**, **F#** (Giraffe), **Go** (net/http, Gin, Echo), **Haskell** (Servant), **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/)), **Kotlin** (Spring Boot, Ktor, Vertx), **PHP** (Laravel, Lumen, Slim, Silex, [Symfony](https://symfony.com/), [Zend Expressive](https://github.com/zendframework/zend-expressive)), **Python** (Flask), **NodeJS**, **Ruby** (Sinatra, Rails5), **Rust** (rust-server), **Scala** (Akka, [Finch](https://github.com/finagle/finch), [Lagom](https://github.com/lagom/lagom), [Play](https://www.playframework.com/), Scalatra) | +| **API clients** | **ActionScript**, **Ada**, **Apex**, **Bash**, **C**, **C#** (.net 2.0, 3.5 or later, .NET Standard 1.3 - 2.0, .NET Core 2.0, .NET 5.0. Libraries: RestSharp, HttpClient), **C++** (Arduino, cpp-restsdk, Qt5, Tizen, Unreal Engine 4), **Clojure**, **Crystal**, **Dart**, **Elixir**, **Elm**, **Eiffel**, **Erlang**, **Go**, **Groovy**, **Haskell** (http-client, Servant), **Java** (Jersey1.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), **k6**, **Kotlin**, **Lua**, **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 (2.x - 11.x), Aurelia, Axios, Fetch, Inversify, jQuery, Nestjs, Node, redux-query, Rxjs) | +| **Server stubs** | **Ada**, **C#** (ASP.NET Core, NancyFx), **C++** (Pistache, Restbed, Qt5 QHTTPEngine), **Erlang**, **F#** (Giraffe), **Go** (net/http, Gin, Echo), **Haskell** (Servant), **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/)), **Kotlin** (Spring Boot, Ktor, Vertx), **PHP** (Laravel, Lumen, Slim, Silex, [Symfony](https://symfony.com/), [Zend Expressive](https://github.com/zendframework/zend-expressive)), **Python** (FastAPI, Flask), **NodeJS**, **Ruby** (Sinatra, Rails5), **Rust** (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/) | -| **Others** | **GraphQL**, **JMeter**, **Ktorm**, **MySQL Schema**, **Protocol Buffer** | +| **Others** | **GraphQL**, **JMeter**, **Ktorm**, **MySQL Schema**, **Protocol Buffer**, **WSDL** | ## Table of contents @@ -110,8 +118,9 @@ The OpenAPI Specification has undergone 3 revisions since initial creation in 20 | OpenAPI Generator Version | Release Date | Notes | | --------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------ | ------------------------------------------------- | | 6.0.0 (upcoming major release) [SNAPSHOT](https://oss.sonatype.org/content/repositories/snapshots/org/openapitools/openapi-generator-cli/6.0.0-SNAPSHOT/) | Nov/Dec 2021 | Minor release with breaking changes (no fallback) | -| 5.2.0 (upcoming minor release) [SNAPSHOT](https://oss.sonatype.org/content/repositories/snapshots/org/openapitools/openapi-generator-cli/5.2.0-SNAPSHOT/) | Jun/Jul 2021 | Minor release with breaking changes (with fallback) | -| [5.1.1](https://github.com/OpenAPITools/openapi-generator/releases/tag/v5.1.1) (latest stable release) | 07.05.2021 | Patch release (enhancements, bug fixes, etc) | +| 5.3.0 (upcoming minor release) [SNAPSHOT](https://oss.sonatype.org/content/repositories/snapshots/org/openapitools/openapi-generator-cli/5.3.0-SNAPSHOT/) | Aug/Sep 2021 | Minor release with breaking changes (with fallback) | +| 5.2.1 (upcoming patch release) [SNAPSHOT](https://oss.sonatype.org/content/repositories/snapshots/org/openapitools/openapi-generator-cli/5.2.1-SNAPSHOT/) | 09.08.2021 | Patch release (enhancements, bug fixes, etc) | +| [5.2.0](https://github.com/OpenAPITools/openapi-generator/releases/tag/v5.2.0) (latest stable release) | 09.07.2021 | 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) | OpenAPI Spec compatibility: 1.0, 1.1, 1.2, 2.0, 3.0 @@ -168,16 +177,16 @@ See the different versions of the [openapi-generator-cli](https://mvnrepository. If you're looking for the latest stable version, you can grab it directly from Maven.org (Java 8 runtime at a minimum): -JAR location: `https://repo1.maven.org/maven2/org/openapitools/openapi-generator-cli/5.1.1/openapi-generator-cli-5.1.1.jar` +JAR location: `https://repo1.maven.org/maven2/org/openapitools/openapi-generator-cli/5.2.0/openapi-generator-cli-5.2.0.jar` For **Mac/Linux** users: ```sh -wget https://repo1.maven.org/maven2/org/openapitools/openapi-generator-cli/5.1.1/openapi-generator-cli-5.1.1.jar -O openapi-generator-cli.jar +wget https://repo1.maven.org/maven2/org/openapitools/openapi-generator-cli/5.2.0/openapi-generator-cli-5.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/5.1.1/openapi-generator-cli-5.1.1.jar +Invoke-WebRequest -OutFile openapi-generator-cli.jar https://repo1.maven.org/maven2/org/openapitools/openapi-generator-cli/5.2.0/openapi-generator-cli-5.2.0.jar ``` After downloading the JAR, run `java -jar openapi-generator-cli.jar help` to show the usage. @@ -269,7 +278,7 @@ To reinstall with the latest master, run `brew uninstall openapi-generator && br To install OpenJDK (pre-requisites), please run ```sh brew tap AdoptOpenJDK/openjdk -brew cask install adoptopenjdk12 +brew install --cask adoptopenjdk12 export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk-12.0.2.jdk/Contents/Home/ ``` @@ -402,7 +411,7 @@ openapi-generator-cli version To use a specific version of "openapi-generator-cli" ```sh -openapi-generator-cli version-manager set 5.1.1 +openapi-generator-cli version-manager set 5.2.0 ``` Or install it as dev-dependency: @@ -426,7 +435,7 @@ java -jar modules/openapi-generator-cli/target/openapi-generator-cli.jar generat (if you're on Windows, replace the last command with `java -jar modules\openapi-generator-cli\target\openapi-generator-cli.jar generate -i https://raw.githubusercontent.com/openapitools/openapi-generator/master/modules/openapi-generator/src/test/resources/3_0/petstore.yaml -g php -o c:\temp\php_api_client`) -You can also download the JAR (latest release) directly from [maven.org](https://repo1.maven.org/maven2/org/openapitools/openapi-generator-cli/5.1.1/openapi-generator-cli-5.1.1.jar) +You can also download the JAR (latest release) directly from [maven.org](https://repo1.maven.org/maven2/org/openapitools/openapi-generator-cli/5.2.0/openapi-generator-cli-5.2.0.jar) To get a list of **general** options available, please run `java -jar modules/openapi-generator-cli/target/openapi-generator-cli.jar help generate` @@ -564,6 +573,7 @@ Here is a list of community-contributed IDE plug-ins that integrate with OpenAPI ## [4 - Companies/Projects using OpenAPI Generator](#table-of-contents) Here are some companies/projects (alphabetical order) using OpenAPI Generator in production. To add your company/project to the list, please visit [README.md](README.md) and click on the icon to edit the page. +- [Aalborg University](https://www.aau.dk) - [Adaptant Solutions AG](https://www.adaptant.io/) - [adesso SE](https://www.adesso.de/) - [Agoda](https://www.agoda.com/) @@ -813,6 +823,9 @@ Here are some companies/projects (alphabetical order) using OpenAPI Generator in - 2021-03-31 - [使用OpenAPI Generator實現Open API Server](https://www.1ju.org/article/java-openapi-generator-server) at [億聚網](https://www.1ju.org/) - 2021-04-19 - [Introducing Twilio’s OpenAPI Specification Beta](https://www.twilio.com/blog/introducing-twilio-open-api-specification-beta) by [GARETH PAUL JONES](https://www.twilio.com/blog/author/gpj) at [Twilio Blog](https://www.twilio.com/blog) - 2021-04-22 - [Leveraging OpenApi strengths in a Micro-Service environment](https://medium.com/unibuddy-technology-blog/leveraging-openapi-strengths-in-a-micro-service-environment-3d7f9e7c26ff) by Nicolas Jellab at [Unibuddy Technology Blog](https://medium.com/unibuddy-technology-blog) +- 2021-04-27 - [From zero to publishing PowerShell API clients in PowerShell Gallery within minutes](https://speakerdeck.com/wing328/from-zero-to-publishing-powershell-api-clients-in-powershell-gallery-within-minutes) by [William Cheng](https://github.com/wing328) at [PowerShell + DevOps Global Summit 2021](https://events.devopscollective.org/event/powershell-devops-global-summit-2021/) +- 2021-05-31 - [FlutterでOpen Api Generator(Swagger)を使う](https://aakira.app/blog/2021/05/flutter-open-api/) by [AAkira](https://twitter.com/_a_akira) +- 2021-06-22 - [Rest API Documentation and Client Generation With OpenAPI](https://dzone.com/articles/rest-api-documentation-and-client-generation-with) by [Prasanth Gullapalli](https://dzone.com/users/1011797/prasanthnath.g@gmail.com.html) ## [6 - About Us](#table-of-contents) @@ -842,6 +855,7 @@ Here is a list of template creators: * Bash: @bkryza * C: @PowerOfCreation @zhemant [:heart:](https://www.patreon.com/zhemant) * C++ REST: @Danielku15 + * C++ Tiny: @AndersSpringborg @kaareHH @michelealbano @mkakbas * C++ UE4: @Kahncode * C# (.NET 2.0): @who * C# (.NET Standard 1.3 ): @Gronsak @@ -946,8 +960,10 @@ Here is a list of template creators: * PHP Laravel: @renepardon * PHP Lumen: @abcsun * PHP Slim: @jfastnacht + * PHP Slim4: @ybelenko * PHP Symfony: @ksm2 * PHP Zend Expressive (with Path Handler): @Articus + * Python FastAPI: @krjakbrjak * Python AIOHTTP: @Jyhess * Ruby on Rails 5: @zlx * Rust (rust-server): @metaswitch @@ -969,6 +985,7 @@ Here is a list of template creators: * Ktorm: @Luiz-Monad * MySQL: @ybelenko * Protocol Buffer: @wing328 + * WSDL @adessoDpd :heart: = Link to support the contributor directly @@ -1010,7 +1027,7 @@ If you want to join the committee, please kindly apply by sending an email to te | Bash | @frol (2017/07) @bkryza (2017/08) @kenjones-cisco (2017/09) | | C | @zhemant (2018/11) @ityuhui (2019/12) @michelealbano (2020/03) | | C++ | @ravinikam (2017/07) @stkrwork (2017/07) @etherealjoy (2018/02) @martindelille (2018/03) @muttleyxd (2019/08) | -| C# | @mandrean (2017/08) @frankyjuang (2019/09) @shibayan (2020/02) @Blackclaws (2021/03) | +| C# | @mandrean (2017/08) @frankyjuang (2019/09) @shibayan (2020/02) @Blackclaws (2021/03) @lucamazzanti (2021/05) | | Clojure | | | Dart | @swipesight (2018/09) @jaumard (2018/09) @josh-burton (2019/12) @amondnet (2019/12) @sbu-WBT (2020/12) @kuhnroyal (2020/12) @agilob (2020/12) | | Eiffel | @jvelilla (2017/09) | diff --git a/appveyor.yml b/appveyor.yml index ec69f197198..e50dc6c2bb2 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -29,8 +29,9 @@ install: - cmd: java -version - cmd: gradle -v - cmd: dir/w - - git clone https://github.com/wing328/swagger-samples + - git clone https://github.com/wing328/swagger-samples --depth 1 - ps: Start-Process -FilePath 'C:\maven\apache-maven-3.2.5\bin\mvn' -ArgumentList 'jetty:run' -WorkingDirectory "$env:appveyor_build_folder\swagger-samples\java\java-jersey-jaxrs-ci" + - ps: Start-Sleep -s 15 - ps: $PSVersionTable.PSVersion - ps: Install-Module -Name Pester -Force -Scope CurrentUser build_script: @@ -54,6 +55,8 @@ build_script: - dotnet build samples\client\petstore\csharp-netcore\OpenAPIClient-net47\Org.OpenAPITools.sln # build C# API client (.net 5.0) - dotnet build samples\client\petstore\csharp-netcore\OpenAPIClient-net5.0\Org.OpenAPITools.sln + # build C# API client (.net 5.0 with ConditionalSerialization) + - dotnet build samples\client\petstore\csharp-netcore\OpenAPIClient-ConditionalSerialization\Org.OpenAPITools.sln # build C# API client - nuget restore samples\client\petstore\csharp\OpenAPIClient\Org.OpenAPITools.sln - msbuild samples\client\petstore\csharp\OpenAPIClient\Org.OpenAPITools.sln /logger:"C:\Program Files\AppVeyor\BuildAgent\Appveyor.MSBuildLogger.dll" @@ -79,6 +82,8 @@ test_script: - dotnet test samples\client\petstore\csharp-netcore\OpenAPIClient-net47\src\Org.OpenAPITools.Test\Org.OpenAPITools.Test.csproj # test C# API client (.net 5.0) - dotnet test samples\client\petstore\csharp-netcore\OpenAPIClient-net5.0\src\Org.OpenAPITools.Test\Org.OpenAPITools.Test.csproj + # test C# API Client using conditional-serialization + - dotnet test samples\client\petstore\csharp-netcore\OpenAPIClient-ConditionalSerialization\src\Org.OpenAPITools.Test\Org.OpenAPITools.Test.csproj # test c# API client - nunit3-console samples\client\petstore\csharp\OpenAPIClient\src\Org.OpenAPITools.Test\bin\Debug\Org.OpenAPITools.Test.dll --result=myresults.xml;format=AppVeyor # test c# API client (with PropertyChanged) diff --git a/bin/configs/cpp-qt5-client.yaml b/bin/configs/cpp-qt-client.yaml similarity index 72% rename from bin/configs/cpp-qt5-client.yaml rename to bin/configs/cpp-qt-client.yaml index dc36141b436..14f4a274500 100644 --- a/bin/configs/cpp-qt5-client.yaml +++ b/bin/configs/cpp-qt-client.yaml @@ -1,7 +1,7 @@ -generatorName: cpp-qt5-client -outputDir: samples/client/petstore/cpp-qt5 +generatorName: cpp-qt-client +outputDir: samples/client/petstore/cpp-qt inputSpec: modules/openapi-generator/src/test/resources/2_0/petstore.yaml -templateDir: modules/openapi-generator/src/main/resources/cpp-qt5-client +templateDir: modules/openapi-generator/src/main/resources/cpp-qt-client additionalProperties: cppNamespace: test_namespace modelNamePrefix: PFX diff --git a/bin/configs/cpp-qt5-qhttpengine-server.yaml b/bin/configs/cpp-qt-qhttpengine-server.yaml similarity index 52% rename from bin/configs/cpp-qt5-qhttpengine-server.yaml rename to bin/configs/cpp-qt-qhttpengine-server.yaml index 8ead0fe398d..9a03bcbc951 100644 --- a/bin/configs/cpp-qt5-qhttpengine-server.yaml +++ b/bin/configs/cpp-qt-qhttpengine-server.yaml @@ -1,4 +1,4 @@ -generatorName: cpp-qt5-qhttpengine-server -outputDir: samples/server/petstore/cpp-qt5-qhttpengine-server +generatorName: cpp-qt-qhttpengine-server +outputDir: samples/server/petstore/cpp-qt-qhttpengine-server inputSpec: modules/openapi-generator/src/test/resources/2_0/petstore.yaml -templateDir: modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server +templateDir: modules/openapi-generator/src/main/resources/cpp-qt-qhttpengine-server diff --git a/bin/configs/cpp-tiny.yaml b/bin/configs/cpp-tiny.yaml new file mode 100644 index 00000000000..237ae1403f4 --- /dev/null +++ b/bin/configs/cpp-tiny.yaml @@ -0,0 +1,7 @@ +generatorName: cpp-tiny +outputDir: samples/client/petstore/cpp-tiny +inputSpec: modules/openapi-generator/src/test/resources/3_0/petstore.yaml +templateDir: modules/openapi-generator/src/main/resources/cpp-tiny +additionalProperties: + hideGenerationTimestamp: "true" + controller: "esp32" diff --git a/bin/configs/csharp-netcore-OpenAPIClient_ConditionalSerialization.yaml b/bin/configs/csharp-netcore-OpenAPIClient_ConditionalSerialization.yaml new file mode 100644 index 00000000000..7c7364771be --- /dev/null +++ b/bin/configs/csharp-netcore-OpenAPIClient_ConditionalSerialization.yaml @@ -0,0 +1,12 @@ +# for .net standard +generatorName: csharp-netcore +outputDir: samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization +inputSpec: modules/openapi-generator/src/test/resources/3_0/java/petstore-with-fake-endpoints-models-for-testing-with-http-signature.yaml +templateDir: modules/openapi-generator/src/main/resources/csharp-netcore +additionalProperties: + packageGuid: '{fa96c953-af24-457d-8a01-f2fd2a7547a9}' + useCompareNetObjects: true + disallowAdditionalPropertiesIfNotPresent: false + useOneOfDiscriminatorLookup: true + targetFramework: netstandard2.0 + conditionalSerialization: true \ No newline at end of file diff --git a/bin/configs/other/erlang-server.yaml b/bin/configs/erlang-server.yaml similarity index 100% rename from bin/configs/other/erlang-server.yaml rename to bin/configs/erlang-server.yaml diff --git a/bin/configs/go-server-chi-api-server.yaml b/bin/configs/go-server-chi-api-server.yaml new file mode 100644 index 00000000000..16db86a3d62 --- /dev/null +++ b/bin/configs/go-server-chi-api-server.yaml @@ -0,0 +1,9 @@ +generatorName: go-server +outputDir: samples/server/petstore/go-chi-server +inputSpec: modules/openapi-generator/src/test/resources/3_0/petstore.yaml +templateDir: modules/openapi-generator/src/main/resources/go-server +additionalProperties: + hideGenerationTimestamp: "true" + packageName: petstoreserver + addResponseHeaders: true + router: "chi" diff --git a/bin/configs/other/haskell-servant.yaml b/bin/configs/haskell-servant.yaml similarity index 100% rename from bin/configs/other/haskell-servant.yaml rename to bin/configs/haskell-servant.yaml diff --git a/bin/configs/kotlin-json-request-string.yaml b/bin/configs/kotlin-json-request-string.yaml index 375622ae5df..bbe5ddd4283 100644 --- a/bin/configs/kotlin-json-request-string.yaml +++ b/bin/configs/kotlin-json-request-string.yaml @@ -6,3 +6,4 @@ additionalProperties: requestDateConverter: toString artifactId: kotlin-petstore-json-request-string parcelizeModels: true + supportAndroidApiLevel25AndBelow: true diff --git a/bin/configs/php-mezzio-ph-modern.yaml b/bin/configs/php-mezzio-ph-modern.yaml new file mode 100644 index 00000000000..accaa2dfe30 --- /dev/null +++ b/bin/configs/php-mezzio-ph-modern.yaml @@ -0,0 +1,6 @@ +generatorName: php-mezzio-ph +outputDir: samples/server/petstore/php-mezzio-ph-modern +inputSpec: modules/openapi-generator/src/test/resources/3_0/petstore.yaml +templateDir: modules/openapi-generator/src/main/resources/php-mezzio-ph-modern +additionalProperties: + modern: "true" diff --git a/bin/configs/python-fastapi.yaml b/bin/configs/python-fastapi.yaml new file mode 100644 index 00000000000..7bf7405c527 --- /dev/null +++ b/bin/configs/python-fastapi.yaml @@ -0,0 +1,6 @@ +generatorName: python-fastapi +outputDir: samples/server/petstore/python-fastapi +inputSpec: modules/openapi-generator/src/test/resources/3_0/petstore.yaml +templateDir: modules/openapi-generator/src/main/resources/python-fastapi +additionalProperties: + hideGenerationTimestamp: "true" diff --git a/bin/configs/scala-legacy.yaml b/bin/configs/scala-legacy.yaml new file mode 100644 index 00000000000..7c9c1865bc0 --- /dev/null +++ b/bin/configs/scala-legacy.yaml @@ -0,0 +1,9 @@ +# This is for generating scala legacy client +generatorName: scala-httpclient-deprecated +outputDir: samples/client/petstore/scala-httpclient-deprecated +inputSpec: modules/openapi-generator/src/test/resources/3_0/petstore.yaml +templateDir: modules/openapi-generator/src/main/resources/scala-httpclient +additionalProperties: + apiPackage: org.openapitools.example.api + invokerPackage: org.openapitools.example.invoker + artifactId: scala-legacy-petstore \ No newline at end of file diff --git a/bin/configs/swift5-oneOf.yaml b/bin/configs/swift5-oneOf.yaml new file mode 100644 index 00000000000..975892b340c --- /dev/null +++ b/bin/configs/swift5-oneOf.yaml @@ -0,0 +1,10 @@ +generatorName: swift5 +outputDir: samples/client/petstore/swift5/oneOf +inputSpec: modules/openapi-generator/src/test/resources/3_0/oneOf.yaml +templateDir: modules/openapi-generator/src/main/resources/swift5 +generateAliasAsModel: true +additionalProperties: + podAuthors: "" + podSummary: PetstoreClient + projectName: PetstoreClient + podHomepage: https://github.com/openapitools/openapi-generator diff --git a/bin/configs/swift5-rxswiftLibrary.yaml b/bin/configs/swift5-rxswiftLibrary.yaml index 49d0e24cca5..8751d347912 100644 --- a/bin/configs/swift5-rxswiftLibrary.yaml +++ b/bin/configs/swift5-rxswiftLibrary.yaml @@ -10,3 +10,4 @@ additionalProperties: projectName: PetstoreClient podHomepage: https://github.com/openapitools/openapi-generator useBacktickEscapes: true + generateModelAdditionalProperties: false diff --git a/bin/configs/swift5-urlsessionLibrary.yaml b/bin/configs/swift5-urlsessionLibrary.yaml index b260611e602..1520a7c1ea9 100644 --- a/bin/configs/swift5-urlsessionLibrary.yaml +++ b/bin/configs/swift5-urlsessionLibrary.yaml @@ -11,3 +11,4 @@ additionalProperties: podHomepage: https://github.com/openapitools/openapi-generator useSPMFileStructure: true useClasses: true + swiftUseApiNamespace: true diff --git a/bin/configs/swift5-vapor.yaml b/bin/configs/swift5-vapor.yaml new file mode 100644 index 00000000000..5f1d2067969 --- /dev/null +++ b/bin/configs/swift5-vapor.yaml @@ -0,0 +1,12 @@ +generatorName: swift5 +outputDir: samples/client/petstore/swift5/vaporLibrary +library: vapor +inputSpec: modules/openapi-generator/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml +templateDir: modules/openapi-generator/src/main/resources/swift5 +generateAliasAsModel: true +additionalProperties: + projectName: PetstoreClient + useSPMFileStructure: true + useClasses: true + useBacktickEscapes: true + mapFileBinaryToData: true diff --git a/bin/configs/swift5-x-swift-hashable.yaml b/bin/configs/swift5-x-swift-hashable.yaml new file mode 100644 index 00000000000..c07937d5336 --- /dev/null +++ b/bin/configs/swift5-x-swift-hashable.yaml @@ -0,0 +1,11 @@ +generatorName: swift5 +outputDir: samples/client/petstore/swift5/x-swift-hashable +inputSpec: modules/openapi-generator/src/test/resources/2_0/swift/petstore-with-fake-endpoints-models-for-testing.yaml +templateDir: modules/openapi-generator/src/main/resources/swift5 +generateAliasAsModel: true +additionalProperties: + podAuthors: "" + podSummary: PetstoreClient + projectName: PetstoreClient + podHomepage: https://github.com/openapitools/openapi-generator + hashableModels: false diff --git a/bin/configs/typescript-angular-v11-oneOf.yaml b/bin/configs/typescript-angular-v11-oneOf.yaml new file mode 100644 index 00000000000..e9d83262ac8 --- /dev/null +++ b/bin/configs/typescript-angular-v11-oneOf.yaml @@ -0,0 +1,5 @@ +generatorName: typescript-angular +outputDir: samples/client/petstore/typescript-angular-v11-oneOf/builds/default +inputSpec: modules/openapi-generator/src/test/resources/3_0/oneOfArrayMapImport.yaml +additionalProperties: + ngVersion: 11.0.0 diff --git a/bin/configs/typescript-fetch-sagas-and-records.yaml b/bin/configs/typescript-fetch-sagas-and-records.yaml new file mode 100644 index 00000000000..a9fbe6136c7 --- /dev/null +++ b/bin/configs/typescript-fetch-sagas-and-records.yaml @@ -0,0 +1,16 @@ +generatorName: typescript-fetch +outputDir: samples/client/petstore/typescript-fetch/builds/sagas-and-records +inputSpec: modules/openapi-generator/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing-saga-and-records.yaml +additionalProperties: + npmVersion: 1.0.0 + npmName: '@openapitools/typescript-fetch-petstore' + npmRepository: https://skimdb.npmjs.com/registry + useSingleRequestParameter: false + supportsES6: true + typescriptThreePlus: true + sagasAndRecords: true + detectPassthroughModelsWithSuffixAndField: 'Response.data' + inferUniqueIdFromNameSuffix: true + inferEntityFromUniqueIdWithName: id + packageAsSourceOnlyLibrary: false + snapshot: false \ No newline at end of file diff --git a/bin/configs/wsdl-schema.yaml b/bin/configs/wsdl-schema.yaml new file mode 100644 index 00000000000..29484b39dfe --- /dev/null +++ b/bin/configs/wsdl-schema.yaml @@ -0,0 +1,6 @@ +generatorName: wsdl-schema +outputDir: samples/schema/petstore/wsdl-schema +inputSpec: modules/openapi-generator/src/test/resources/3_0/wsdl/petstore.yaml +templateDir: modules/openapi-generator/src/main/resources/wsdl-schema +additionalProperties: + hideGenerationTimestamp: "true" diff --git a/bin/utils/release/release_version_update.sh b/bin/utils/release/release_version_update.sh index c2be83681ca..f57fd7b7daf 100755 --- a/bin/utils/release/release_version_update.sh +++ b/bin/utils/release/release_version_update.sh @@ -83,7 +83,6 @@ declare -a xml_files=( "${root}/modules/openapi-generator-maven-plugin/examples/java-client.xml" "${root}/modules/openapi-generator-maven-plugin/examples/non-java-invalid-spec.xml" "${root}/modules/openapi-generator-maven-plugin/examples/non-java.xml" - "${root}/samples/meta-codegen/lib/pom.xml" "${root}/pom.xml" ) diff --git a/docs/contributing.md b/docs/contributing.md index fe325ae17e1..f47d79bd09f 100644 --- a/docs/contributing.md +++ b/docs/contributing.md @@ -92,12 +92,10 @@ To add test cases (optional) covering the change in the code generator, please r To test the templates, please perform the following: -- Update the Petstore sample by running the shell scripts under the `bin` folder. For example, run `./bin/generate-samples.sh . -/bin/configs/python*` to update the Python-related samples under [`samples`](https://github.com/openapitools/openapi-generator/tree/master/samples). For Windows, please install [GIT bash](https://gitforwindows.org/). (If you find that there are new files generated or unexpected changes as a result of the update, that's not unusual as the test cases are added to the OpenAPI spec from time to time. If you've questions or concerns, please open a ticket to start a discussion) -- During development it can be helpful to quickly regenerate the samples without recompiling all of openapi-generator, e.g. when you have only updated the mustache templates. This can be done by passing the `-t` parameter: `-t modules/openapi-generator/src/main/resources/python`. +- Update the Petstore sample by running the shell scripts under the `bin` folder. For example, run `./bin/generate-samples.sh ./bin/configs/python*` to update the Python-related samples under [`samples`](https://github.com/openapitools/openapi-generator/tree/master/samples). For Windows, please install [GIT bash](https://gitforwindows.org/). (If you find that there are new files generated or unexpected changes as a result of the update, that's not unusual as the test cases are added to the OpenAPI spec from time to time. If you've questions or concerns, please open a ticket to start a discussion) +- During development, it can be helpful to quickly regenerate the samples without recompiling all of openapi-generator, e.g. when you have only updated the mustache templates. This can be done by passing the `-t` parameter: `-t modules/openapi-generator/src/main/resources/python`. - Run the tests in the sample folder using maven `mvn integration-test -f /path/to/pom.xml`, e.g. `mvn integration-test -f samples/client/petstore/python/pom.xml`. (some languages may not contain unit testing for Petstore and we're looking for contribution from the community to implement those tests) -- Finally, git commit the updated samples files: `git commit -a` - (`git add -A` if added files with new test cases) +- Finally, git commit the updated samples files: `git commit -a` (`git add -A` if added files with new test cases) - For new test cases, please add to the [Fake Petstore spec](https://github.com/OpenAPITools/openapi-generator/blob/master/modules/openapi-generator/src/test/resources/3_0/petstore-with-fake-endpoints-models-for-testing.yaml) To start the CI tests, you can: diff --git a/docs/generators.md b/docs/generators.md index 6cb063b2230..c71da0663ed 100644 --- a/docs/generators.md +++ b/docs/generators.md @@ -12,8 +12,9 @@ The following generators are available: * [bash](generators/bash.md) * [c](generators/c.md) * [clojure](generators/clojure.md) -* [cpp-qt5-client](generators/cpp-qt5-client.md) +* [cpp-qt-client](generators/cpp-qt-client.md) * [cpp-restsdk](generators/cpp-restsdk.md) +* [cpp-tiny (beta)](generators/cpp-tiny.md) * [cpp-tizen](generators/cpp-tizen.md) * [cpp-ue4 (beta)](generators/cpp-ue4.md) * [crystal (beta)](generators/crystal.md) @@ -61,7 +62,7 @@ The following generators are available: * [scala-sttp (beta)](generators/scala-sttp.md) * [scalaz](generators/scalaz.md) * [swift4-deprecated (deprecated)](generators/swift4-deprecated.md) -* [swift5 (beta)](generators/swift5.md) +* [swift5](generators/swift5.md) * [typescript (experimental)](generators/typescript.md) * [typescript-angular](generators/typescript-angular.md) * [typescript-angularjs-deprecated (deprecated)](generators/typescript-angularjs-deprecated.md) @@ -80,7 +81,7 @@ The following generators are available: * [ada-server](generators/ada-server.md) * [aspnetcore](generators/aspnetcore.md) * [cpp-pistache-server](generators/cpp-pistache-server.md) -* [cpp-qt5-qhttpengine-server](generators/cpp-qt5-qhttpengine-server.md) +* [cpp-qt-qhttpengine-server](generators/cpp-qt-qhttpengine-server.md) * [cpp-restbed-server](generators/cpp-restbed-server.md) * [csharp-nancyfx](generators/csharp-nancyfx.md) * [erlang-server](generators/erlang-server.md) @@ -119,6 +120,7 @@ The following generators are available: * [php-symfony](generators/php-symfony.md) * [python-aiohttp](generators/python-aiohttp.md) * [python-blueplanet](generators/python-blueplanet.md) +* [python-fastapi (beta)](generators/python-fastapi.md) * [python-flask](generators/python-flask.md) * [ruby-on-rails](generators/ruby-on-rails.md) * [ruby-sinatra](generators/ruby-sinatra.md) @@ -149,6 +151,7 @@ The following generators are available: * [ktorm-schema (beta)](generators/ktorm-schema.md) * [mysql-schema](generators/mysql-schema.md) * [protobuf-schema (beta)](generators/protobuf-schema.md) +* [wsdl-schema (beta)](generators/wsdl-schema.md) ## CONFIG generators diff --git a/docs/generators/aspnetcore.md b/docs/generators/aspnetcore.md index 99f0b789bdc..d7e282c8279 100644 --- a/docs/generators/aspnetcore.md +++ b/docs/generators/aspnetcore.md @@ -9,7 +9,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl | ------ | ----------- | ------ | ------- | |aspnetCoreVersion|ASP.NET Core version: 5.0, 3.1, 3.0, 2.2, 2.1, 2.0 (deprecated)|
**2.0**
ASP.NET Core 2.0
**2.1**
ASP.NET Core 2.1
**2.2**
ASP.NET Core 2.2
**3.0**
ASP.NET Core 3.0
**3.1**
ASP.NET Core 3.1
**5.0**
ASP.NET Core 5.0
|3.1| |buildTarget|Target to build an application or library|
**program**
Generate code for a standalone server
**library**
Generate code for a server abstract class library
|program| -|classModifier|Class Modifier for controller classes: Empty string or abstract.|
****
Keep class default with no modifier
**abstract**
Make class abstract
|| +|classModifier|Class Modifier for controller classes: Empty string or abstract.| || |compatibilityVersion|ASP.Net Core CompatibilityVersion| |Version_2_2| |enumNameSuffix|Suffix that will be appended to all enum names.| |Enum| |enumValueSuffix|Suffix that will be appended to all enum values.| |Enum| @@ -17,8 +17,9 @@ These options may be applied as additional-properties (cli) or configOptions (pl |isLibrary|Is the build a library| |false| |licenseName|The name of the license| |NoLicense| |licenseUrl|The URL of the license| |http://localhost| -|modelClassModifier|Model Class Modifier can be nothing or partial|
****
Keep model class default with no modifier
**partial**
Make model class partial
|partial| +|modelClassModifier|Model Class Modifier can be nothing or partial| |partial| |newtonsoftVersion|Version for Microsoft.AspNetCore.Mvc.NewtonsoftJson for ASP.NET Core 3.0+| |3.0.0| +|nullableReferenceTypes|Use nullable annotations in the project. Only supported on C# 8 / ASP.NET Core 3.0 or newer.| |false| |operationIsAsync|Set methods to async or sync (default).| |false| |operationModifier|Operation Modifier can be virtual or abstract|
**virtual**
Keep method virtual
**abstract**
Make method abstract
|virtual| |operationResultTask|Set methods result to Task<>.| |false| diff --git a/docs/generators/cpp-qt5-client.md b/docs/generators/cpp-qt-client.md similarity index 99% rename from docs/generators/cpp-qt5-client.md rename to docs/generators/cpp-qt-client.md index ce9e00428f8..0dcbd968233 100644 --- a/docs/generators/cpp-qt5-client.md +++ b/docs/generators/cpp-qt-client.md @@ -1,6 +1,6 @@ --- -title: Config Options for cpp-qt5-client -sidebar_label: cpp-qt5-client +title: Config Options for cpp-qt-client +sidebar_label: cpp-qt-client --- 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. diff --git a/docs/generators/cpp-qt5-qhttpengine-server.md b/docs/generators/cpp-qt-qhttpengine-server.md similarity index 98% rename from docs/generators/cpp-qt5-qhttpengine-server.md rename to docs/generators/cpp-qt-qhttpengine-server.md index 3467f16775b..efd57d28d7a 100644 --- a/docs/generators/cpp-qt5-qhttpengine-server.md +++ b/docs/generators/cpp-qt-qhttpengine-server.md @@ -1,6 +1,6 @@ --- -title: Config Options for cpp-qt5-qhttpengine-server -sidebar_label: cpp-qt5-qhttpengine-server +title: Config Options for cpp-qt-qhttpengine-server +sidebar_label: cpp-qt-qhttpengine-server --- 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. diff --git a/docs/generators/cpp-tiny.md b/docs/generators/cpp-tiny.md new file mode 100644 index 00000000000..1c90b5cbe8e --- /dev/null +++ b/docs/generators/cpp-tiny.md @@ -0,0 +1,243 @@ +--- +title: Config Options for cpp-tiny +sidebar_label: cpp-tiny +--- + +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| +|controller|name of microcontroller (e.g esp32 or esp8266)| |esp32| +|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| +|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| +|reservedWordPrefix|Prefix to prepend to reserved words in order to avoid conflicts| |r_| +|sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| +|sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| +|variableNameFirstCharacterUppercase|Make first character of variable name uppercase (eg. value -> Value)| |true| + +## IMPORT MAPPING + +| Type/Alias | Imports | +| ---------- | ------- | + + +## INSTANTIATION TYPES + +| Type/Alias | Instantiated By | +| ---------- | --------------- | + + +## LANGUAGE PRIMITIVES + + + +## RESERVED WORDS + + + +## 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 +|Array|✓|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 + +### 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 + +### Wire Format Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|JSON|✓|OAS2,OAS3 +|XML|✗|OAS2,OAS3 +|PROTOBUF|✗|ToolingExtension +|Custom|✗|OAS2,OAS3 diff --git a/docs/generators/csharp-netcore.md b/docs/generators/csharp-netcore.md index 0887dcbfeca..8999e7a3a61 100644 --- a/docs/generators/csharp-netcore.md +++ b/docs/generators/csharp-netcore.md @@ -9,6 +9,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl | ------ | ----------- | ------ | ------- | |allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false| |caseInsensitiveResponseHeaders|Make API response's headers case-insensitive| |false| +|conditionalSerialization|Serialize only those properties which are initialized by user, accepted values are true or false, default value 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| |hideGenerationTimestamp|Hides the generation timestamp when files are generated.| |true| |interfacePrefix|Prefix interfaces with a community standard or widely accepted prefix.| |I| @@ -17,6 +18,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |modelPropertyNaming|Naming convention for the property: 'camelCase', 'PascalCase', 'snake_case' and 'original', which keeps the original name| |PascalCase| |netCoreProjectFile|Use the new format (.NET Core) for .NET project files (.csproj).| |false| |nonPublicApi|Generates code with reduced access modifiers; allows embedding elsewhere without exposing non-public API calls to consumers.| |false| +|nullableReferenceTypes|Use nullable annotations in the project. Only supported on C# 8 / ASP.NET Core 3.0 or newer.| |false| |optionalAssemblyInfo|Generate AssemblyInfo.cs.| |true| |optionalEmitDefaultValues|Set DataMember's EmitDefaultValue.| |false| |optionalMethodArgument|C# Optional method argument, e.g. void square(int x=10) (.net 4.0+ only).| |true| diff --git a/docs/generators/go-server.md b/docs/generators/go-server.md index 36ac78aea6d..440b3461b0f 100644 --- a/docs/generators/go-server.md +++ b/docs/generators/go-server.md @@ -13,6 +13,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |hideGenerationTimestamp|Hides the generation timestamp when files are generated.| |true| |packageName|Go package name (convention: lowercase).| |openapi| |packageVersion|Go package version.| |1.0.0| +|router|Specify the router which should be used.|
**mux**
mux
**chi**
chi
|mux| |serverPort|The network port the generated server binds to| |8080| |sourceFolder|source folder for generated code| |go| diff --git a/docs/generators/javascript-flowtyped.md b/docs/generators/javascript-flowtyped.md index eca0bf2e080..51ac05927d3 100644 --- a/docs/generators/javascript-flowtyped.md +++ b/docs/generators/javascript-flowtyped.md @@ -18,6 +18,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |npmRepository|Use this property to set an url your private npmRepo in the package.json| |null| |npmVersion|The version of your npm package. If not provided, using the version from the OpenAPI specification file.| |1.0.0| |nullSafeAdditionalProps|Set to make additional properties types declare that their indexer may return undefined| |false| +|paramNaming|Naming convention for parameters: '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| |snapshot|When setting this property to true, the version will be suffixed with -SNAPSHOT.yyyyMMddHHmm| |false| |sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| diff --git a/docs/generators/kotlin-server-deprecated.md b/docs/generators/kotlin-server-deprecated.md index 5499354747c..778b13ee7b3 100644 --- a/docs/generators/kotlin-server-deprecated.md +++ b/docs/generators/kotlin-server-deprecated.md @@ -80,16 +80,20 @@ These options may be applied as additional-properties (cli) or configOptions (pl
  • continue
  • do
  • else
  • +
  • external
  • false
  • for
  • fun
  • if
  • in
  • interface
  • +
  • internal
  • is
  • null
  • object
  • +
  • open
  • package
  • +
  • private
  • return
  • super
  • this
  • diff --git a/docs/generators/kotlin-server.md b/docs/generators/kotlin-server.md index b45dc3ffb4d..f6e6c260343 100644 --- a/docs/generators/kotlin-server.md +++ b/docs/generators/kotlin-server.md @@ -17,6 +17,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |featureConditionalHeaders|Avoid sending content if client already has same content, by checking ETag or LastModified properties.| |false| |featureHSTS|Avoid sending content if client already has same content, by checking ETag or LastModified properties.| |true| |featureLocations|Generates routes in a typed way, for both: constructing URLs and reading the parameters.| |true| +|featureMetrics|Enables metrics feature.| |true| |groupId|Generated artifact package's organization (i.e. maven groupId).| |org.openapitools| |library|library template (sub-template)|
    **ktor**
    ktor framework
    |ktor| |modelMutable|Create mutable models| |false| @@ -81,16 +82,20 @@ These options may be applied as additional-properties (cli) or configOptions (pl
  • continue
  • do
  • else
  • +
  • external
  • false
  • for
  • fun
  • if
  • in
  • interface
  • +
  • internal
  • is
  • null
  • object
  • +
  • open
  • package
  • +
  • private
  • return
  • super
  • this
  • diff --git a/docs/generators/kotlin-spring.md b/docs/generators/kotlin-spring.md index 3c62035e71e..58152432964 100644 --- a/docs/generators/kotlin-spring.md +++ b/docs/generators/kotlin-spring.md @@ -93,16 +93,20 @@ These options may be applied as additional-properties (cli) or configOptions (pl
  • continue
  • do
  • else
  • +
  • external
  • false
  • for
  • fun
  • if
  • in
  • interface
  • +
  • internal
  • is
  • null
  • object
  • +
  • open
  • package
  • +
  • private
  • return
  • super
  • this
  • diff --git a/docs/generators/kotlin-vertx.md b/docs/generators/kotlin-vertx.md index f92dadaf520..246ffa62a64 100644 --- a/docs/generators/kotlin-vertx.md +++ b/docs/generators/kotlin-vertx.md @@ -74,16 +74,20 @@ These options may be applied as additional-properties (cli) or configOptions (pl
  • continue
  • do
  • else
  • +
  • external
  • false
  • for
  • fun
  • if
  • in
  • interface
  • +
  • internal
  • is
  • null
  • object
  • +
  • open
  • package
  • +
  • private
  • return
  • super
  • this
  • diff --git a/docs/generators/kotlin.md b/docs/generators/kotlin.md index f4b0aceeb60..8f853b41cac 100644 --- a/docs/generators/kotlin.md +++ b/docs/generators/kotlin.md @@ -14,7 +14,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |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| |enumPropertyNaming|Naming convention for enum properties: 'camelCase', 'PascalCase', 'snake_case', 'UPPERCASE', and 'original'| |camelCase| |groupId|Generated artifact package's organization (i.e. maven groupId).| |org.openapitools| -|library|Library template (sub-template) to use|
    **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.
    **jvm-retrofit2**
    Platform: Java Virtual Machine. HTTP client: Retrofit 2.6.2.
    **multiplatform**
    Platform: Kotlin multiplatform. HTTP client: Ktor 1.2.4. JSON processing: Kotlinx Serialization: 0.12.0.
    |jvm-okhttp4| +|library|Library template (sub-template) to use|
    **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.
    **jvm-retrofit2**
    Platform: Java Virtual Machine. HTTP client: Retrofit 2.6.2.
    **multiplatform**
    Platform: Kotlin multiplatform. HTTP client: Ktor 1.6.0. JSON processing: Kotlinx Serialization: 1.2.1.
    |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| |packageName|Generated artifact package name.| |org.openapitools.client| @@ -25,6 +25,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |null| |sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |null| |sourceFolder|source folder for generated code| |src/main/kotlin| +|supportAndroidApiLevel25AndBelow|[WARNING] This flag will generate code that has a known security vulnerability. It uses `kotlin.io.createTempFile` instead of `java.nio.file.Files.createTempFile` in oder to support Android API level 25 and bellow. For more info, please check the following links https://github.com/OpenAPITools/openapi-generator/security/advisories/GHSA-23x4-m842-fmwf, https://github.com/OpenAPITools/openapi-generator/pull/9284| |false| |useCoroutines|Whether to use the Coroutines adapter with the retrofit2 library.| |false| |useRxJava|Whether to use the RxJava adapter with the retrofit2 library.| |false| |useRxJava2|Whether to use the RxJava2 adapter with the retrofit2 library.| |false| @@ -83,16 +84,20 @@ These options may be applied as additional-properties (cli) or configOptions (pl
  • continue
  • do
  • else
  • +
  • external
  • false
  • for
  • fun
  • if
  • in
  • interface
  • +
  • internal
  • is
  • null
  • object
  • +
  • open
  • package
  • +
  • private
  • return
  • super
  • this
  • diff --git a/docs/generators/php-mezzio-ph.md b/docs/generators/php-mezzio-ph.md index f691e8f57fb..93f31d7fbca 100644 --- a/docs/generators/php-mezzio-ph.md +++ b/docs/generators/php-mezzio-ph.md @@ -15,6 +15,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |invokerPackage|The main namespace to use for all classes. e.g. Yay\Pets| |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| |modelPackage|package for generated models| |null| +|modern|use modern language features (generated code will require PHP 8.0)| |false| |packageName|The main package name for classes. e.g. GeneratedPetstore| |null| |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| diff --git a/docs/generators/powershell.md b/docs/generators/powershell.md index a9c14eab47d..c822e241889 100644 --- a/docs/generators/powershell.md +++ b/docs/generators/powershell.md @@ -13,6 +13,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |discardReadOnly|Set discardReadonly to true to generate the Initialize cmdlet without readonly parameters| |null| |iconUri|A URL to an icon representing the generated PowerShell module| |null| |licenseUri|A URL to the license for the generated PowerShell module| |null| +|modelsCmdletVerb|Verb to be used when generating the Models cmdlets in the examples.| |Initialize| |packageGuid|GUID for PowerShell module (e.g. a27b908d-2a20-467f-bc32-af6f3a654ac5). A random GUID will be generated by default.| |null| |packageName|Client package name (e.g. PSTwitter).| |PSOpenAPITools| |packageVersion|Package version (e.g. 0.1.2).| |0.1.2| @@ -21,6 +22,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |releaseNotes|Release notes of the generated PowerShell module| |null| |skipVerbParsing|Set skipVerbParsing to not try get powershell verbs of operation names| |null| |tags|Tags applied to the generated PowerShell module. These help with module discovery in online galleries| |null| +|useClassNameInModelsExamples|Use classname instead of name when generating the Models cmdlets in the examples.| |true| |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.| |null| ## IMPORT MAPPING diff --git a/docs/generators/python-aiohttp.md b/docs/generators/python-aiohttp.md index 7c46da0b5b4..9adef96ba51 100644 --- a/docs/generators/python-aiohttp.md +++ b/docs/generators/python-aiohttp.md @@ -23,6 +23,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| |supportPython2|support python2. This option has been deprecated and will be removed in the 5.x release.| |false| |useNose|use the nose test framework| |false| +|usePythonSrcRootInImports|include pythonSrcRoot in import namespaces.| |false| ## IMPORT MAPPING diff --git a/docs/generators/python-blueplanet.md b/docs/generators/python-blueplanet.md index 81c9b89cbf3..ba461d1822f 100644 --- a/docs/generators/python-blueplanet.md +++ b/docs/generators/python-blueplanet.md @@ -23,6 +23,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| |supportPython2|support python2. This option has been deprecated and will be removed in the 5.x release.| |false| |useNose|use the nose test framework| |false| +|usePythonSrcRootInImports|include pythonSrcRoot in import namespaces.| |false| ## IMPORT MAPPING diff --git a/docs/generators/python-fastapi.md b/docs/generators/python-fastapi.md new file mode 100644 index 00000000000..2143321f2d7 --- /dev/null +++ b/docs/generators/python-fastapi.md @@ -0,0 +1,211 @@ +--- +title: Config Options for python-fastapi +sidebar_label: python-fastapi +--- + +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| +|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| +|packageName|python package name (convention: snake_case).| |openapi_server| +|packageVersion|python package version.| |1.0.0| +|prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| +|serverPort|TCP port to listen to in app.run| |8080| +|sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| +|sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| + +## IMPORT MAPPING + +| Type/Alias | Imports | +| ---------- | ------- | + + +## INSTANTIATION TYPES + +| Type/Alias | Instantiated By | +| ---------- | --------------- | + + +## LANGUAGE PRIMITIVES + + + +## RESERVED WORDS + + + +## 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 +|Array|✓|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 + +### 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 + +### Wire Format Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|JSON|✓|OAS2,OAS3 +|XML|✓|OAS2,OAS3 +|PROTOBUF|✗|ToolingExtension +|Custom|✗|OAS2,OAS3 diff --git a/docs/generators/python-flask.md b/docs/generators/python-flask.md index 92bf4fdb97f..9e69fa44302 100644 --- a/docs/generators/python-flask.md +++ b/docs/generators/python-flask.md @@ -23,6 +23,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| |supportPython2|support python2. This option has been deprecated and will be removed in the 5.x release.| |false| |useNose|use the nose test framework| |false| +|usePythonSrcRootInImports|include pythonSrcRoot in import namespaces.| |false| ## IMPORT MAPPING diff --git a/docs/generators/swift5.md b/docs/generators/swift5.md index 9774b434f13..96cfe8424c0 100644 --- a/docs/generators/swift5.md +++ b/docs/generators/swift5.md @@ -11,10 +11,13 @@ These options may be applied as additional-properties (cli) or configOptions (pl |apiNamePrefix|Prefix that will be appended to all API names ('tags'). Default: empty string. e.g. Pet => Pet.| |null| |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| +|generateModelAdditionalProperties|Generate model additional properties (default: true)| |true| +|hashableModels|Make hashable models (default: true)| |true| |hideGenerationTimestamp|Hides the generation timestamp when files are generated.| |true| |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| |lenientTypeCast|Accept and cast values for simple types (string->bool, string->int, int->string)| |false| -|library|Library template (sub-template) to use|
    **urlsession**
    [DEFAULT] HTTP client: URLSession
    **alamofire**
    HTTP client: Alamofire
    |urlsession| +|library|Library template (sub-template) to use|
    **urlsession**
    [DEFAULT] HTTP client: URLSession
    **alamofire**
    HTTP client: Alamofire
    **vapor**
    HTTP client: Vapor
    |urlsession| +|mapFileBinaryToData|[WARNING] This option will be removed and enabled by default in the future once we've enhanced the code to work with `Data` in all the different situations. Map File and Binary to Data (default: false)| |false| |nonPublicApi|Generates code with reduced access modifiers; allows embedding elsewhere without exposing non-public API calls to consumers.(default: false)| |null| |objcCompatible|Add additional properties and methods for Objective-C compatibility (default: false)| |null| |podAuthors|Authors used for Podspec| |null| @@ -36,6 +39,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |swiftPackagePath|Set a custom source path instead of OpenAPIClient/Classes/OpenAPIs.| |null| |swiftUseApiNamespace|Flag to make all the API classes inner-class of {{projectName}}API| |null| |useBacktickEscapes|Escape reserved words using backticks (default: false)| |false| +|useClasses|Use final classes for models instead of structs (default: false)| |false| |useSPMFileStructure|Use SPM file structure and set the source path to Sources/{{projectName}} (default: false).| |null| ## IMPORT MAPPING diff --git a/docs/generators/tiny-cpp.md b/docs/generators/tiny-cpp.md new file mode 100644 index 00000000000..f7f6a0385ca --- /dev/null +++ b/docs/generators/tiny-cpp.md @@ -0,0 +1,243 @@ +--- +title: Config Options for tiny-cpp +sidebar_label: tiny-cpp +--- + +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| +|controller|name of microcontroller (e.g esp32 or esp8266)| |esp32| +|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| +|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| +|reservedWordPrefix|Prefix to prepend to reserved words in order to avoid conflicts| |r_| +|sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| +|sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| +|variableNameFirstCharacterUppercase|Make first character of variable name uppercase (eg. value -> Value)| |true| + +## IMPORT MAPPING + +| Type/Alias | Imports | +| ---------- | ------- | + + +## INSTANTIATION TYPES + +| Type/Alias | Instantiated By | +| ---------- | --------------- | + + +## LANGUAGE PRIMITIVES + + + +## RESERVED WORDS + + + +## 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 +|Array|✓|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 + +### 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 + +### Wire Format Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|JSON|✓|OAS2,OAS3 +|XML|✗|OAS2,OAS3 +|PROTOBUF|✗|ToolingExtension +|Custom|✗|OAS2,OAS3 diff --git a/docs/generators/typescript-angular.md b/docs/generators/typescript-angular.md index 6916e3f662c..67341026ceb 100644 --- a/docs/generators/typescript-angular.md +++ b/docs/generators/typescript-angular.md @@ -24,6 +24,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |npmRepository|Use this property to set an url your private npmRepo in the package.json| |null| |npmVersion|The version of your npm package. If not provided, using the version from the OpenAPI specification file.| |1.0.0| |nullSafeAdditionalProps|Set to make additional properties types declare that their indexer may return undefined| |false| +|paramNaming|Naming convention for parameters: '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| |providedIn|Use this property to provide Injectables in wanted level (it is only valid in angular version greater or equal to 9.0.0).|
    **root**
    The application-level injector in most apps.
    **none**
    No providedIn (same as providedInRoot=false)
    **any**
    Provides a unique instance in each lazy loaded module while all eagerly loaded modules share one instance.
    **platform**
    A special singleton platform injector shared by all applications on the page.
    |root| |providedInRoot|Use this property to provide Injectables in root (it is only valid in angular version greater or equal to 6.0.0). IMPORTANT: Deprecated for angular version greater or equal to 9.0.0, use **providedIn** instead.| |false| diff --git a/docs/generators/typescript-angularjs-deprecated.md b/docs/generators/typescript-angularjs-deprecated.md index 889c9fb3d2d..9363a6958da 100644 --- a/docs/generators/typescript-angularjs-deprecated.md +++ b/docs/generators/typescript-angularjs-deprecated.md @@ -15,6 +15,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |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| |modelPropertyNaming|Naming convention for the property: 'camelCase', 'PascalCase', 'snake_case' and 'original', which keeps the original name. Only change it if you provide your own run-time code for (de-)serialization of models| |original| |nullSafeAdditionalProps|Set to make additional properties types declare that their indexer may return undefined| |false| +|paramNaming|Naming convention for parameters: '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| diff --git a/docs/generators/typescript-aurelia.md b/docs/generators/typescript-aurelia.md index a1f568cfb65..aaad28dd75b 100644 --- a/docs/generators/typescript-aurelia.md +++ b/docs/generators/typescript-aurelia.md @@ -17,6 +17,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |npmName|The name under which you want to publish generated npm package. Required to generate a full package| |null| |npmVersion|The version of your npm package. If not provided, using the version from the OpenAPI specification file.| |1.0.0| |nullSafeAdditionalProps|Set to make additional properties types declare that their indexer may return undefined| |false| +|paramNaming|Naming convention for parameters: '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| |snapshot|When setting this property to true, the version will be suffixed with -SNAPSHOT.yyyyMMddHHmm| |false| |sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| diff --git a/docs/generators/typescript-axios.md b/docs/generators/typescript-axios.md index 5bddee54189..3e9f31aed5f 100644 --- a/docs/generators/typescript-axios.md +++ b/docs/generators/typescript-axios.md @@ -18,6 +18,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |npmRepository|Use this property to set an url of your private npmRepo in the package.json| |null| |npmVersion|The version of your npm package. If not provided, using the version from the OpenAPI specification file.| |1.0.0| |nullSafeAdditionalProps|Set to make additional properties types declare that their indexer may return undefined| |false| +|paramNaming|Naming convention for parameters: '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| |snapshot|When setting this property to true, the version will be suffixed with -SNAPSHOT.yyyyMMddHHmm| |false| |sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| diff --git a/docs/generators/typescript-fetch.md b/docs/generators/typescript-fetch.md index 2acbe8c7741..f8e9cd2328a 100644 --- a/docs/generators/typescript-fetch.md +++ b/docs/generators/typescript-fetch.md @@ -18,8 +18,10 @@ These options may be applied as additional-properties (cli) or configOptions (pl |npmRepository|Use this property to set an url your private npmRepo in the package.json| |null| |npmVersion|The version of your npm package. If not provided, using the version from the OpenAPI specification file.| |1.0.0| |nullSafeAdditionalProps|Set to make additional properties types declare that their indexer may return undefined| |false| +|paramNaming|Naming convention for parameters: 'camelCase', 'PascalCase', 'snake_case' and 'original', which keeps the original name| |camelCase| |prefixParameterInterfaces|Setting this property to true will generate parameter interface declarations prefixed with API class name to avoid name conflicts.| |false| |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| +|sagasAndRecords|Setting this property to true will generate additional files for use with redux-saga and immutablejs.| |false| |snapshot|When setting this property to true, the version will be suffixed with -SNAPSHOT.yyyyMMddHHmm| |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| diff --git a/docs/generators/typescript-inversify.md b/docs/generators/typescript-inversify.md index 41df5d2b2b7..38077cb2b40 100644 --- a/docs/generators/typescript-inversify.md +++ b/docs/generators/typescript-inversify.md @@ -18,6 +18,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |npmRepository|Use this property to set an url your private npmRepo in the package.json| |null| |npmVersion|The version of your npm package. If not provided, using the version from the OpenAPI specification file.| |1.0.0| |nullSafeAdditionalProps|Set to make additional properties types declare that their indexer may return undefined| |false| +|paramNaming|Naming convention for parameters: '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| |snapshot|When setting this property to true, the version will be suffixed with -SNAPSHOT.yyyyMMddHHmm| |false| |sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| diff --git a/docs/generators/typescript-jquery.md b/docs/generators/typescript-jquery.md index 33713bf6f85..fcff7abe194 100644 --- a/docs/generators/typescript-jquery.md +++ b/docs/generators/typescript-jquery.md @@ -19,6 +19,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |npmRepository|Use this property to set an url your private npmRepo in the package.json| |null| |npmVersion|The version of your npm package. If not provided, using the version from the OpenAPI specification file.| |1.0.0| |nullSafeAdditionalProps|Set to make additional properties types declare that their indexer may return undefined| |false| +|paramNaming|Naming convention for parameters: '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| |snapshot|When setting this property to true, the version will be suffixed with -SNAPSHOT.yyyyMMddHHmm| |false| |sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| diff --git a/docs/generators/typescript-nestjs.md b/docs/generators/typescript-nestjs.md index 0697f2266f6..50e9acb1675 100644 --- a/docs/generators/typescript-nestjs.md +++ b/docs/generators/typescript-nestjs.md @@ -22,6 +22,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |npmRepository|Use this property to set an url your private npmRepo in the package.json| |null| |npmVersion|The version of your npm package. If not provided, using the version from the OpenAPI specification file.| |1.0.0| |nullSafeAdditionalProps|Set to make additional properties types declare that their indexer may return undefined| |false| +|paramNaming|Naming convention for parameters: '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| |serviceFileSuffix|The suffix of the file of the generated service (service<suffix>.ts).| |.service| |serviceSuffix|The suffix of the generated service.| |Service| diff --git a/docs/generators/typescript-node.md b/docs/generators/typescript-node.md index 8c755639588..388dfd551bd 100644 --- a/docs/generators/typescript-node.md +++ b/docs/generators/typescript-node.md @@ -18,6 +18,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |npmRepository|Use this property to set an url your private npmRepo in the package.json| |null| |npmVersion|The version of your npm package. If not provided, using the version from the OpenAPI specification file.| |1.0.0| |nullSafeAdditionalProps|Set to make additional properties types declare that their indexer may return undefined| |false| +|paramNaming|Naming convention for parameters: '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| |snapshot|When setting this property to true, the version will be suffixed with -SNAPSHOT.yyyyMMddHHmm| |false| |sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| diff --git a/docs/generators/typescript-redux-query.md b/docs/generators/typescript-redux-query.md index f35e028ff4b..dd79fa1a433 100644 --- a/docs/generators/typescript-redux-query.md +++ b/docs/generators/typescript-redux-query.md @@ -18,6 +18,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |npmRepository|Use this property to set an url your private npmRepo in the package.json| |null| |npmVersion|The version of your npm package. If not provided, using the version from the OpenAPI specification file.| |1.0.0| |nullSafeAdditionalProps|Set to make additional properties types declare that their indexer may return undefined| |false| +|paramNaming|Naming convention for parameters: '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| |snapshot|When setting this property to true, the version will be suffixed with -SNAPSHOT.yyyyMMddHHmm| |false| |sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| diff --git a/docs/generators/typescript-rxjs.md b/docs/generators/typescript-rxjs.md index 05909b89bd2..50999179985 100644 --- a/docs/generators/typescript-rxjs.md +++ b/docs/generators/typescript-rxjs.md @@ -18,6 +18,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |npmRepository|Use this property to set an url your private npmRepo in the package.json| |null| |npmVersion|The version of your npm package. If not provided, using the version from the OpenAPI specification file.| |1.0.0| |nullSafeAdditionalProps|Set to make additional properties types declare that their indexer may return undefined| |false| +|paramNaming|Naming convention for parameters: '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| |snapshot|When setting this property to true, the version will be suffixed with -SNAPSHOT.yyyyMMddHHmm| |false| |sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| diff --git a/docs/generators/wsdl-schema.md b/docs/generators/wsdl-schema.md new file mode 100644 index 00000000000..7842f856749 --- /dev/null +++ b/docs/generators/wsdl-schema.md @@ -0,0 +1,150 @@ +--- +title: Config Options for wsdl-schema +sidebar_label: wsdl-schema +--- + +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| +|hostname|the hostname of the service| |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| +|serviceName|service name for the wsdl| |null| +|soapPath|basepath of the soap services| |null| +|sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| +|sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| + +## IMPORT MAPPING + +| Type/Alias | Imports | +| ---------- | ------- | + + +## INSTANTIATION TYPES + +| Type/Alias | Instantiated By | +| ---------- | --------------- | + + +## LANGUAGE PRIMITIVES + + + +## RESERVED WORDS + + + +## 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 +|Array|✓|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 + +### 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 + +### Wire Format Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|JSON|✓|OAS2,OAS3 +|XML|✓|OAS2,OAS3 +|PROTOBUF|✗|ToolingExtension +|Custom|✗|OAS2,OAS3 diff --git a/docs/plugins.md b/docs/plugins.md index 691c5fa85d1..c9fbbe5b548 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -45,7 +45,7 @@ For full details of all options, see the [plugin README](https://github.com/Open ### Dependencies -The generated models use commonly use Swagger v2 annotations like `@ApiModelProperty`. A user may add Swagger v3 annotations: +The generated models use commonly used Swagger v2 annotations like `@ApiModelProperty`. A user may add Swagger v3 annotations: ```xml diff --git a/modules/openapi-generator-gradle-plugin/README.adoc b/modules/openapi-generator-gradle-plugin/README.adoc index 08b09304900..86c2df36c1f 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 "5.1.0" + id "org.openapi.generator" version "5.1.1" } ---- @@ -113,7 +113,7 @@ buildscript { // url "https://plugins.gradle.org/m2/" } dependencies { - classpath "org.openapitools:openapi-generator-gradle-plugin:5.1.0" + classpath "org.openapitools:openapi-generator-gradle-plugin:5.1.1" } } diff --git a/modules/openapi-generator-gradle-plugin/src/main/kotlin/org/openapitools/generator/gradle/plugin/tasks/ValidateTask.kt b/modules/openapi-generator-gradle-plugin/src/main/kotlin/org/openapitools/generator/gradle/plugin/tasks/ValidateTask.kt index 3d0cbab2b06..6f3038e4e29 100644 --- a/modules/openapi-generator-gradle-plugin/src/main/kotlin/org/openapitools/generator/gradle/plugin/tasks/ValidateTask.kt +++ b/modules/openapi-generator-gradle-plugin/src/main/kotlin/org/openapitools/generator/gradle/plugin/tasks/ValidateTask.kt @@ -56,11 +56,11 @@ import org.openapitools.codegen.validations.oas.RuleConfiguration open class ValidateTask : DefaultTask() { @get:InputFile @PathSensitive(PathSensitivity.RELATIVE) - var inputSpec = project.objects.property() + val inputSpec = project.objects.property() @Optional @Input - var recommend = project.objects.property() + val recommend = project.objects.property() @Suppress("unused") @get:Internal @@ -128,4 +128,4 @@ open class ValidateTask : DefaultTask() { out.println("Spec is valid.") } } -} \ No newline at end of file +} diff --git a/modules/openapi-generator-gradle-plugin/src/test/kotlin/ValidateTaskDslTest.kt b/modules/openapi-generator-gradle-plugin/src/test/kotlin/ValidateTaskDslTest.kt index 2b06e853192..94ae68ab3af 100644 --- a/modules/openapi-generator-gradle-plugin/src/test/kotlin/ValidateTaskDslTest.kt +++ b/modules/openapi-generator-gradle-plugin/src/test/kotlin/ValidateTaskDslTest.kt @@ -3,6 +3,8 @@ package org.openapitools.generator.gradle.plugin import org.gradle.testkit.runner.GradleRunner import org.gradle.testkit.runner.TaskOutcome.FAILED import org.gradle.testkit.runner.TaskOutcome.SUCCESS +import org.gradle.util.GradleVersion +import org.testng.annotations.DataProvider import org.testng.annotations.Test import java.io.File import kotlin.test.assertEquals @@ -11,8 +13,25 @@ import kotlin.test.assertTrue class ValidateTaskDslTest : TestBase() { override var temp: File = createTempDir(javaClass.simpleName) - @Test - fun `openApiValidate should fail on non-file spec`() { + @DataProvider(name = "gradle_version_provider") + fun gradleVersionProvider(): Array> = arrayOf( + arrayOf(null), // uses the version of Gradle used to build the plugin itself + arrayOf("5.6.4"), + arrayOf("6.9"), + arrayOf("7.0")) + + private fun getGradleRunner(gradleVersion: String?): GradleRunner { + val gradleRunner = GradleRunner.create() + return if (gradleVersion.isNullOrBlank()) { + //Use the current version of Gradle + gradleRunner + } else { + gradleRunner.withGradleVersion(gradleVersion) + } + } + + @Test(dataProvider = "gradle_version_provider") + fun `openApiValidate should fail on non-file spec`(gradleVersion: String?) { // Arrange withProject(""" | plugins { @@ -25,20 +44,28 @@ class ValidateTaskDslTest : TestBase() { """.trimMargin()) // Act - val result = GradleRunner.create() + val result = getGradleRunner(gradleVersion) .withProjectDir(temp) .withArguments("openApiValidate") .withPluginClasspath() .buildAndFail() // Assert - assertTrue(result.output.contains("some_location' specified for property 'inputSpec' does not exist"), "Unexpected/no message presented to the user for a spec pointing to an invalid URI.") + val gradleActualVersion = gradleVersion ?: GradleVersion.current().version + val gradleVersionParts = gradleActualVersion.split(".") + val isBeforeGradle7 = (gradleVersionParts.isEmpty() || gradleVersionParts[0].toInt() < 7) + val expectedMessage = if (isBeforeGradle7) { + "some_location' specified for property 'inputSpec' does not exist" + } else { + "An input file was expected to be present but it doesn't exist." + } + assertTrue(result.output.contains(expectedMessage), "Unexpected/no message presented to the user for a spec pointing to an invalid URI.") assertEquals(FAILED, result.task(":openApiValidate")?.outcome, "Expected a failed run, but found ${result.task(":openApiValidate")?.outcome}") } - @Test - fun `openApiValidate should succeed on valid spec`() { + @Test(dataProvider = "gradle_version_provider") + fun `openApiValidate should succeed on valid spec`(gradleVersion: String?) { // Arrange val projectFiles = mapOf( "spec.yaml" to javaClass.classLoader.getResourceAsStream("specs/petstore-v3.0.yaml") @@ -55,7 +82,7 @@ class ValidateTaskDslTest : TestBase() { """.trimMargin(), projectFiles) // Act - val result = GradleRunner.create() + val result = getGradleRunner(gradleVersion) .withProjectDir(temp) .withArguments("openApiValidate") .withPluginClasspath() @@ -67,8 +94,8 @@ class ValidateTaskDslTest : TestBase() { "Expected a successful run, but found ${result.task(":openApiValidate")?.outcome}") } - @Test - fun `openApiValidate should fail on invalid spec`() { + @Test(dataProvider = "gradle_version_provider") + fun `openApiValidate should fail on invalid spec`(gradleVersion: String?) { // Arrange val projectFiles = mapOf( "spec.yaml" to javaClass.classLoader.getResourceAsStream("specs/petstore-v3.0-invalid.yaml") @@ -84,7 +111,7 @@ class ValidateTaskDslTest : TestBase() { """.trimMargin(), projectFiles) // Act - val result = GradleRunner.create() + val result = getGradleRunner(gradleVersion) .withProjectDir(temp) .withArguments("openApiValidate") .withPluginClasspath() @@ -96,4 +123,4 @@ class ValidateTaskDslTest : TestBase() { "Expected a failed run, but found ${result.task(":openApiValidate")?.outcome}") } -} \ No newline at end of file +} diff --git a/modules/openapi-generator-maven-plugin/examples/kotlin.xml b/modules/openapi-generator-maven-plugin/examples/kotlin.xml index 3c3972591cb..57c046022a7 100644 --- a/modules/openapi-generator-maven-plugin/examples/kotlin.xml +++ b/modules/openapi-generator-maven-plugin/examples/kotlin.xml @@ -219,6 +219,13 @@ okhttp 4.2.2 + + + + org.jetbrains.kotlin + kotlin-stdlib + ${kotlin.version} + @@ -229,7 +236,7 @@ 2.7 1.0.0 4.8.1 - 1.3.50 + 1.5.10 1.8 1.8.0 2.2 diff --git a/modules/openapi-generator-online/src/main/java/org/openapitools/codegen/online/service/Generator.java b/modules/openapi-generator-online/src/main/java/org/openapitools/codegen/online/service/Generator.java index be21b970d7a..7cf052e3083 100644 --- a/modules/openapi-generator-online/src/main/java/org/openapitools/codegen/online/service/Generator.java +++ b/modules/openapi-generator-online/src/main/java/org/openapitools/codegen/online/service/Generator.java @@ -153,7 +153,7 @@ public class Generator { List files = new DefaultGenerator().opts(clientOptInput).generate(); if (files.size() > 0) { List filesToAdd = new ArrayList<>(); - LOGGER.debug("adding to " + outputFolder); + LOGGER.debug("adding to {}", outputFolder); filesToAdd.add(new File(outputFolder)); ZipUtil zip = new ZipUtil(); zip.compressFiles(filesToAdd, outputFilename); 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 631ff47eedb..bb7aa069fe7 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 @@ -184,6 +184,9 @@ public class CodegenConstants { public static final String OPTIONAL_EMIT_DEFAULT_VALUES = "optionalEmitDefaultValues"; public static final String OPTIONAL_EMIT_DEFAULT_VALUES_DESC = "Set DataMember's EmitDefaultValue."; + public static final String OPTIONAL_CONDITIONAL_SERIALIZATION = "conditionalSerialization"; + public static final String OPTIONAL_CONDITIONAL_SERIALIZATION_DESC = "Serialize only those properties which are initialized by user, accepted values are true or false, default value is false."; + public static final String NETCORE_PROJECT_FILE = "netCoreProjectFile"; public static final String NETCORE_PROJECT_FILE_DESC = "Use the new format (.NET Core) for .NET project files (.csproj)."; @@ -205,12 +208,20 @@ public class CodegenConstants { public static final String MODEL_PROPERTY_NAMING = "modelPropertyNaming"; public static final String MODEL_PROPERTY_NAMING_DESC = "Naming convention for the property: 'camelCase', 'PascalCase', 'snake_case' and 'original', which keeps the original name"; + public static final String PARAM_NAMING = "paramNaming"; + public static final String PARAM_NAMING_DESC = "Naming convention for parameters: 'camelCase', 'PascalCase', 'snake_case' and 'original', which keeps the original name"; + public static final String DOTNET_FRAMEWORK = "targetFramework"; public static final String DOTNET_FRAMEWORK_DESC = "The target .NET framework version. To target multiple frameworks, use `;` as the separator, e.g. `netstandard2.1;netcoreapp3.0`"; + public static final String NULLABLE_REFERENCE_TYPES = "nullableReferenceTypes"; + public static final String NULLABLE_REFERENCE_TYPES_DESC = "Use nullable annotations in the project. Only supported on C# 8 / ASP.NET Core 3.0 or newer."; + public static final String TEMPLATING_ENGINE = "templatingEngine"; public static final String TEMPLATING_ENGINE_DESC = "The templating engine plugin to use: \"mustache\" (default) or \"handlebars\" (beta)"; + public static enum PARAM_NAMING_TYPE {camelCase, PascalCase, snake_case, original} + public static enum MODEL_PROPERTY_NAMING_TYPE {camelCase, PascalCase, snake_case, original} public static enum ENUM_PROPERTY_NAMING_TYPE {camelCase, PascalCase, snake_case, original, UPPERCASE} @@ -309,6 +320,12 @@ public class CodegenConstants { public static final String REMOVE_OPERATION_ID_PREFIX = "removeOperationIdPrefix"; public static final String REMOVE_OPERATION_ID_PREFIX_DESC = "Remove prefix of operationId, e.g. config_getId => getId"; + public static final String REMOVE_OPERATION_ID_PREFIX_DELIMITER = "removeOperationIdPrefixDelimiter"; + public static final String REMOVE_OPERATION_ID_PREFIX_DELIMITER_DESC = "Character to use as a delimiter for the prefix. Default: '_'"; + + public static final String REMOVE_OPERATION_ID_PREFIX_COUNT = "removeOperationIdPrefixCount"; + public static final String REMOVE_OPERATION_ID_PREFIX_COUNT_DESC = "Count of delimiter for the prefix. Use -1 for last Default: 1"; + public static final String SKIP_OPERATION_EXAMPLE = "skipOperationExample"; public static final String SKIP_OPERATION_EXAMPLE_DESC = "Skip examples defined in operations to avoid out of memory errors."; 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 e7a3adce6a3..a441659434a 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 @@ -64,7 +64,7 @@ public class CodegenModel implements IJsonSchemaValidationProperties { public String defaultValue; public String arrayModelType; public boolean isAlias; // Is this effectively an alias of another simple type - public boolean isString, isInteger, isLong, isNumber, isNumeric, isFloat, isDouble, isDate, isDateTime; + public boolean isString, isInteger, isLong, isNumber, isNumeric, isFloat, isDouble, isDate, isDateTime, isShort, isUnboundedInteger, isBoolean; private boolean additionalPropertiesIsAnyType; public List vars = new ArrayList(); // all properties (without parent's properties) public List allVars = new ArrayList(); // all properties (with parent's properties) @@ -606,6 +606,30 @@ public class CodegenModel implements IJsonSchemaValidationProperties { this.isArray = isArray; } + @Override + public boolean getIsShort() { return isShort; } + + @Override + public void setIsShort(boolean isShort) { + this.isShort = isShort; + } + + @Override + public boolean getIsBoolean() { return isBoolean; } + + @Override + public void setIsBoolean(boolean isBoolean) { + this.isBoolean= isBoolean; + } + + @Override + public boolean getIsUnboundedInteger() { return isUnboundedInteger; } + + @Override + public void setIsUnboundedInteger(boolean isUnboundedInteger) { + this.isUnboundedInteger = isUnboundedInteger; + } + @Override public CodegenProperty getAdditionalProperties() { return additionalProperties; } @@ -752,7 +776,10 @@ public class CodegenModel implements IJsonSchemaValidationProperties { return isAlias == that.isAlias && isString == that.isString && isInteger == that.isInteger && + isShort == that.isShort && isLong == that.isLong && + isUnboundedInteger == that.isUnboundedInteger && + isBoolean == that.isBoolean && isNumber == that.isNumber && isNumeric == that.isNumeric && isFloat == that.isFloat && @@ -839,7 +866,7 @@ public class CodegenModel implements IJsonSchemaValidationProperties { getDescription(), getClassVarName(), getModelJson(), getDataType(), getXmlPrefix(), getXmlNamespace(), getXmlName(), getClassFilename(), getUnescapedDescription(), getDiscriminator(), getDefaultValue(), getArrayModelType(), isAlias, isString, isInteger, isLong, isNumber, isNumeric, isFloat, isDouble, - isDate, isDateTime, isNull, hasValidation, + isDate, isDateTime, isNull, hasValidation, isShort, isUnboundedInteger, isBoolean, getVars(), getAllVars(), getRequiredVars(), getOptionalVars(), getReadOnlyVars(), getReadWriteVars(), getParentVars(), getAllowableValues(), getMandatory(), getAllMandatory(), getImports(), hasVars, isEmptyVars(), hasMoreModels, hasEnums, isEnum, isNullable, hasRequired, hasOptional, isArray, @@ -881,7 +908,10 @@ public class CodegenModel implements IJsonSchemaValidationProperties { sb.append(", isAlias=").append(isAlias); sb.append(", isString=").append(isString); sb.append(", isInteger=").append(isInteger); + sb.append(", isShort=").append(isShort); sb.append(", isLong=").append(isLong); + sb.append(", isUnboundedInteger=").append(isUnboundedInteger); + sb.append(", isBoolean=").append(isBoolean); sb.append(", isNumber=").append(isNumber); sb.append(", isNumeric=").append(isNumeric); sb.append(", isFloat=").append(isFloat); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenParameter.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenParameter.java index 326785046d9..874ac93d152 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenParameter.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenParameter.java @@ -35,7 +35,7 @@ public class CodegenParameter implements IJsonSchemaValidationProperties { public String example; // example value (x-example) public String jsonSchema; public boolean isString, isNumeric, isInteger, isLong, isNumber, isFloat, isDouble, isDecimal, isByteArray, isBinary, - isBoolean, isDate, isDateTime, isUuid, isUri, isEmail, isFreeFormObject, isAnyType; + isBoolean, isDate, isDateTime, isUuid, isUri, isEmail, isFreeFormObject, isAnyType, isShort, isUnboundedInteger; public boolean isArray, isMap; public boolean isFile; public boolean isEnum; @@ -184,7 +184,9 @@ public class CodegenParameter implements IJsonSchemaValidationProperties { output.isString = this.isString; output.isNumeric = this.isNumeric; output.isInteger = this.isInteger; + output.isShort = this.isShort; output.isLong = this.isLong; + output.isUnboundedInteger = this.isUnboundedInteger; output.isDouble = this.isDouble; output.isDecimal = this.isDecimal; output.isFloat = this.isFloat; @@ -209,7 +211,7 @@ public class CodegenParameter implements IJsonSchemaValidationProperties { @Override public int hashCode() { - return Objects.hash(isFormParam, isQueryParam, isPathParam, isHeaderParam, isCookieParam, isBodyParam, isContainer, isCollectionFormatMulti, isPrimitiveType, isModel, isExplode, baseName, paramName, dataType, datatypeWithEnum, dataFormat, collectionFormat, description, unescapedDescription, baseType, defaultValue, enumName, style, isDeepObject, example, jsonSchema, isString, isNumeric, isInteger, isLong, isNumber, isFloat, isDouble, isDecimal, isByteArray, isBinary, isBoolean, isDate, isDateTime, isUuid, isUri, isEmail, isFreeFormObject, isAnyType, isArray, isMap, isFile, isEnum, _enum, allowableValues, items, mostInnerItems, additionalProperties, vars, requiredVars, vendorExtensions, hasValidation, getMaxProperties(), getMinProperties(), isNullable, required, getMaximum(), getExclusiveMaximum(), getMinimum(), getExclusiveMinimum(), getMaxLength(), getMinLength(), getPattern(), getMaxItems(), getMinItems(), getUniqueItems(), contentType, multipleOf, isNull, additionalPropertiesIsAnyType, hasVars, hasRequired); + return Objects.hash(isFormParam, isQueryParam, isPathParam, isHeaderParam, isCookieParam, isBodyParam, isContainer, isCollectionFormatMulti, isPrimitiveType, isModel, isExplode, baseName, paramName, dataType, datatypeWithEnum, dataFormat, collectionFormat, description, unescapedDescription, baseType, defaultValue, enumName, style, isDeepObject, example, jsonSchema, isString, isNumeric, isInteger, isLong, isNumber, isFloat, isDouble, isDecimal, isByteArray, isBinary, isBoolean, isDate, isDateTime, isUuid, isUri, isEmail, isFreeFormObject, isAnyType, isArray, isMap, isFile, isEnum, _enum, allowableValues, items, mostInnerItems, additionalProperties, vars, requiredVars, vendorExtensions, hasValidation, getMaxProperties(), getMinProperties(), isNullable, required, getMaximum(), getExclusiveMaximum(), getMinimum(), getExclusiveMinimum(), getMaxLength(), getMinLength(), getPattern(), getMaxItems(), getMinItems(), getUniqueItems(), contentType, multipleOf, isNull, additionalPropertiesIsAnyType, hasVars, hasRequired, isShort, isUnboundedInteger); } @Override @@ -231,7 +233,9 @@ public class CodegenParameter implements IJsonSchemaValidationProperties { isString == that.isString && isNumeric == that.isNumeric && isInteger == that.isInteger && + isShort == that.isShort && isLong == that.isLong && + isUnboundedInteger == that.isUnboundedInteger && isNumber == that.isNumber && isFloat == that.isFloat && isDouble == that.isDouble && @@ -328,7 +332,9 @@ public class CodegenParameter implements IJsonSchemaValidationProperties { sb.append(", isString=").append(isString); sb.append(", isNumeric=").append(isNumeric); sb.append(", isInteger=").append(isInteger); + sb.append(", isShort=").append(isShort); sb.append(", isLong=").append(isLong); + sb.append(", isUnboundedInteger=").append(isUnboundedInteger); sb.append(", isNumber=").append(isNumber); sb.append(", isFloat=").append(isFloat); sb.append(", isDouble=").append(isDouble); @@ -560,6 +566,30 @@ public class CodegenParameter implements IJsonSchemaValidationProperties { this.isArray = isArray; } + @Override + public boolean getIsShort() { return isShort; } + + @Override + public void setIsShort(boolean isShort) { + this.isShort = isShort; + } + + @Override + public boolean getIsBoolean() { return isBoolean; } + + @Override + public void setIsBoolean(boolean isBoolean) { + this.isBoolean = isBoolean; + } + + @Override + public boolean getIsUnboundedInteger() { return isUnboundedInteger; } + + @Override + public void setIsUnboundedInteger(boolean isUnboundedInteger) { + this.isUnboundedInteger = isUnboundedInteger; + } + @Override public CodegenProperty getAdditionalProperties() { return additionalProperties; } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenProperty.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenProperty.java index b20e55f61b4..4ccbb8c3a9d 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenProperty.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenProperty.java @@ -118,7 +118,9 @@ public class CodegenProperty implements Cloneable, IJsonSchemaValidationProperti public boolean isString; public boolean isNumeric; public boolean isInteger; + public boolean isShort; public boolean isLong; + public boolean isUnboundedInteger; public boolean isNumber; public boolean isFloat; public boolean isDouble; @@ -507,6 +509,30 @@ public class CodegenProperty implements Cloneable, IJsonSchemaValidationProperti this.isArray = isArray; } + @Override + public boolean getIsShort() { return isShort; } + + @Override + public void setIsShort(boolean isShort) { + this.isShort = isShort; + } + + @Override + public boolean getIsBoolean() { return isBoolean; } + + @Override + public void setIsBoolean(boolean isBoolean) { + this.isBoolean = isBoolean; + } + + @Override + public boolean getIsUnboundedInteger() { return isUnboundedInteger; } + + @Override + public void setIsUnboundedInteger(boolean isUnboundedInteger) { + this.isUnboundedInteger = isUnboundedInteger; + } + public Map getVendorExtensions() { return vendorExtensions; } @@ -652,10 +678,12 @@ public class CodegenProperty implements Cloneable, IJsonSchemaValidationProperti this.maxProperties = maxProperties; } + @Override public Number getMultipleOf() { return multipleOf; } + @Override public void setMultipleOf(Number multipleOf) { this.multipleOf = multipleOf; } @@ -765,7 +793,9 @@ public class CodegenProperty implements Cloneable, IJsonSchemaValidationProperti sb.append(", isString=").append(isString); sb.append(", isNumeric=").append(isNumeric); sb.append(", isInteger=").append(isInteger); + sb.append(", isShort=").append(isShort); sb.append(", isLong=").append(isLong); + sb.append(", isUnboundedInteger=").append(isUnboundedInteger); sb.append(", isNumber=").append(isNumber); sb.append(", isFloat=").append(isFloat); sb.append(", isDouble=").append(isDouble); @@ -838,7 +868,9 @@ public class CodegenProperty implements Cloneable, IJsonSchemaValidationProperti isString == that.isString && isNumeric == that.isNumeric && isInteger == that.isInteger && + isShort == that.isShort && isLong == that.isLong && + isUnboundedInteger == that.isUnboundedInteger && isNumber == that.isNumber && isFloat == that.isFloat && isDouble == that.isDouble && @@ -926,7 +958,7 @@ public class CodegenProperty implements Cloneable, IJsonSchemaValidationProperti hasMoreNonReadOnly, isPrimitiveType, isModel, isContainer, isString, isNumeric, isInteger, isLong, isNumber, isFloat, isDouble, isDecimal, isByteArray, isBinary, isFile, isBoolean, isDate, isDateTime, isUuid, isUri, isEmail, isFreeFormObject, - isArray, isMap, isEnum, isReadOnly, isWriteOnly, isNullable, + isArray, isMap, isEnum, isReadOnly, isWriteOnly, isNullable, isShort, isUnboundedInteger, isSelfReference, isCircularReference, isDiscriminator, _enum, allowableValues, items, mostInnerItems, additionalProperties, vars, requiredVars, vendorExtensions, hasValidation, isInherited, discriminatorValue, nameInCamelCase, diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenResponse.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenResponse.java index bb062c1304f..22c85170bbb 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenResponse.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenResponse.java @@ -36,7 +36,9 @@ public class CodegenResponse implements IJsonSchemaValidationProperties { public boolean isString; public boolean isNumeric; public boolean isInteger; + public boolean isShort; public boolean isLong; + public boolean isUnboundedInteger; public boolean isNumber; public boolean isFloat; public boolean isDouble; @@ -89,7 +91,7 @@ public class CodegenResponse implements IJsonSchemaValidationProperties { isString, isNumeric, isInteger, isLong, isNumber, isFloat, isDouble, isDecimal, isByteArray, isBoolean, isDate, isDateTime, isUuid, isEmail, isModel, isFreeFormObject, isAnyType, isDefault, simpleType, primitiveType, isMap, isArray, isBinary, isFile, schema, jsonSchema, vendorExtensions, items, additionalProperties, - vars, requiredVars, isNull, hasValidation, + vars, requiredVars, isNull, hasValidation, isShort, isUnboundedInteger, getMaxProperties(), getMinProperties(), uniqueItems, getMaxItems(), getMinItems(), getMaxLength(), getMinLength(), exclusiveMinimum, exclusiveMaximum, getMinimum(), getMaximum(), getPattern(), is1xx, is2xx, is3xx, is4xx, is5xx, additionalPropertiesIsAnyType, hasVars, hasRequired); @@ -104,7 +106,9 @@ public class CodegenResponse implements IJsonSchemaValidationProperties { isString == that.isString && isNumeric == that.isNumeric && isInteger == that.isInteger && + isShort == that.isShort && isLong == that.isLong && + isUnboundedInteger == that.isUnboundedInteger && isNumber == that.isNumber && isFloat == that.isFloat && isDouble == that.isDouble && @@ -316,6 +320,30 @@ public class CodegenResponse implements IJsonSchemaValidationProperties { this.isArray = isArray; } + @Override + public boolean getIsShort() { return isShort; } + + @Override + public void setIsShort(boolean isShort) { + this.isShort = isShort; + } + + @Override + public boolean getIsBoolean() { return isBoolean; } + + @Override + public void setIsBoolean(boolean isBoolean) { + this.isBoolean = isBoolean; + } + + @Override + public boolean getIsUnboundedInteger() { return isUnboundedInteger; } + + @Override + public void setIsUnboundedInteger(boolean isUnboundedInteger) { + this.isUnboundedInteger = isUnboundedInteger; + } + @Override public void setIsModel(boolean isModel) { this.isModel = isModel; @@ -402,7 +430,9 @@ public class CodegenResponse implements IJsonSchemaValidationProperties { sb.append(", isString=").append(isString); sb.append(", isNumeric=").append(isNumeric); sb.append(", isInteger=").append(isInteger); + sb.append(", isShort=").append(isShort); sb.append(", isLong=").append(isLong); + sb.append(", isUnboundedInteger=").append(isUnboundedInteger); sb.append(", isNumber=").append(isNumber); sb.append(", isFloat=").append(isFloat); sb.append(", isDouble=").append(isDouble); 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 2edf1bf15af..b17b449893f 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 @@ -177,6 +177,8 @@ public class DefaultCodegen implements CodegenConfig { protected List cliOptions = new ArrayList(); protected boolean skipOverwrite; protected boolean removeOperationIdPrefix; + protected String removeOperationIdPrefixDelimiter = "_"; + protected int removeOperationIdPrefixCount = 1; protected boolean skipOperationExample; protected final static Pattern JSON_MIME_PATTERN = Pattern.compile("(?i)application\\/json(;.*)?"); @@ -254,10 +256,12 @@ public class DefaultCodegen implements CodegenConfig { // A cache to efficiently lookup a Schema instance based on the return value of `toModelName()`. private Map modelNameToSchemaCache; + @Override public List cliOptions() { return cliOptions; } + @Override public void processOpts() { if (additionalProperties.containsKey(CodegenConstants.TEMPLATE_DIR)) { this.setTemplateDir((String) additionalProperties.get(CodegenConstants.TEMPLATE_DIR)); @@ -323,6 +327,16 @@ public class DefaultCodegen implements CodegenConfig { .get(CodegenConstants.REMOVE_OPERATION_ID_PREFIX).toString())); } + if (additionalProperties.containsKey(CodegenConstants.REMOVE_OPERATION_ID_PREFIX_DELIMITER)) { + this.setRemoveOperationIdPrefixDelimiter(additionalProperties + .get(CodegenConstants.REMOVE_OPERATION_ID_PREFIX_DELIMITER).toString()); + } + + if (additionalProperties.containsKey(CodegenConstants.REMOVE_OPERATION_ID_PREFIX_COUNT)) { + this.setRemoveOperationIdPrefixCount(Integer.parseInt(additionalProperties + .get(CodegenConstants.REMOVE_OPERATION_ID_PREFIX_COUNT).toString())); + } + if (additionalProperties.containsKey(CodegenConstants.SKIP_OPERATION_EXAMPLE)) { this.setSkipOperationExample(Boolean.parseBoolean(additionalProperties .get(CodegenConstants.SKIP_OPERATION_EXAMPLE).toString())); @@ -398,6 +412,7 @@ public class DefaultCodegen implements CodegenConfig { } // override with any special post-processing for all models + @Override @SuppressWarnings({"static-method", "unchecked"}) public Map postProcessAllModels(Map objs) { if (this.useOneOfInterfaces) { @@ -500,6 +515,7 @@ public class DefaultCodegen implements CodegenConfig { * @param objs Map of models * @return maps of models with various updates */ + @Override public Map updateAllModels(Map objs) { Map allModels = getAllModels(objs); @@ -612,6 +628,7 @@ public class DefaultCodegen implements CodegenConfig { } // override with any special post-processing + @Override @SuppressWarnings("static-method") public Map postProcessModels(Map objs) { return objs; @@ -716,7 +733,7 @@ public class DefaultCodegen implements CodegenConfig { * @return the sanitized value for enum */ public String toEnumValue(String value, String datatype) { - if ("number".equalsIgnoreCase(datatype)) { + if ("number".equalsIgnoreCase(datatype) || "boolean".equalsIgnoreCase(datatype)) { return value; } else { return "\"" + escapeText(value) + "\""; @@ -756,6 +773,7 @@ public class DefaultCodegen implements CodegenConfig { } // override with any message to be shown right before the process finishes + @Override @SuppressWarnings("static-method") public void postProcess() { System.out.println("################################################################################"); @@ -766,28 +784,33 @@ public class DefaultCodegen implements CodegenConfig { } // override with any special post-processing + @Override @SuppressWarnings("static-method") public Map postProcessOperationsWithModels(Map objs, List allModels) { return objs; } // override with any special post-processing + @Override @SuppressWarnings("static-method") public Map postProcessSupportingFileData(Map objs) { return objs; } // override to post-process any model properties + @Override @SuppressWarnings("unused") public void postProcessModelProperty(CodegenModel model, CodegenProperty property) { } // override to post-process any parameters + @Override @SuppressWarnings("unused") public void postProcessParameter(CodegenParameter parameter) { } //override with any special handling of the entire OpenAPI spec document + @Override @SuppressWarnings("unused") public void preprocessOpenAPI(OpenAPI openAPI) { if (useOneOfInterfaces) { @@ -872,23 +895,27 @@ public class DefaultCodegen implements CodegenConfig { } // override with any special handling of the entire OpenAPI spec document + @Override @SuppressWarnings("unused") public void processOpenAPI(OpenAPI openAPI) { } // override with any special handling of the JMustache compiler + @Override @SuppressWarnings("unused") public Compiler processCompiler(Compiler compiler) { return compiler; } // override with any special handling for the templating engine + @Override @SuppressWarnings("unused") public TemplatingEngineAdapter processTemplatingEngine(TemplatingEngineAdapter templatingEngine) { return templatingEngine; } // override with any special text escaping logic + @Override @SuppressWarnings("static-method") public String escapeText(String input) { if (input == null) { @@ -915,6 +942,7 @@ public class DefaultCodegen implements CodegenConfig { * @param input String to be escaped * @return escaped string */ + @Override public String escapeTextWhileAllowingNewLines(String input) { if (input == null) { return input; @@ -935,6 +963,7 @@ public class DefaultCodegen implements CodegenConfig { } // override with any special encoding and escaping logic + @Override @SuppressWarnings("static-method") public String encodePath(String input) { return escapeText(input); @@ -947,6 +976,7 @@ public class DefaultCodegen implements CodegenConfig { * @param input String to be cleaned up * @return string with unsafe characters removed or escaped */ + @Override public String escapeUnsafeCharacters(String input) { LOGGER.warn("escapeUnsafeCharacters should be overridden in the code generator with proper logic to escape " + "unsafe characters"); @@ -963,56 +993,69 @@ public class DefaultCodegen implements CodegenConfig { * @param input String to be cleaned up * @return string with quotation mark removed or escaped */ + @Override public String escapeQuotationMark(String input) { LOGGER.warn("escapeQuotationMark should be overridden in the code generator with proper logic to escape " + "single/double quote"); return input.replace("\"", "\\\""); } + @Override public Set defaultIncludes() { return defaultIncludes; } + @Override public Map typeMapping() { return typeMapping; } + @Override public Map instantiationTypes() { return instantiationTypes; } + @Override public Set reservedWords() { return reservedWords; } + @Override public Set languageSpecificPrimitives() { return languageSpecificPrimitives; } + @Override public Map importMapping() { return importMapping; } + @Override public String testPackage() { return testPackage; } + @Override public String modelPackage() { return modelPackage; } + @Override public String apiPackage() { return apiPackage; } + @Override public String fileSuffix() { return fileSuffix; } + @Override public String templateDir() { return templateDir; } + @Override public String embeddedTemplateDir() { if (embeddedTemplateDir != null) { return embeddedTemplateDir; @@ -1021,90 +1064,112 @@ public class DefaultCodegen implements CodegenConfig { } } + @Override public Map apiDocTemplateFiles() { return apiDocTemplateFiles; } + @Override public Map modelDocTemplateFiles() { return modelDocTemplateFiles; } + @Override public Map reservedWordsMappings() { return reservedWordsMappings; } + @Override public Map apiTestTemplateFiles() { return apiTestTemplateFiles; } + @Override public Map modelTestTemplateFiles() { return modelTestTemplateFiles; } + @Override public Map apiTemplateFiles() { return apiTemplateFiles; } + @Override public Map modelTemplateFiles() { return modelTemplateFiles; } + @Override public String apiFileFolder() { return outputFolder + File.separator + apiPackage().replace('.', File.separatorChar); } + @Override public String modelFileFolder() { return outputFolder + File.separator + modelPackage().replace('.', File.separatorChar); } + @Override public String apiTestFileFolder() { return outputFolder + File.separator + testPackage().replace('.', File.separatorChar); } + @Override public String modelTestFileFolder() { return outputFolder + File.separator + testPackage().replace('.', File.separatorChar); } + @Override public String apiDocFileFolder() { return outputFolder; } + @Override public String modelDocFileFolder() { return outputFolder; } + @Override public Map additionalProperties() { return additionalProperties; } + @Override public Map serverVariableOverrides() { return serverVariables; } + @Override public Map vendorExtensions() { return vendorExtensions; } + @Override public List supportingFiles() { return supportingFiles; } + @Override public String outputFolder() { return outputFolder; } + @Override public void setOutputDir(String dir) { this.outputFolder = dir; } + @Override public String getOutputDir() { return outputFolder(); } + @Override public String getInputSpec() { return inputSpec; } + @Override public void setInputSpec(String inputSpec) { this.inputSpec = inputSpec; } @@ -1233,6 +1298,7 @@ public class DefaultCodegen implements CodegenConfig { * @param name the file name of the Api * @return the file name of the Api */ + @Override public String toApiFilename(String name) { return toApiName(name); } @@ -1243,6 +1309,7 @@ public class DefaultCodegen implements CodegenConfig { * @param name the file name of the Api * @return the file name of the Api */ + @Override public String toApiDocFilename(String name) { return toApiName(name); } @@ -1253,6 +1320,7 @@ public class DefaultCodegen implements CodegenConfig { * @param name the file name of the Api * @return the file name of the Api */ + @Override public String toApiTestFilename(String name) { return toApiName(name) + "Test"; } @@ -1263,6 +1331,7 @@ public class DefaultCodegen implements CodegenConfig { * @param name the varible name of the Api * @return the snake-cased variable name */ + @Override public String toApiVarName(String name) { return lowerCamelCase(name); } @@ -1273,6 +1342,7 @@ public class DefaultCodegen implements CodegenConfig { * @param name the model name * @return the file name of the model */ + @Override public String toModelFilename(String name) { return camelize(name); } @@ -1283,6 +1353,7 @@ public class DefaultCodegen implements CodegenConfig { * @param name the model name * @return the file name of the model */ + @Override public String toModelTestFilename(String name) { return camelize(name) + "Test"; } @@ -1293,6 +1364,7 @@ public class DefaultCodegen implements CodegenConfig { * @param name the model name * @return the file name of the model */ + @Override public String toModelDocFilename(String name) { return camelize(name); } @@ -1346,6 +1418,7 @@ public class DefaultCodegen implements CodegenConfig { * @param name Codegen property object * @return the sanitized parameter name */ + @Override public String toParamName(String name) { name = removeNonNameElementToCamelCase(name); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. if (reservedWords.contains(name)) { @@ -1386,6 +1459,7 @@ public class DefaultCodegen implements CodegenConfig { *

    * throws Runtime exception as reserved word is not allowed (default behavior) */ + @Override @SuppressWarnings("static-method") public String escapeReservedWord(String name) { throw new RuntimeException("reserved word " + name + " not allowed"); @@ -1397,6 +1471,7 @@ public class DefaultCodegen implements CodegenConfig { * @param name the name of the "Model" * @return the fully-qualified "Model" name for import */ + @Override public String toModelImport(String name) { if ("".equals(modelPackage())) { return name; @@ -1411,6 +1486,7 @@ public class DefaultCodegen implements CodegenConfig { * @param name the name of the "Model" * @return Map of fully-qualified models. */ + @Override public Map toModelImportMap(String name){ return Collections.singletonMap(this.toModelImport(name),name); } @@ -1421,6 +1497,7 @@ public class DefaultCodegen implements CodegenConfig { * @param name the name of the "Api" * @return the fully-qualified "Api" name for import */ + @Override public String toApiImport(String name) { return apiPackage() + "." + name; } @@ -1592,6 +1669,7 @@ public class DefaultCodegen implements CodegenConfig { * @param operation OAS operation object * @return string presentation of the example path */ + @Override @SuppressWarnings("static-method") public String generateExamplePath(String path, Operation operation) { StringBuilder sb = new StringBuilder(); @@ -2000,6 +2078,7 @@ public class DefaultCodegen implements CodegenConfig { return "oneOf<" + String.join(",", names) + ">"; } + @Override public Schema unaliasSchema(Schema schema, Map usedImportMappings) { return ModelUtils.unaliasSchema(this.openAPI, schema, usedImportMappings); } @@ -2142,6 +2221,7 @@ public class DefaultCodegen implements CodegenConfig { * @param name name * @return a string presentation of the type */ + @Override @SuppressWarnings("static-method") public String getTypeDeclaration(String name) { return name; @@ -2153,6 +2233,7 @@ public class DefaultCodegen implements CodegenConfig { * @param schema property schema * @return a string presentation of the property type */ + @Override public String getTypeDeclaration(Schema schema) { if (schema == null) { LOGGER.warn("Null schema found. Default type to `NULL_SCHEMA_ERR`"); @@ -2189,6 +2270,7 @@ public class DefaultCodegen implements CodegenConfig { * @param name the name of the property * @return getter name based on naming convention */ + @Override public String toBooleanGetter(String name) { return "get" + getterAndSetterCapitalize(name); } @@ -2199,6 +2281,7 @@ public class DefaultCodegen implements CodegenConfig { * @param name the name of the property * @return getter name based on naming convention */ + @Override public String toGetter(String name) { return "get" + getterAndSetterCapitalize(name); } @@ -2209,6 +2292,7 @@ public class DefaultCodegen implements CodegenConfig { * @param name the name of the property * @return setter name based on naming convention */ + @Override public String toSetter(String name) { return "set" + getterAndSetterCapitalize(name); } @@ -2220,6 +2304,7 @@ public class DefaultCodegen implements CodegenConfig { * @param name the name of the Api * @return capitalized Api name */ + @Override public String toApiName(String name) { if (name.length() == 0) { return "DefaultApi"; @@ -2235,6 +2320,7 @@ public class DefaultCodegen implements CodegenConfig { * @param name the name of the model * @return capitalized model name */ + @Override public String toModelName(final String name) { return camelize(modelNamePrefix + "_" + name + "_" + modelNameSuffix); } @@ -2271,6 +2357,7 @@ public class DefaultCodegen implements CodegenConfig { * @param schema OAS Model object * @return Codegen Model object */ + @Override public CodegenModel fromModel(String name, Schema schema) { Map allDefinitions = ModelUtils.getSchemas(this.openAPI); if (typeAliases == null) { @@ -2403,6 +2490,13 @@ public class DefaultCodegen implements CodegenConfig { if (StringUtils.isBlank(interfaceSchema.get$ref())) { // primitive type String languageType = getTypeDeclaration(interfaceSchema); + if (ModelUtils.isArraySchema(interfaceSchema) || ModelUtils.isMapSchema(interfaceSchema)) { + CodegenProperty cp = fromProperty("composedSchemaImports", interfaceSchema); + while (cp != null) { + addImport(m, cp.complexType); + cp = cp.items; + } + } if (composed.getAnyOf() != null) { if (m.anyOf.contains(languageType)) { @@ -2532,8 +2626,13 @@ public class DefaultCodegen implements CodegenConfig { m.isNumeric = Boolean.TRUE; if (ModelUtils.isLongSchema(schema)) { // int64/long format m.isLong = Boolean.TRUE; - } else { // int32 format - m.isInteger = Boolean.TRUE; + } else { + m.isInteger = Boolean.TRUE; // older use case, int32 and unbounded int + if (ModelUtils.isShortSchema(schema)) { // int32 + m.setIsShort(Boolean.TRUE); + } else { // unbounded integer + m.setIsUnboundedInteger(Boolean.TRUE); + } } } else if (ModelUtils.isDateTimeSchema(schema)) { // NOTE: DateTime schemas as CodegenModel is a rare use case and may be removed at a later date. @@ -2554,6 +2653,8 @@ public class DefaultCodegen implements CodegenConfig { } else { // type is number and without format m.isNumber = Boolean.TRUE; } + } else if (ModelUtils.isBooleanSchema(schema)) { + m.isBoolean = Boolean.TRUE; } else if (ModelUtils.isFreeFormObject(openAPI, schema)) { addAdditionPropertiesToCodeGenModel(m, schema); } @@ -2706,14 +2807,18 @@ public class DefaultCodegen implements CodegenConfig { String modelName = ModelUtils.getSimpleRef(oneOf.get$ref()); CodegenProperty thisCp = discriminatorFound(composedSchemaName, oneOf, discPropName, openAPI); if (thisCp == null) { - LOGGER.warn("'" + composedSchemaName + "' defines discriminator '" + discPropName + "', but the referenced OneOf schema '" + modelName + "' is missing " + discPropName); + LOGGER.warn( + "'{}' defines discriminator '{}', but the referenced OneOf schema '{}' is missing {}", + composedSchemaName, discPropName, modelName, discPropName); } if (cp.dataType == null) { cp = thisCp; continue; } if (cp != thisCp) { - LOGGER.warn("'" + composedSchemaName + "' defines discriminator '" + discPropName + "', but the OneOf schema '" + modelName + "' has a different " + discPropName + " definition than the prior OneOf schema's. Make sure the " + discPropName + " type and required values are the same"); + LOGGER.warn( + "'{}' defines discriminator '{}', but the OneOf schema '{}' has a different {} definition than the prior OneOf schema's. Make sure the {} type and required values are the same", + composedSchemaName, discPropName, modelName, discPropName, discPropName); } } return cp; @@ -2725,14 +2830,18 @@ public class DefaultCodegen implements CodegenConfig { String modelName = ModelUtils.getSimpleRef(anyOf.get$ref()); CodegenProperty thisCp = discriminatorFound(composedSchemaName, anyOf, discPropName, openAPI); if (thisCp == null) { - LOGGER.warn("'" + composedSchemaName + "' defines discriminator '" + discPropName + "', but the referenced AnyOf schema '" + modelName + "' is missing " + discPropName); + LOGGER.warn( + "'{}' defines discriminator '{}', but the referenced AnyOf schema '{}' is missing {}", + composedSchemaName, discPropName, modelName, discPropName); } - if (cp.dataType == null) { + if (cp != null && cp.dataType == null) { cp = thisCp; continue; } if (cp != thisCp) { - LOGGER.warn("'" + composedSchemaName + "' defines discriminator '" + discPropName + "', but the AnyOf schema '" + modelName + "' has a different " + discPropName + " definition than the prior AnyOf schema's. Make sure the " + discPropName + " type and required values are the same"); + LOGGER.warn( + "'{}' defines discriminator '{}', but the AnyOf schema '{}' has a different {} definition than the prior AnyOf schema's. Make sure the {} type and required values are the same", + composedSchemaName, discPropName, modelName, discPropName, discPropName); } } return cp; @@ -2870,7 +2979,9 @@ public class DefaultCodegen implements CodegenConfig { // schemas also has inline composed schemas // Note: if it is only inline one level, then the inline model resolver will move it into its own // schema and make it a $ref schema in the oneOf/anyOf location - LOGGER.warn("Invalid inline schema defined in oneOf/anyOf in '" + composedSchemaName + "'. Per the OpenApi spec, for this case when a composed schema defines a discriminator, the oneOf/anyOf schemas must use $ref. Change this inline definition to a $ref definition"); + LOGGER.warn( + "Invalid inline schema defined in oneOf/anyOf in '{}'. Per the OpenApi spec, for this case when a composed schema defines a discriminator, the oneOf/anyOf schemas must use $ref. Change this inline definition to a $ref definition", + composedSchemaName); } CodegenProperty df = discriminatorFound(composedSchemaName, sc, discPropName, openAPI); String modelName = ModelUtils.getSimpleRef(ref); @@ -2890,7 +3001,8 @@ public class DefaultCodegen implements CodegenConfig { msgSuffix += spacer + "invalid optional definition of " + discPropName + ", include it in required"; } } - LOGGER.warn("'" + composedSchemaName + "' defines discriminator '" + discPropName + "', but the referenced schema '" + modelName + "' is incorrect. " + msgSuffix); + LOGGER.warn("'{}' defines discriminator '{}', but the referenced schema '{}' is incorrect. {}", + composedSchemaName, discPropName, modelName, msgSuffix); } MappedModel mm = new MappedModel(modelName, toModelName(modelName)); descendentSchemas.add(mm); @@ -3185,6 +3297,11 @@ public class DefaultCodegen implements CodegenConfig { } if (p.getExtensions() != null && !p.getExtensions().isEmpty()) { property.getVendorExtensions().putAll(p.getExtensions()); + } else if (p.get$ref() != null) { + Schema referencedSchema = ModelUtils.getReferencedSchema(this.openAPI, p); + if (referencedSchema.getExtensions() != null && !referencedSchema.getExtensions().isEmpty()) { + property.getVendorExtensions().putAll(referencedSchema.getExtensions()); + } } String type = getSchemaType(p); @@ -3192,10 +3309,14 @@ public class DefaultCodegen implements CodegenConfig { property.isNumeric = Boolean.TRUE; if (ModelUtils.isLongSchema(p)) { // int64/long format property.isLong = Boolean.TRUE; - } else { // int32 format - property.isInteger = Boolean.TRUE; + } else { + property.isInteger = Boolean.TRUE; // older use case, int32 and unbounded int + if (ModelUtils.isShortSchema(p)) { // int32 + property.setIsShort(Boolean.TRUE); + } else { // unbounded integer + property.setIsUnboundedInteger(Boolean.TRUE); + } } - } else if (ModelUtils.isBooleanSchema(p)) { // boolean type property.isBoolean = true; property.getter = toBooleanGetter(name); @@ -3672,6 +3793,7 @@ public class DefaultCodegen implements CodegenConfig { * @param servers list of servers * @return Codegen Operation object */ + @Override public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, @@ -3705,9 +3827,14 @@ public class DefaultCodegen implements CodegenConfig { String operationId = getOrGenerateOperationId(operation, path, httpMethod); // remove prefix in operationId if (removeOperationIdPrefix) { - int offset = operationId.indexOf('_'); - if (offset > -1) { - operationId = operationId.substring(offset + 1); + // The prefix is everything before the removeOperationIdPrefixCount occurrence of removeOperationIdPrefixDelimiter + String[] componenets = operationId.split("[" + removeOperationIdPrefixDelimiter + "]"); + if (componenets.length > 1) { + // If removeOperationIdPrefixCount is -1 or bigger that the number of occurrences, uses the last one + int componenet_number = removeOperationIdPrefixCount == -1 ? componenets.length - 1 : removeOperationIdPrefixCount; + componenet_number = Math.min(componenet_number, componenets.length - 1); + // Reconstruct the operationId from its split elements and the delimiter + operationId = String.join(removeOperationIdPrefixDelimiter, Arrays.copyOfRange(componenets, componenet_number, componenets.length)); } } operationId = removeNonNameElementToCamelCase(operationId); @@ -4067,6 +4194,11 @@ public class DefaultCodegen implements CodegenConfig { } else if (Boolean.TRUE.equals(cp.isInteger)) { r.isInteger = true; r.isNumeric = true; + if (Boolean.TRUE.equals(cp.isShort)) { + r.isShort = true; + } else if (Boolean.TRUE.equals(cp.isUnboundedInteger)) { + r.isUnboundedInteger = true; + } } else if (Boolean.TRUE.equals(cp.isNumber)) { r.isNumber = true; r.isNumeric = true; @@ -4422,7 +4554,9 @@ public class DefaultCodegen implements CodegenConfig { }).collect(Collectors.toList()); } else { - LOGGER.warn("No object schema found for deepObject parameter" + codegenParameter + " deepObject won't have specific properties"); + LOGGER.warn( + "No object schema found for deepObject parameter{} deepObject won't have specific properties", + codegenParameter); } } @@ -4475,6 +4609,7 @@ public class DefaultCodegen implements CodegenConfig { * @param securitySchemeMap a map of OAS SecuritySchemeDefinition object * @return a list of Codegen Security objects */ + @Override @SuppressWarnings("static-method") public List fromSecurity(Map securitySchemeMap) { if (securitySchemeMap == null) { @@ -4696,6 +4831,7 @@ public class DefaultCodegen implements CodegenConfig { * @param co Codegen Operation object * @param operations map of Codegen operations */ + @Override @SuppressWarnings("static-method") public void addOperationToGroup(String tag, String resourcePath, Operation operation, CodegenOperation co, Map> operations) { @@ -4714,7 +4850,7 @@ public class DefaultCodegen implements CodegenConfig { } } if (!co.operationId.equals(uniqueName)) { - LOGGER.warn("generated unique operationId `" + uniqueName + "`"); + LOGGER.warn("generated unique operationId `{}`", uniqueName); } co.operationId = uniqueName; co.operationIdLowerCase = uniqueName.toLowerCase(Locale.ROOT); @@ -4869,7 +5005,7 @@ public class DefaultCodegen implements CodegenConfig { final String key = entry.getKey(); final Schema prop = entry.getValue(); if (prop == null) { - LOGGER.warn("Please report the issue. There shouldn't be null property for " + key); + LOGGER.warn("Please report the issue. There shouldn't be null property for {}", key); } else { final CodegenProperty cp = fromProperty(key, prop); cp.required = mandatory.contains(key); @@ -4963,7 +5099,7 @@ public class DefaultCodegen implements CodegenConfig { */ @SuppressWarnings("static-method") public String removeNonNameElementToCamelCase(String name) { - return removeNonNameElementToCamelCase(name, "[-_:;#]"); + return removeNonNameElementToCamelCase(name, "[-_:;#" + removeOperationIdPrefixDelimiter + "]"); } /** @@ -4983,11 +5119,13 @@ public class DefaultCodegen implements CodegenConfig { return result; } + @Override public String apiFilename(String templateName, String tag) { String suffix = apiTemplateFiles().get(templateName); return apiFileFolder() + File.separator + toApiFilename(tag) + suffix; } + @Override public String modelFilename(String templateName, String modelName) { String suffix = modelTemplateFiles().get(templateName); return modelFileFolder() + File.separator + toModelFilename(modelName) + suffix; @@ -5000,6 +5138,7 @@ public class DefaultCodegen implements CodegenConfig { * @param tag tag * @return the API documentation file name with full path */ + @Override public String apiDocFilename(String templateName, String tag) { String docExtension = getDocExtension(); String suffix = docExtension != null ? docExtension : apiDocTemplateFiles().get(templateName); @@ -5013,43 +5152,69 @@ public class DefaultCodegen implements CodegenConfig { * @param tag tag * @return the API test file name with full path */ + @Override public String apiTestFilename(String templateName, String tag) { String suffix = apiTestTemplateFiles().get(templateName); return apiTestFileFolder() + File.separator + toApiTestFilename(tag) + suffix; } + @Override public boolean shouldOverwrite(String filename) { return !(skipOverwrite && new File(filename).exists()); } + @Override public boolean isSkipOverwrite() { return skipOverwrite; } + @Override public void setSkipOverwrite(boolean skipOverwrite) { this.skipOverwrite = skipOverwrite; } + @Override public boolean isRemoveOperationIdPrefix() { return removeOperationIdPrefix; } + @Override public boolean isSkipOperationExample() { return skipOperationExample; } + @Override public void setRemoveOperationIdPrefix(boolean removeOperationIdPrefix) { this.removeOperationIdPrefix = removeOperationIdPrefix; } + public String getRemoveOperationIdPrefixDelimiter() { + return removeOperationIdPrefixDelimiter; + } + + public void setRemoveOperationIdPrefixDelimiter(String removeOperationIdPrefixDelimiter) { + this.removeOperationIdPrefixDelimiter = removeOperationIdPrefixDelimiter; + } + + public int getRemoveOperationIdPrefixCount() { + return removeOperationIdPrefixCount; + } + + public void setRemoveOperationIdPrefixCount(int removeOperationIdPrefixCount) { + this.removeOperationIdPrefixCount = removeOperationIdPrefixCount; + } + + @Override public void setSkipOperationExample(boolean skipOperationExample) { this.skipOperationExample = skipOperationExample; } + @Override public boolean isHideGenerationTimestamp() { return hideGenerationTimestamp; } + @Override public void setHideGenerationTimestamp(boolean hideGenerationTimestamp) { this.hideGenerationTimestamp = hideGenerationTimestamp; } @@ -5060,6 +5225,7 @@ public class DefaultCodegen implements CodegenConfig { * * @return the supported libraries */ + @Override public Map supportedLibraries() { return supportedLibraries; } @@ -5069,6 +5235,7 @@ public class DefaultCodegen implements CodegenConfig { * * @param library Library template */ + @Override public void setLibrary(String library) { if (library != null && !supportedLibraries.containsKey(library)) { StringBuilder sb = new StringBuilder("Unknown library: " + library + "\nAvailable libraries:"); @@ -5089,6 +5256,7 @@ public class DefaultCodegen implements CodegenConfig { * * @return Library template */ + @Override public String getLibrary() { return library; } @@ -5107,6 +5275,7 @@ public class DefaultCodegen implements CodegenConfig { * * @param gitHost Git host */ + @Override public void setGitHost(String gitHost) { this.gitHost = gitHost; } @@ -5116,6 +5285,7 @@ public class DefaultCodegen implements CodegenConfig { * * @return Git host */ + @Override public String getGitHost() { return gitHost; } @@ -5125,6 +5295,7 @@ public class DefaultCodegen implements CodegenConfig { * * @param gitUserId Git user ID */ + @Override public void setGitUserId(String gitUserId) { this.gitUserId = gitUserId; } @@ -5134,6 +5305,7 @@ public class DefaultCodegen implements CodegenConfig { * * @return Git user ID */ + @Override public String getGitUserId() { return gitUserId; } @@ -5143,6 +5315,7 @@ public class DefaultCodegen implements CodegenConfig { * * @param gitRepoId Git repo ID */ + @Override public void setGitRepoId(String gitRepoId) { this.gitRepoId = gitRepoId; } @@ -5152,6 +5325,7 @@ public class DefaultCodegen implements CodegenConfig { * * @return Git repo ID */ + @Override public String getGitRepoId() { return gitRepoId; } @@ -5161,6 +5335,7 @@ public class DefaultCodegen implements CodegenConfig { * * @param releaseNote Release note */ + @Override public void setReleaseNote(String releaseNote) { this.releaseNote = releaseNote; } @@ -5170,6 +5345,7 @@ public class DefaultCodegen implements CodegenConfig { * * @return Release note */ + @Override public String getReleaseNote() { return releaseNote; } @@ -5179,6 +5355,7 @@ public class DefaultCodegen implements CodegenConfig { * * @return Documentation files extension */ + @Override public String getDocExtension() { return docExtension; } @@ -5188,6 +5365,7 @@ public class DefaultCodegen implements CodegenConfig { * * @param userDocExtension documentation files extension */ + @Override public void setDocExtension(String userDocExtension) { this.docExtension = userDocExtension; } @@ -5197,6 +5375,7 @@ public class DefaultCodegen implements CodegenConfig { * * @param httpUserAgent HTTP user agent */ + @Override public void setHttpUserAgent(String httpUserAgent) { this.httpUserAgent = httpUserAgent; } @@ -5206,6 +5385,7 @@ public class DefaultCodegen implements CodegenConfig { * * @return HTTP user agent */ + @Override public String getHttpUserAgent() { return httpUserAgent; } @@ -5225,6 +5405,7 @@ public class DefaultCodegen implements CodegenConfig { * @param name string to be sanitize * @return sanitized string */ + @Override @SuppressWarnings("static-method") public String sanitizeName(String name) { return sanitizeName(name, "\\W"); @@ -5334,6 +5515,7 @@ public class DefaultCodegen implements CodegenConfig { * @param tag Tag * @return Sanitized tag */ + @Override public String sanitizeTag(String tag) { tag = camelize(sanitizeName(tag)); @@ -5383,6 +5565,11 @@ public class DefaultCodegen implements CodegenConfig { } else if (Boolean.TRUE.equals(property.isInteger)) { parameter.isInteger = true; parameter.isPrimitiveType = true; + if (Boolean.TRUE.equals(property.isShort)) { + parameter.isShort = true; + } else if (Boolean.TRUE.equals(property.isUnboundedInteger)) { + parameter.isUnboundedInteger = true; + } } else if (Boolean.TRUE.equals(property.isDouble)) { parameter.isDouble = true; parameter.isPrimitiveType = true; @@ -5457,13 +5644,9 @@ public class DefaultCodegen implements CodegenConfig { // handle default value for enum, e.g. available => StatusEnum.AVAILABLE if (var.defaultValue != null) { + final String enumDefaultValue = getEnumDefaultValue(var.defaultValue, dataType); + String enumName = null; - final String enumDefaultValue; - if (isDataTypeString(dataType)) { - enumDefaultValue = toEnumValue(var.defaultValue, dataType); - } else { - enumDefaultValue = var.defaultValue; - } for (Map enumVar : enumVars) { if (enumDefaultValue.equals(enumVar.get("value"))) { enumName = (String) enumVar.get("name"); @@ -5476,6 +5659,16 @@ public class DefaultCodegen implements CodegenConfig { } } + protected String getEnumDefaultValue(String defaultValue, String dataType) { + final String enumDefaultValue; + if (isDataTypeString(dataType)) { + enumDefaultValue = toEnumValue(defaultValue, dataType); + } else { + enumDefaultValue = defaultValue; + } + return enumDefaultValue; + } + protected List> buildEnumVars(List values, String dataType) { List> enumVars = new ArrayList<>(); int truncateIdx = 0; @@ -5562,6 +5755,7 @@ public class DefaultCodegen implements CodegenConfig { * * @return a string of the full path to an override ignore file. */ + @Override public String getIgnoreFilePathOverride() { return ignoreFilePathOverride; } @@ -5571,6 +5765,7 @@ public class DefaultCodegen implements CodegenConfig { * * @param ignoreFileOverride The full path to an ignore file */ + @Override public void setIgnoreFilePathOverride(final String ignoreFileOverride) { this.ignoreFilePathOverride = ignoreFileOverride; } @@ -5751,14 +5946,17 @@ public class DefaultCodegen implements CodegenConfig { } } + @Override public CodegenType getTag() { return null; } + @Override public String getName() { return null; } + @Override public String getHelp() { return null; } @@ -6347,6 +6545,7 @@ public class DefaultCodegen implements CodegenConfig { * @param file file to be processed * @param fileType file type */ + @Override public void postProcessFile(File file, String fileType) { LOGGER.debug("Post processing file {} ({})", file, fileType); } @@ -6356,6 +6555,7 @@ public class DefaultCodegen implements CodegenConfig { * * @return true if the option is enabled */ + @Override public boolean isEnablePostProcessFile() { return enablePostProcessFile; } @@ -6365,6 +6565,7 @@ public class DefaultCodegen implements CodegenConfig { * * @param enablePostProcessFile true to enable post-processing file */ + @Override public void setEnablePostProcessFile(boolean enablePostProcessFile) { this.enablePostProcessFile = enablePostProcessFile; } 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 9fde6eaa047..d2e1bb4500d 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 @@ -938,7 +938,7 @@ public class DefaultGenerator implements Generator { // TODO: initial behavior is "merge" user defined with built-in templates. consider offering user a "replace" option. if (userDefinedTemplates != null && !userDefinedTemplates.isEmpty()) { Map supportingFilesMap = config.supportingFiles().stream() - .collect(Collectors.toMap(TemplateDefinition::getTemplateFile, Function.identity())); + .collect(Collectors.toMap(TemplateDefinition::getTemplateFile, Function.identity(), (oldValue, newValue) -> oldValue)); // TemplateFileType.SupportingFiles userDefinedTemplates.stream() diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/IJsonSchemaValidationProperties.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/IJsonSchemaValidationProperties.java index 4eb567b6cdc..bf078ab792d 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/IJsonSchemaValidationProperties.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/IJsonSchemaValidationProperties.java @@ -77,7 +77,19 @@ public interface IJsonSchemaValidationProperties { boolean getIsArray(); - void setIsArray(boolean isArray); + void setIsArray(boolean isShort); + + boolean getIsShort(); + + void setIsShort(boolean isShort); + + boolean getIsBoolean(); + + void setIsBoolean(boolean isBoolean); + + boolean getIsUnboundedInteger(); + + void setIsUnboundedInteger(boolean isUnboundedInteger); CodegenProperty getAdditionalProperties(); @@ -110,4 +122,4 @@ public interface IJsonSchemaValidationProperties { boolean getHasRequired(); void setHasRequired(boolean hasRequired); -} \ No newline at end of file +} diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/TemplateManager.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/TemplateManager.java index 3af30d83bab..072bb4037ef 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/TemplateManager.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/TemplateManager.java @@ -206,6 +206,7 @@ public class TemplateManager implements TemplatingExecutor, TemplateProcessor { * @return File representing the written file. * @throws IOException If file cannot be written. */ + @Override public File writeToFile(String filename, byte[] contents) throws IOException { // Use Paths.get here to normalize path (for Windows file separator, space escaping on Linux/Mac, etc) File outputFile = Paths.get(filename).toFile(); 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 7c0176dcb46..1bf89faabbb 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 @@ -34,7 +34,10 @@ public class GlobalSettings { private static ThreadLocal properties = new InheritableThreadLocal() { @Override protected Properties initialValue() { - return (Properties) System.getProperties().clone(); + // avoid using System.getProperties().clone() which is broken in Gradle - see https://github.com/gradle/gradle/issues/17344 + Properties copy = new Properties(); + copy.putAll(System.getProperties()); + return copy; }; }; 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 0c4f9ad726d..e699a252719 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 @@ -204,7 +204,7 @@ public class ExampleGenerator { output.add(kv); } else if (mediaType.startsWith(MIME_TYPE_XML)) { // TODO - LOGGER.warn("XML example value of (array/primitive) is not handled at the moment: " + example); + LOGGER.warn("XML example value of (array/primitive) is not handled at the moment: {}", example); } } } @@ -296,7 +296,7 @@ public class ExampleGenerator { LOGGER.debug("URI or URL format, without default or enum, generating random one."); return "http://example.com/aeiou"; } - LOGGER.debug("No values found, using property name " + propertyName + " as example"); + LOGGER.debug("No values found, using property name {} as example", propertyName); return propertyName; } else if (!StringUtils.isEmpty(property.get$ref())) { // model String simpleName = ModelUtils.getSimpleRef(property.get$ref()); 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 309ae0357fc..7ef64adcd71 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 @@ -220,7 +220,7 @@ abstract public class AbstractAdaCodegen extends DefaultCodegen implements Codeg protected String toAdaIdentifier(String name, String prefix) { // We cannot use reserved keywords for identifiers if (isReservedWord(name)) { - LOGGER.warn("Identifier '" + name + "' is a reserved word, renamed to " + prefix + name); + LOGGER.warn("Identifier '{}' is a reserved word, renamed to {}{}", name, prefix, name); name = prefix + name; } StringBuilder result = new StringBuilder(); @@ -277,6 +277,7 @@ abstract public class AbstractAdaCodegen extends DefaultCodegen implements Codeg * @param name the name of the model * @return capitalized model name */ + @Override public String toModelName(final String name) { String result = camelize(sanitizeName(name)); @@ -287,20 +288,22 @@ abstract public class AbstractAdaCodegen extends DefaultCodegen implements Codeg // model name cannot use reserved keyword, e.g. return if (isReservedWord(name)) { String modelName = "Model_" + result; - LOGGER.warn(name + " (reserved word) cannot be used as model name. Renamed to " + modelName); + LOGGER.warn("{} (reserved word) cannot be used as model name. Renamed to {}", name, modelName); return modelName; } // model name starts with number if (result.matches("^\\d.*")) { String modelName = "Model_" + result; // e.g. 200Response => Model_200Response (after camelize) - LOGGER.warn(name + " (model name starts with number) cannot be used as model name. Renamed to " + modelName); + LOGGER.warn("{} (model name starts with number) cannot be used as model name. Renamed to {}", name, + modelName); return modelName; } if (languageSpecificPrimitives.contains(result)) { String modelName = "Model_" + result; - LOGGER.warn(name + " (model name matches existing language type) cannot be used as a model name. Renamed to " + modelName); + LOGGER.warn("{} (model name matches existing language type) cannot be used as a model name. Renamed to {}", + name, modelName); return modelName; } 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 f2a577ca899..0049bb6554d 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 @@ -162,14 +162,15 @@ public abstract class AbstractApexCodegen extends DefaultCodegen implements Code // model name cannot use reserved keyword, e.g. return if (isReservedWord(camelizedName)) { final String modelName = "Model" + camelizedName; - LOGGER.warn(camelizedName + " (reserved word) cannot be used as model name. Renamed to " + modelName); + LOGGER.warn("{} (reserved word) cannot be used as model name. Renamed to {}", camelizedName, modelName); return modelName; } // model name starts with number if (camelizedName.matches("^\\d.*")) { final String modelName = "Model" + camelizedName; // e.g. 200Response => Model200Response (after camelize) - LOGGER.warn(name + " (model name starts with number) cannot be used as model name. Renamed to " + modelName); + LOGGER.warn("{} (model name starts with number) cannot be used as model name. Renamed to {}", name, + modelName); return modelName; } @@ -188,7 +189,7 @@ public abstract class AbstractApexCodegen extends DefaultCodegen implements Code ArraySchema ap = (ArraySchema) p; Schema inner = ap.getItems(); if (inner == null) { - LOGGER.warn(ap.getName() + "(array property) does not have a proper inner type defined"); + LOGGER.warn("{}(array property) does not have a proper inner type defined", ap.getName()); // TODO maybe better defaulting to StringProperty than returning null return null; } @@ -197,7 +198,7 @@ public abstract class AbstractApexCodegen extends DefaultCodegen implements Code Schema inner = getAdditionalProperties(p); if (inner == null) { - LOGGER.warn(p.getName() + "(map property) does not have a proper inner type defined"); + LOGGER.warn("{}(map property) does not have a proper inner type defined", p.getName()); // TODO maybe better defaulting to StringProperty than returning null return null; } @@ -408,7 +409,7 @@ public abstract class AbstractApexCodegen extends DefaultCodegen implements Code } if (null == schemaType) { - LOGGER.error("No Type defined for Property " + p); + LOGGER.error("No Type defined for Property {}", p); } return toModelName(schemaType); } @@ -425,7 +426,7 @@ public abstract class AbstractApexCodegen extends DefaultCodegen implements Code // method name cannot use reserved keyword, e.g. return if (isReservedWord(operationId)) { String newOperationId = camelize("call_" + operationId, true); - LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + newOperationId); + LOGGER.warn("{} (reserved word) cannot be used as method name. Renamed to {}", operationId, newOperationId); return newOperationId; } @@ -642,6 +643,7 @@ public abstract class AbstractApexCodegen extends DefaultCodegen implements Code return p.replaceAll("\"", "%22"); } + @Override public String toRegularExpression(String pattern) { return escapeText(pattern); } 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 eb263b34c37..ffb716bdfda 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 @@ -41,12 +41,14 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co protected boolean optionalAssemblyInfoFlag = true; protected boolean optionalEmitDefaultValuesFlag = false; + protected boolean conditionalSerialization = false; protected boolean optionalProjectFileFlag = true; protected boolean optionalMethodArgumentFlag = true; protected boolean useDateTimeOffsetFlag = false; protected boolean useCollection = false; protected boolean returnICollection = false; protected boolean netCoreProjectFileFlag = false; + protected boolean nullReferenceTypesFlag = false; protected String modelPropertyNaming = CodegenConstants.MODEL_PROPERTY_NAMING_TYPE.PascalCase.name(); @@ -356,6 +358,12 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co additionalProperties.put(CodegenConstants.NETCORE_PROJECT_FILE, netCoreProjectFileFlag); } + if (additionalProperties.containsKey(CodegenConstants.NULLABLE_REFERENCE_TYPES)) { + setNullableReferenceTypes(convertPropertyToBooleanAndWriteBack(CodegenConstants.NULLABLE_REFERENCE_TYPES)); + } else { + additionalProperties.put(CodegenConstants.NULLABLE_REFERENCE_TYPES, nullReferenceTypesFlag); + } + if (additionalProperties.containsKey(CodegenConstants.INTERFACE_PREFIX)) { String useInterfacePrefix = additionalProperties.get(CodegenConstants.INTERFACE_PREFIX).toString(); if ("false".equals(useInterfacePrefix.toLowerCase(Locale.ROOT))) { @@ -789,13 +797,13 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co // method name cannot use reserved keyword, e.g. return if (isReservedWord(operationId)) { - LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + camelize(sanitizeName("call_" + operationId))); + LOGGER.warn("{} (reserved word) cannot be used as method name. Renamed to {}", operationId, camelize(sanitizeName("call_" + operationId))); operationId = "call_" + operationId; } // operationId starts with a number if (operationId.matches("^\\d.*")) { - LOGGER.warn(operationId + " (starting with a number) cannot be used as method name. Renamed to " + camelize(sanitizeName("call_" + operationId))); + LOGGER.warn("{} (starting with a number) cannot be used as method name. Renamed to {}", operationId, camelize(sanitizeName("call_" + operationId))); operationId = "call_" + operationId; } @@ -1032,13 +1040,14 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co // model name cannot use reserved keyword, e.g. return if (isReservedWord(name)) { - LOGGER.warn(name + " (reserved word) cannot be used as model name. Renamed to " + camelize("model_" + name)); + LOGGER.warn("{} (reserved word) cannot be used as model name. Renamed to {}", name, camelize("model_" + name)); name = "model_" + name; // e.g. return => ModelReturn (after camelize) } // model name starts with number if (name.matches("^\\d.*")) { - LOGGER.warn(name + " (model name starts with number) cannot be used as model name. Renamed to " + camelize("model_" + name)); + LOGGER.warn("{} (model name starts with number) cannot be used as model name. Renamed to {}", name, + camelize("model_" + name)); name = "model_" + name; // e.g. 200Response => Model200Response (after camelize) } @@ -1111,6 +1120,13 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co return interfacePrefix; } + public void setNullableReferenceTypes(final Boolean nullReferenceTypesFlag){ + this.nullReferenceTypesFlag = nullReferenceTypesFlag; + if (nullReferenceTypesFlag == true){ + this.nullableType.add("string"); + } + } + public void setInterfacePrefix(final String interfacePrefix) { this.interfacePrefix = interfacePrefix; } @@ -1267,7 +1283,7 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co if (exitValue != 0) { LOGGER.error("Error running the command ({}). Exit code: {}", command, exitValue); } else { - LOGGER.info("Successfully executed: " + command); + LOGGER.info("Successfully executed: {}", command); } } catch (InterruptedException | IOException e) { LOGGER.error("Error running the command ({}). Exception: {}", command, e.getMessage()); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractCppCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractCppCodegen.java index 71f0757d91c..2adc4b8e1b2 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractCppCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractCppCodegen.java @@ -237,7 +237,7 @@ abstract public class AbstractCppCodegen extends DefaultCodegen implements Codeg @Override public String toOperationId(String operationId) { if (isReservedWord(operationId)) { - LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + escapeReservedWord(operationId)); + LOGGER.warn("{} (reserved word) cannot be used as method name. Renamed to {}", operationId, escapeReservedWord(operationId)); return escapeReservedWord(operationId); } return sanitizeName(super.toOperationId(operationId)); @@ -275,6 +275,7 @@ abstract public class AbstractCppCodegen extends DefaultCodegen implements Codeg * @param name the name of the property * @return getter name based on naming convention */ + @Override public String toBooleanGetter(String name) { return "is" + getterAndSetterCapitalize(name); } @@ -284,6 +285,7 @@ abstract public class AbstractCppCodegen extends DefaultCodegen implements Codeg return "std::shared_ptr<" + toModelName(str) + ">"; } + @Override public void processOpts() { super.processOpts(); @@ -329,7 +331,7 @@ abstract public class AbstractCppCodegen extends DefaultCodegen implements Codeg if (exitValue != 0) { LOGGER.error("Error running the command ({}). Exit value: {}", command, exitValue); } else { - LOGGER.info("Successfully executed: " + command); + LOGGER.info("Successfully executed: {}", command); } } catch (InterruptedException | IOException e) { LOGGER.error("Error running the command ({}). Exception: {}", command, e.getMessage()); 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 6cd5d2926e8..c5d8f65516d 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 @@ -1,7 +1,6 @@ package org.openapitools.codegen.languages; import com.google.common.collect.Lists; -import com.google.common.collect.Maps; import com.google.common.collect.Sets; import io.swagger.v3.oas.models.Operation; import io.swagger.v3.oas.models.media.ArraySchema; @@ -29,6 +28,9 @@ public abstract class AbstractDartCodegen extends DefaultCodegen { private static final Logger LOGGER = LoggerFactory.getLogger(AbstractDartCodegen.class); + protected static final List DEFAULT_SUPPORTED_CONTENT_TYPES = Arrays.asList( + "application/json", "application/x-www-form-urlencoded", "multipart/form-data"); + public static final String PUB_LIBRARY = "pubLibrary"; public static final String PUB_NAME = "pubName"; public static final String PUB_VERSION = "pubVersion"; @@ -556,6 +558,68 @@ public abstract class AbstractDartCodegen extends DefaultCodegen { return op; } + @Override + public Map postProcessOperationsWithModels(Map objs, List allModels) { + super.postProcessOperationsWithModels(objs, allModels); + Map operations = (Map) objs.get("operations"); + if (operations != null) { + List ops = (List) operations.get("operation"); + for (CodegenOperation op : ops) { + if (op.hasConsumes) { + if (!op.formParams.isEmpty() || op.isMultipart) { + // DefaultCodegen only sets this if the first consumes mediaType + // is application/x-www-form-urlencoded or multipart. + // Can just use the original + op.prioritizedContentTypes = op.consumes; + } else { + // Prioritize content types by moving application/json to the front + // similar to JavaCodegen + op.prioritizedContentTypes = prioritizeContentTypes(op.consumes); + String mediaType = op.prioritizedContentTypes.get(0).get("mediaType"); + if (!DEFAULT_SUPPORTED_CONTENT_TYPES.contains(mediaType)) { + LOGGER.warn("The media-type '{}' for operation '{}' is not support in the Dart generators by default.", mediaType, op.path); + } + } + } + } + } + return objs; + } + + private List> prioritizeContentTypes(List> consumes) { + if (consumes.size() <= 1) { + // no need to change any order + return consumes; + } + + List> prioritizedContentTypes = new ArrayList<>(consumes.size()); + + List> jsonVendorMimeTypes = new ArrayList<>(consumes.size()); + List> jsonMimeTypes = new ArrayList<>(consumes.size()); + + for (Map consume : consumes) { + String mediaType = consume.get("mediaType"); + if (isJsonVendorMimeType(mediaType)) { + jsonVendorMimeTypes.add(consume); + } else if (isJsonMimeType(mediaType)) { + jsonMimeTypes.add(consume); + } else { + prioritizedContentTypes.add(consume); + } + } + + prioritizedContentTypes.addAll(0, jsonMimeTypes); + prioritizedContentTypes.addAll(0, jsonVendorMimeTypes); + return prioritizedContentTypes; + } + + private static boolean isMultipartType(String mediaType) { + if (mediaType != null) { + return "multipart/form-data".equals(mediaType); + } + return false; + } + @Override protected void updateEnumVarsWithExtensions(List> enumVars, Map vendorExtensions, String dataType) { if (vendorExtensions != null && useEnumExtension && vendorExtensions.containsKey("x-enum-values")) { diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractEiffelCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractEiffelCodegen.java index 945f7324920..d0554f2646d 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractEiffelCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractEiffelCodegen.java @@ -192,22 +192,22 @@ public abstract class AbstractEiffelCodegen extends DefaultCodegen implements Co // model name cannot use reserved keyword, e.g. return if (isReservedWord(name)) { - LOGGER.warn(name + " (reserved word) cannot be used as model name. Renamed to " + ("model_" + name)); + LOGGER.warn("{} (reserved word) cannot be used as model name. Renamed to {}", name, "model_" + name); name = "model_" + name; // e.g. return => ModelReturn (after // camelize) } // model name starts with number if (name.matches("^\\d.*")) { - LOGGER.warn(name + " (model name starts with number) cannot be used as model name. Renamed to " - + ("model_" + name)); + LOGGER.warn("{} (model name starts with number) cannot be used as model name. Renamed to {}", name, + "model_" + name); name = "model_" + name; // e.g. 200Response => Model200Response // (after camelize) } // model name starts with _ if (name.startsWith("_")) { - LOGGER.warn(name + " (model name starts with _) cannot be used as model name. Renamed to " - + ("model" + name)); + LOGGER.warn("{} (model name starts with _) cannot be used as model name. Renamed to {}", name, + "model" + name); name = "model" + name; // e.g. 200Response => Model200Response // (after camelize) } @@ -344,8 +344,7 @@ public abstract class AbstractEiffelCodegen extends DefaultCodegen implements Co // method name cannot use reserved keyword, e.g. return if (isReservedWord(sanitizedOperationId)) { - LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " - + camelize("call_" + operationId)); + LOGGER.warn("{} (reserved word) cannot be used as method name. Renamed to {}", operationId, camelize("call_" + operationId)); sanitizedOperationId = "call_" + sanitizedOperationId; } @@ -609,7 +608,7 @@ public abstract class AbstractEiffelCodegen extends DefaultCodegen implements Co @Override protected void updatePropertyForArray(CodegenProperty property, CodegenProperty innerProperty) { if (innerProperty == null) { - LOGGER.warn("skipping invalid array property " + Json.pretty(property)); + LOGGER.warn("skipping invalid array property {}", Json.pretty(property)); return; } property.dataFormat = innerProperty.dataFormat; diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractFSharpCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractFSharpCodegen.java index 0dc4e1126a7..d33738bd824 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractFSharpCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractFSharpCodegen.java @@ -628,13 +628,13 @@ public abstract class AbstractFSharpCodegen extends DefaultCodegen implements Co // method name cannot use reserved keyword, e.g. return if (isReservedWord(operationId)) { - LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + camelize(sanitizeName("call_" + operationId))); + LOGGER.warn("{} (reserved word) cannot be used as method name. Renamed to {}", operationId, camelize(sanitizeName("call_" + operationId))); operationId = "call_" + operationId; } // operationId starts with a number if (operationId.matches("^\\d.*")) { - LOGGER.warn(operationId + " (starting with a number) cannot be used as method name. Renamed to " + camelize(sanitizeName("call_" + operationId))); + LOGGER.warn("{} (starting with a number) cannot be used as method name. Renamed to {}", operationId, camelize(sanitizeName("call_" + operationId))); operationId = "call_" + operationId; } @@ -900,13 +900,14 @@ public abstract class AbstractFSharpCodegen extends DefaultCodegen implements Co // model name cannot use reserved keyword, e.g. return if (isReservedWord(name)) { - LOGGER.warn(name + " (reserved word) cannot be used as model name. Renamed to " + camelize("model_" + name)); + LOGGER.warn("{} (reserved word) cannot be used as model name. Renamed to {}", name, camelize("model_" + name)); name = "model_" + name; // e.g. return => ModelReturn (after camelize) } // model name starts with number if (name.matches("^\\d.*")) { - LOGGER.warn(name + " (model name starts with number) cannot be used as model name. Renamed to " + camelize("model_" + name)); + LOGGER.warn("{} (model name starts with number) cannot be used as model name. Renamed to {}", name, + camelize("model_" + name)); name = "model_" + name; // e.g. 200Response => Model200Response (after camelize) } @@ -1121,7 +1122,7 @@ public abstract class AbstractFSharpCodegen extends DefaultCodegen implements Co if (exitValue != 0) { LOGGER.error("Error running the command ({}). Exit code: {}", command, exitValue); } else { - LOGGER.info("Successfully executed: " + command); + LOGGER.info("Successfully executed: {}", command); } } catch (InterruptedException | IOException e) { LOGGER.error("Error running the command ({}). Exception: {}", command, e.getMessage()); 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 cee83d467c8..c4dd2d45168 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 @@ -202,7 +202,7 @@ public abstract class AbstractGoCodegen extends DefaultCodegen implements Codege // for reserved word append _ if (isReservedWord(name)) { - LOGGER.warn(name + " (reserved word) cannot be used as variable name. Renamed to " + escapeReservedWord(name)); + LOGGER.warn("{} (reserved word) cannot be used as variable name. Renamed to {}", name, escapeReservedWord(name)); name = escapeReservedWord(name); } @@ -234,7 +234,7 @@ public abstract class AbstractGoCodegen extends DefaultCodegen implements Codege // really should just be a letter, e.g. "p Person"), but we'll get // around to that some other time... Maybe. if (isReservedWord(name)) { - LOGGER.warn(name + " (reserved word) cannot be used as parameter name. Renamed to " + name + "_"); + LOGGER.warn("{} (reserved word) cannot be used as parameter name. Renamed to {}_", name, name); name = name + "_"; } @@ -269,7 +269,8 @@ public abstract class AbstractGoCodegen extends DefaultCodegen implements Codege name = toModel("model_" + name); if (isReservedFilename(name)) { - LOGGER.warn(name + ".go with suffix (reserved word) cannot be used as filename. Renamed to " + name + "_.go"); + LOGGER.warn("{}.go with suffix (reserved word) cannot be used as filename. Renamed to {}_.go", name, + name); name += "_"; } return name; @@ -292,14 +293,14 @@ public abstract class AbstractGoCodegen extends DefaultCodegen implements Codege // model name cannot use reserved keyword, e.g. return if (isReservedWord(name)) { - LOGGER.warn(name + " (reserved word) cannot be used as model name. Renamed to " + ("model_" + name)); + LOGGER.warn("{} (reserved word) cannot be used as model name. Renamed to {}", name, "model_" + name); name = "model_" + name; // e.g. return => ModelReturn (after camelize) } // model name starts with number if (name.matches("^\\d.*")) { - LOGGER.warn(name + " (model name starts with number) cannot be used as model name. Renamed to " - + ("model_" + name)); + LOGGER.warn("{} (model name starts with number) cannot be used as model name. Renamed to {}", name, + "model_" + name); name = "model_" + name; // e.g. 200Response => Model200Response (after camelize) } @@ -317,7 +318,8 @@ public abstract class AbstractGoCodegen extends DefaultCodegen implements Codege // e.g. PetApi.go => pet_api.go api = "api_" + underscore(api); if (isReservedFilename(api)) { - LOGGER.warn(name + ".go with suffix (reserved word) cannot be used as filename. Renamed to " + api + "_.go"); + LOGGER.warn("{}.go with suffix (reserved word) cannot be used as filename. Renamed to {}_.go", name, + api); api += "_"; } apiName = api; @@ -441,14 +443,13 @@ public abstract class AbstractGoCodegen extends DefaultCodegen implements Codege // method name cannot use reserved keyword, e.g. return if (isReservedWord(sanitizedOperationId)) { - LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " - + camelize("call_" + sanitizedOperationId)); + LOGGER.warn("{} (reserved word) cannot be used as method name. Renamed to {}", operationId, camelize("call_" + sanitizedOperationId)); sanitizedOperationId = "call_" + sanitizedOperationId; } // operationId starts with a number if (sanitizedOperationId.matches("^\\d.*")) { - LOGGER.warn(operationId + " (starting with a number) cannot be used as method name. Renamed to " + camelize("call_" + sanitizedOperationId)); + LOGGER.warn("{} (starting with a number) cannot be used as method name. Renamed to {}", operationId, camelize("call_" + sanitizedOperationId)); sanitizedOperationId = "call_" + sanitizedOperationId; } @@ -831,7 +832,7 @@ public abstract class AbstractGoCodegen extends DefaultCodegen implements Codege if (exitValue != 0) { LOGGER.error("Error running the command ({}). Exit code: {}", command, exitValue); } else { - LOGGER.info("Successfully executed: " + command); + LOGGER.info("Successfully executed: {}", command); } } catch (InterruptedException | IOException e) { LOGGER.error("Error running the command ({}). Exception: {}", command, e.getMessage()); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractGraphQLCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractGraphQLCodegen.java index 5246963a8b1..041ead342ae 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractGraphQLCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractGraphQLCodegen.java @@ -143,6 +143,7 @@ public abstract class AbstractGraphQLCodegen extends DefaultCodegen implements C return outputFolder + File.separator + packageName + File.separator + "api" + File.separator; } + @Override public String modelFileFolder() { return outputFolder + File.separator + packageName + File.separator + "model" + File.separator; } @@ -193,13 +194,14 @@ public abstract class AbstractGraphQLCodegen extends DefaultCodegen implements C // model name cannot use reserved keyword, e.g. return if (isReservedWord(name)) { - LOGGER.warn(name + " (reserved word) cannot be used as model name. Renamed to " + ("model_" + name)); + LOGGER.warn("{} (reserved word) cannot be used as model name. Renamed to {}", name, "model_" + name); name = "model_" + name; // e.g. return => ModelReturn (after camelize) } // model name starts with number if (name.matches("^\\d.*")) { - LOGGER.warn(name + " (model name starts with number) cannot be used as model name. Renamed to " + ("model_" + name)); + LOGGER.warn("{} (model name starts with number) cannot be used as model name. Renamed to {}", name, + "model_" + name); name = "model_" + name; // e.g. 200Response => Model200Response (after camelize) } @@ -317,7 +319,7 @@ public abstract class AbstractGraphQLCodegen extends DefaultCodegen implements C // method name cannot use reserved keyword, e.g. return if (isReservedWord(sanitizedOperationId)) { - LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + underscore("call_" + operationId)); + LOGGER.warn("{} (reserved word) cannot be used as method name. Renamed to {}", operationId, underscore("call_" + operationId)); sanitizedOperationId = "call_" + sanitizedOperationId; } 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 0ef7bc8d843..c50caf9c3aa 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 @@ -313,13 +313,14 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code String derivedInvokerPackage = deriveInvokerPackageName((String) additionalProperties.get(CodegenConstants.API_PACKAGE)); this.additionalProperties.put(CodegenConstants.INVOKER_PACKAGE, derivedInvokerPackage); this.setInvokerPackage((String) additionalProperties.get(CodegenConstants.INVOKER_PACKAGE)); - LOGGER.info("Invoker Package Name, originally not set, is now derived from api package name: " + derivedInvokerPackage); + LOGGER.info("Invoker Package Name, originally not set, is now derived from api package name: {}", derivedInvokerPackage); } else if (additionalProperties.containsKey(CodegenConstants.MODEL_PACKAGE)) { // guess from model package String derivedInvokerPackage = deriveInvokerPackageName((String) additionalProperties.get(CodegenConstants.MODEL_PACKAGE)); this.additionalProperties.put(CodegenConstants.INVOKER_PACKAGE, derivedInvokerPackage); this.setInvokerPackage((String) additionalProperties.get(CodegenConstants.INVOKER_PACKAGE)); - LOGGER.info("Invoker Package Name, originally not set, is now derived from model package name: " + derivedInvokerPackage); + LOGGER.info("Invoker Package Name, originally not set, is now derived from model package name: {}", + derivedInvokerPackage); } else { //not set, use default to be passed to template additionalProperties.put(CodegenConstants.INVOKER_PACKAGE, invokerPackage); @@ -538,12 +539,7 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code importMapping.put("com.fasterxml.jackson.annotation.JsonProperty", "com.fasterxml.jackson.annotation.JsonCreator"); if (additionalProperties.containsKey(JAVA8_MODE)) { - setJava8Mode(Boolean.parseBoolean(additionalProperties.get(JAVA8_MODE).toString())); - if (java8Mode) { - additionalProperties.put("java8", true); - } else { - additionalProperties.put("java8", false); - } + setJava8ModeAndAdditionalProperties(Boolean.parseBoolean(additionalProperties.get(JAVA8_MODE).toString())); } if (additionalProperties.containsKey(SUPPORT_ASYNC)) { @@ -786,14 +782,15 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code // model name cannot use reserved keyword, e.g. return if (isReservedWord(camelizedName)) { final String modelName = "Model" + camelizedName; - LOGGER.warn(camelizedName + " (reserved word) cannot be used as model name. Renamed to " + modelName); + LOGGER.warn("{} (reserved word) cannot be used as model name. Renamed to {}", camelizedName, modelName); return modelName; } // model name starts with number if (camelizedName.matches("^\\d.*")) { final String modelName = "Model" + camelizedName; // e.g. 200Response => Model200Response (after camelize) - LOGGER.warn(name + " (model name starts with number) cannot be used as model name. Renamed to " + modelName); + LOGGER.warn("{} (model name starts with number) cannot be used as model name. Renamed to {}", name, + modelName); return modelName; } @@ -1140,7 +1137,7 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code } if (null == openAPIType) { - LOGGER.error("No Type defined for Schema " + p); + LOGGER.error("No Type defined for Schema {}", p); } return toModelName(openAPIType); } @@ -1157,7 +1154,7 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code // method name cannot use reserved keyword, e.g. return if (isReservedWord(operationId)) { String newOperationId = camelize("call_" + operationId, true); - LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + newOperationId); + LOGGER.warn("{} (reserved word) cannot be used as method name. Renamed to {}", operationId, newOperationId); return newOperationId; } @@ -1284,7 +1281,7 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code continue; } for (Operation operation : path.readOperations()) { - LOGGER.info("Processing operation " + operation.getOperationId()); + LOGGER.info("Processing operation {}", operation.getOperationId()); if (hasBodyParameter(openAPI, operation) || hasFormParameter(openAPI, operation)) { String defaultContentType = hasFormParameter(openAPI, operation) ? "application/x-www-form-urlencoded" : "application/json"; List consumes = new ArrayList<>(getConsumesInfo(openAPI, operation)); @@ -1690,6 +1687,15 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code this.java8Mode = enabled; } + public void setJava8ModeAndAdditionalProperties(boolean enabled) { + this.java8Mode = enabled; + if (this.java8Mode) { + this.additionalProperties.put("java8", true); + } else { + this.additionalProperties.put("java8", false); + } + } + public void setSupportAsync(boolean enabled) { this.supportAsync = enabled; } @@ -1838,7 +1844,7 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code if (exitValue != 0) { LOGGER.error("Error running the command ({}). Exit value: {}", command, exitValue); } else { - LOGGER.info("Successfully executed: " + command); + LOGGER.info("Successfully executed: {}", command); } } catch (InterruptedException | IOException e) { LOGGER.error("Error running the command ({}). Exception: {}", command, e.getMessage()); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractJavaJAXRSServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractJavaJAXRSServerCodegen.java index 8ee05fcd3e4..e631ae130fa 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractJavaJAXRSServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractJavaJAXRSServerCodegen.java @@ -305,6 +305,7 @@ public abstract class AbstractJavaJAXRSServerCodegen extends AbstractJavaCodegen return outputFolder + "/" + output + "/" + apiPackage().replace('.', '/'); } + @Override public void setUseBeanValidation(boolean useBeanValidation) { this.useBeanValidation = useBeanValidation; } 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 e3d4204a8d6..2506f6d7e0c 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 @@ -125,7 +125,11 @@ public abstract class AbstractKotlinCodegen extends DefaultCodegen implements Co "val", "var", "when", - "while" + "while", + "private", + "open", + "external", + "internal" )); defaultIncludes = new HashSet(Arrays.asList( @@ -421,7 +425,7 @@ public abstract class AbstractKotlinCodegen extends DefaultCodegen implements Co } if (additionalProperties.containsKey(CodegenConstants.INVOKER_PACKAGE)) { - LOGGER.warn(CodegenConstants.INVOKER_PACKAGE + " with " + this.getName() + " generator is ignored. Use " + CodegenConstants.PACKAGE_NAME + "."); + LOGGER.warn("{} with {} generator is ignored. Use {}.", CodegenConstants.INVOKER_PACKAGE, this.getName(), CodegenConstants.PACKAGE_NAME); } if (additionalProperties.containsKey(CodegenConstants.SERIALIZABLE_MODEL)) { @@ -624,14 +628,15 @@ public abstract class AbstractKotlinCodegen extends DefaultCodegen implements Co // model name cannot use reserved keyword, e.g. return if (isReservedWord(modifiedName)) { final String modelName = "Model" + modifiedName; - LOGGER.warn(modifiedName + " (reserved word) cannot be used as model name. Renamed to " + modelName); + LOGGER.warn("{} (reserved word) cannot be used as model name. Renamed to {}", modifiedName, modelName); return modelName; } // model name starts with number if (modifiedName.matches("^\\d.*")) { final String modelName = "Model" + modifiedName; // e.g. 200Response => Model200Response (after camelize) - LOGGER.warn(name + " (model name starts with number) cannot be used as model name. Renamed to " + modelName); + LOGGER.warn("{} (model name starts with number) cannot be used as model name. Renamed to {}", name, + modelName); return modelName; } @@ -655,7 +660,7 @@ public abstract class AbstractKotlinCodegen extends DefaultCodegen implements Co // method name cannot use reserved keyword, e.g. return if (isReservedWord(operationId)) { String newOperationId = camelize("call_" + operationId, true); - LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + newOperationId); + LOGGER.warn("{} (reserved word) cannot be used as method name. Renamed to {}", operationId, newOperationId); return newOperationId; } @@ -890,7 +895,7 @@ public abstract class AbstractKotlinCodegen extends DefaultCodegen implements Co if (exitValue != 0) { LOGGER.error("Error running the command ({}). Exit value: {}", command, exitValue); } else { - LOGGER.info("Successfully executed: " + command); + LOGGER.info("Successfully executed: {}", command); } } catch (InterruptedException | IOException e) { LOGGER.error("Error running the command ({}). Exception: {}", command, e.getMessage()); 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 115e945d6ac..4e1f571a709 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 @@ -295,14 +295,15 @@ public abstract class AbstractPhpCodegen extends DefaultCodegen implements Codeg ArraySchema ap = (ArraySchema) p; Schema inner = ap.getItems(); if (inner == null) { - LOGGER.warn(ap.getName() + "(array property) does not have a proper inner type defined.Default to string"); + LOGGER.warn("{}(array property) does not have a proper inner type defined.Default to string", + ap.getName()); inner = new StringSchema().description("TODO default missing array inner type to string"); } return getTypeDeclaration(inner) + "[]"; } else if (ModelUtils.isMapSchema(p)) { Schema inner = getAdditionalProperties(p); if (inner == null) { - LOGGER.warn(p.getName() + "(map property) does not have a proper inner type defined. Default to string"); + LOGGER.warn("{}(map property) does not have a proper inner type defined. Default to string", p.getName()); inner = new StringSchema().description("TODO default missing map inner type to string"); } return getSchemaType(p) + ""; @@ -408,13 +409,14 @@ public abstract class AbstractPhpCodegen extends DefaultCodegen implements Codeg // model name cannot use reserved keyword if (isReservedWord(name)) { - LOGGER.warn(name + " (reserved word) cannot be used as model name. Renamed to " + camelize("model_" + name)); + LOGGER.warn("{} (reserved word) cannot be used as model name. Renamed to {}", name, camelize("model_" + name)); name = "model_" + name; // e.g. return => ModelReturn (after camelize) } // model name starts with number if (name.matches("^\\d.*")) { - LOGGER.warn(name + " (model name starts with number) cannot be used as model name. Renamed to " + camelize("model_" + name)); + LOGGER.warn("{} (model name starts with number) cannot be used as model name. Renamed to {}", name, + camelize("model_" + name)); name = "model_" + name; // e.g. 200Response => Model200Response (after camelize) } @@ -492,13 +494,13 @@ public abstract class AbstractPhpCodegen extends DefaultCodegen implements Codeg // method name cannot use reserved keyword, e.g. return if (isReservedWord(operationId)) { - LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + camelize(sanitizeName("call_" + operationId), true)); + LOGGER.warn("{} (reserved word) cannot be used as method name. Renamed to {}", operationId, camelize(sanitizeName("call_" + operationId), true)); operationId = "call_" + operationId; } // operationId starts with a number if (operationId.matches("^\\d.*")) { - LOGGER.warn(operationId + " (starting with a number) cannot be used as method name. Renamed to " + camelize(sanitizeName("call_" + operationId), true)); + LOGGER.warn("{} (starting with a number) cannot be used as method name. Renamed to {}", operationId, camelize(sanitizeName("call_" + operationId), true)); operationId = "call_" + operationId; } @@ -590,7 +592,7 @@ public abstract class AbstractPhpCodegen extends DefaultCodegen implements Codeg // type is a model class, e.g. User example = "new " + getTypeDeclaration(type) + "()"; } else { - LOGGER.warn("Type " + type + " not handled properly in setParameterExampleValue"); + LOGGER.warn("Type {} not handled properly in setParameterExampleValue", type); } if (example == null) { @@ -747,7 +749,7 @@ public abstract class AbstractPhpCodegen extends DefaultCodegen implements Codeg if (exitValue != 0) { LOGGER.error("Error running the command ({}). Exit value: {}", command, exitValue); } else { - LOGGER.info("Successfully executed: " + command); + LOGGER.info("Successfully executed: {}", command); } } catch (InterruptedException | IOException e) { LOGGER.error("Error running the command ({}). Exception: {}", command, e.getMessage()); 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 2765920fab4..eced1ac0e78 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 @@ -600,6 +600,7 @@ public abstract class AbstractPythonCodegen extends DefaultCodegen implements Co public void setPackageName(String packageName) { this.packageName = packageName; + additionalProperties.put(CodegenConstants.PACKAGE_NAME, this.packageName); } public void setProjectName(String projectName) { diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractPythonConnexionServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractPythonConnexionServerCodegen.java index 3898b7c09da..2e04cd2d3e6 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractPythonConnexionServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractPythonConnexionServerCodegen.java @@ -52,6 +52,7 @@ public abstract class AbstractPythonConnexionServerCodegen extends AbstractPytho // nose is a python testing framework, we use pytest if USE_NOSE is unset public static final String USE_NOSE = "useNose"; public static final String PYTHON_SRC_ROOT = "pythonSrcRoot"; + public static final String USE_PYTHON_SRC_ROOT_IN_IMPORTS = "usePythonSrcRootInImports"; static final String MEDIA_TYPE = "mediaType"; protected int serverPort = 8080; @@ -62,6 +63,7 @@ public abstract class AbstractPythonConnexionServerCodegen extends AbstractPytho protected boolean featureCORS = Boolean.FALSE; protected boolean useNose = Boolean.FALSE; protected String pythonSrcRoot; + protected boolean usePythonSrcRootInImports = Boolean.FALSE; public AbstractPythonConnexionServerCodegen(String templateDirectory, boolean fixBodyNameValue) { super(); @@ -79,7 +81,7 @@ public abstract class AbstractPythonConnexionServerCodegen extends AbstractPytho typeMapping.put("map", "Dict"); // set the output folder here - outputFolder = "generated-code/connexion"; + outputFolder = "generated-code" + File.separatorChar + "connexion"; apiTemplateFiles.put("controller.mustache", ".py"); modelTemplateFiles.put("model.mustache", ".py"); @@ -132,6 +134,8 @@ public abstract class AbstractPythonConnexionServerCodegen extends AbstractPytho defaultValue(Boolean.FALSE.toString())); cliOptions.add(new CliOption(PYTHON_SRC_ROOT, "put python sources in this subdirectory of output folder (defaults to \"\" for). Use this for src/ layout."). defaultValue("")); + cliOptions.add(new CliOption(USE_PYTHON_SRC_ROOT_IN_IMPORTS, "include pythonSrcRoot in import namespaces."). + defaultValue("false")); } protected void addSupportingFiles() { @@ -147,7 +151,6 @@ public abstract class AbstractPythonConnexionServerCodegen extends AbstractPytho setPackageName((String) additionalProperties.get(CodegenConstants.PACKAGE_NAME)); } else { setPackageName("openapi_server"); - additionalProperties.put(CodegenConstants.PACKAGE_NAME, this.packageName); } if (additionalProperties.containsKey(CodegenConstants.PACKAGE_VERSION)) { setPackageVersion((String) additionalProperties.get(CodegenConstants.PACKAGE_VERSION)); @@ -177,9 +180,19 @@ public abstract class AbstractPythonConnexionServerCodegen extends AbstractPytho if (additionalProperties.containsKey(USE_NOSE)) { setUseNose((String) additionalProperties.get(USE_NOSE)); } + if (additionalProperties.containsKey(USE_PYTHON_SRC_ROOT_IN_IMPORTS)) { + setUsePythonSrcRootInImports((String) additionalProperties.get(USE_PYTHON_SRC_ROOT_IN_IMPORTS)); + } if (additionalProperties.containsKey(PYTHON_SRC_ROOT)) { - setPythonSrcRoot((String) additionalProperties.get(PYTHON_SRC_ROOT)); - additionalProperties.put(PYTHON_SRC_ROOT, pythonSrcRoot); + String pythonSrcRoot = (String) additionalProperties.get(PYTHON_SRC_ROOT); + if (usePythonSrcRootInImports) { + // if we prepend the package name if the pythonSrcRoot we get the desired effect. + // but we also need to set pythonSrcRoot itself to "" to ensure all the paths are + // what we expect. + setPackageName(pythonSrcRoot + "." + packageName); + pythonSrcRoot = ""; + } + setPythonSrcRoot(pythonSrcRoot); } else { setPythonSrcRoot(""); } @@ -218,6 +231,11 @@ public abstract class AbstractPythonConnexionServerCodegen extends AbstractPytho } else { this.pythonSrcRoot = pySrcRoot + File.separator; } + additionalProperties.put(PYTHON_SRC_ROOT, StringUtils.defaultIfBlank(this.pythonSrcRoot, null)); + } + + public void setUsePythonSrcRootInImports(String val) { + this.usePythonSrcRootInImports = Boolean.parseBoolean(val); } @@ -325,7 +343,9 @@ public abstract class AbstractPythonConnexionServerCodegen extends AbstractPytho fixedPath += "/" + token; } if (!fixedPath.equals(pathname)) { - LOGGER.warn("Path '" + pathname + "' is not consistant with Python variable names. It will be replaced by '" + fixedPath + "'"); + LOGGER.warn( + "Path '{}' is not consistant with Python variable names. It will be replaced by '{}'", + pathname, fixedPath); paths.remove(pathname); path.addExtension("x-python-connexion-openapi-name", pathname); paths.put(fixedPath, path); @@ -355,12 +375,14 @@ public abstract class AbstractPythonConnexionServerCodegen extends AbstractPytho String swaggerParameterName = parameter.getName(); String pythonParameterName = this.toParamName(swaggerParameterName); if (!swaggerParameterName.equals(pythonParameterName)) { - LOGGER.warn("Parameter name '" + swaggerParameterName + "' is not consistant with Python variable names. It will be replaced by '" + pythonParameterName + "'"); + LOGGER.warn( + "Parameter name '{}' is not consistant with Python variable names. It will be replaced by '{}'", + swaggerParameterName, pythonParameterName); parameter.addExtension("x-python-connexion-openapi-name", swaggerParameterName); parameter.setName(pythonParameterName); } if (swaggerParameterName.isEmpty()) { - LOGGER.error("Missing parameter name in " + pathname + "." + parameter.getIn()); + LOGGER.error("Missing parameter name in {}.{}", pathname, parameter.getIn()); } } } @@ -417,13 +439,13 @@ public abstract class AbstractPythonConnexionServerCodegen extends AbstractPytho } break; case OPENIDCONNECT: - LOGGER.warn("Security type " + securityScheme.getType().toString() + " is not supported by connextion yet"); + LOGGER.warn("Security type {} is not supported by connextion yet", securityScheme.getType().toString()); case OAUTH2: addSecurityExtension(securityScheme, "x-tokenInfoFunc", baseFunctionName + "info_from_" + securityName); addSecurityExtension(securityScheme, "x-scopeValidateFunc", baseFunctionName + "validate_scope_" + securityName); break; default: - LOGGER.warn("Unknown security type " + securityScheme.getType().toString()); + LOGGER.warn("Unknown security type {}", securityScheme.getType().toString()); } } } @@ -480,7 +502,9 @@ public abstract class AbstractPythonConnexionServerCodegen extends AbstractPytho // Get and remove the (temporary) vendor extension String openapiPathname = (String) pathExtensions.remove("x-python-connexion-openapi-name"); if (openapiPathname != null && !openapiPathname.equals(pythonPathname)) { - LOGGER.info("Path '" + pythonPathname + "' is not consistant with the original OpenAPI definition. It will be replaced back by '" + openapiPathname + "'"); + LOGGER.info( + "Path '{}' is not consistant with the original OpenAPI definition. It will be replaced back by '{}'", + pythonPathname, openapiPathname); paths.remove(pythonPathname); paths.put(openapiPathname, path); } @@ -499,13 +523,18 @@ public abstract class AbstractPythonConnexionServerCodegen extends AbstractPytho if (swaggerParameterName != null) { String pythonParameterName = parameter.getName(); if (!swaggerParameterName.equals(pythonParameterName)) { - LOGGER.info("Reverting name of parameter '" + pythonParameterName + "' of operation '" + operation.getOperationId() + "' back to '" + swaggerParameterName + "'"); + LOGGER.info( + "Reverting name of parameter '{}' of operation '{}' back to '{}'", + pythonParameterName, operation.getOperationId(), swaggerParameterName); parameter.setName(swaggerParameterName); } else { - LOGGER.debug("Name of parameter '" + pythonParameterName + "' of operation '" + operation.getOperationId() + "' was unchanged."); + LOGGER.debug("Name of parameter '{}' of operation '{}' was unchanged.", + pythonParameterName, operation.getOperationId()); } } else { - LOGGER.debug("x-python-connexion-openapi-name was not set on parameter '" + parameter.getName() + "' of operation '" + operation.getOperationId() + "'"); + LOGGER.debug( + "x-python-connexion-openapi-name was not set on parameter '{}' of operation '{}'", + parameter.getName(), operation.getOperationId()); } } } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractRubyCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractRubyCodegen.java index 07c8a6e3cf6..040434952c0 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractRubyCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractRubyCodegen.java @@ -191,6 +191,7 @@ abstract public class AbstractRubyCodegen extends DefaultCodegen implements Code return varName; } + @Override public String toRegularExpression(String pattern) { return addRegularExpressionDelimiter(pattern); } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractScalaCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractScalaCodegen.java index 7ceb98d917e..7278c7fbc02 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractScalaCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractScalaCodegen.java @@ -164,6 +164,10 @@ public abstract class AbstractScalaCodegen extends DefaultCodegen { LOGGER.info("NOTE: To enable file post-processing, 'enablePostProcessFile' must be set to `true` (--enable-post-process-file for CLI)."); } + if (additionalProperties.containsKey(CodegenConstants.INVOKER_PACKAGE)) { + this.setInvokerPackage((String) additionalProperties.get(CodegenConstants.INVOKER_PACKAGE)); + } + if (additionalProperties.containsKey(CodegenConstants.SOURCE_FOLDER)) { this.setSourceFolder((String) additionalProperties.get(CodegenConstants.SOURCE_FOLDER)); } @@ -461,14 +465,15 @@ public abstract class AbstractScalaCodegen extends DefaultCodegen { // model name cannot use reserved keyword, e.g. return if (isReservedWord(camelizedName)) { final String modelName = "Model" + camelizedName; - LOGGER.warn(camelizedName + " (reserved word) cannot be used as model name. Renamed to " + modelName); + LOGGER.warn("{} (reserved word) cannot be used as model name. Renamed to {}", camelizedName, modelName); return modelName; } // model name starts with number if (name.matches("^\\d.*")) { final String modelName = "Model" + camelizedName; // e.g. 200Response => Model200Response (after camelize) - LOGGER.warn(name + " (model name starts with number) cannot be used as model name. Renamed to " + modelName); + LOGGER.warn("{} (model name starts with number) cannot be used as model name. Renamed to {}", name, + modelName); return modelName; } @@ -531,7 +536,7 @@ public abstract class AbstractScalaCodegen extends DefaultCodegen { if (exitValue != 0) { LOGGER.error("Error running the command ({}). Exit value: {}", command, exitValue); } else { - LOGGER.info("Successfully executed: " + command); + LOGGER.info("Successfully executed: {}", command); } } catch (InterruptedException | IOException e) { LOGGER.error("Error running the command ({}). Exception: {}", command, e.getMessage()); @@ -553,7 +558,7 @@ public abstract class AbstractScalaCodegen extends DefaultCodegen { // method name cannot use reserved keyword, e.g. return if (isReservedWord(operationId)) { String newOperationId = camelize("call_" + operationId, true); - LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + newOperationId); + LOGGER.warn("{} (reserved word) cannot be used as method name. Renamed to {}", operationId, newOperationId); return newOperationId; } 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 353c05d5a2e..8a7d8b97aaf 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 @@ -27,6 +27,7 @@ import org.apache.commons.io.FilenameUtils; import org.apache.commons.lang3.StringUtils; import org.openapitools.codegen.CodegenConstants.ENUM_PROPERTY_NAMING_TYPE; import org.openapitools.codegen.CodegenConstants.MODEL_PROPERTY_NAMING_TYPE; +import org.openapitools.codegen.CodegenConstants.PARAM_NAMING_TYPE; import org.openapitools.codegen.*; import org.openapitools.codegen.meta.features.*; import org.openapitools.codegen.utils.ModelUtils; @@ -64,6 +65,7 @@ public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen imp protected MODEL_PROPERTY_NAMING_TYPE modelPropertyNaming = MODEL_PROPERTY_NAMING_TYPE.original; protected ENUM_PROPERTY_NAMING_TYPE enumPropertyNaming = ENUM_PROPERTY_NAMING_TYPE.PascalCase; + protected PARAM_NAMING_TYPE paramNaming = PARAM_NAMING_TYPE.camelCase; protected Boolean supportsES6 = false; protected Boolean nullSafeAdditionalProps = false; protected HashSet languageGenericTypes; @@ -175,6 +177,7 @@ public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen imp cliOptions.add(new CliOption(CodegenConstants.ENUM_PROPERTY_NAMING, CodegenConstants.ENUM_PROPERTY_NAMING_DESC).defaultValue(this.enumPropertyNaming.name())); cliOptions.add(new CliOption(CodegenConstants.MODEL_PROPERTY_NAMING, MODEL_PROPERTY_NAMING_DESC_WITH_WARNING).defaultValue(this.modelPropertyNaming.name())); cliOptions.add(new CliOption(CodegenConstants.SUPPORTS_ES6, CodegenConstants.SUPPORTS_ES6_DESC).defaultValue(String.valueOf(this.getSupportsES6()))); + cliOptions.add(new CliOption(CodegenConstants.PARAM_NAMING, CodegenConstants.PARAM_NAMING_DESC).defaultValue(this.paramNaming.name())); this.cliOptions.add(new CliOption(NPM_NAME, "The name under which you want to publish generated npm package." + " Required to generate a full package")); this.cliOptions.add(new CliOption(NPM_VERSION, "The version of your npm package. If not provided, using the version from the OpenAPI specification file.").defaultValue(this.getNpmVersion())); @@ -212,6 +215,10 @@ public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen imp setModelPropertyNaming((String) additionalProperties.get(CodegenConstants.MODEL_PROPERTY_NAMING)); } + if (additionalProperties.containsKey(CodegenConstants.PARAM_NAMING)) { + setParamNaming((String) additionalProperties.get(CodegenConstants.PARAM_NAMING)); + } + if (additionalProperties.containsKey(CodegenConstants.SUPPORTS_ES6)) { setSupportsES6(Boolean.valueOf(additionalProperties.get(CodegenConstants.SUPPORTS_ES6).toString())); additionalProperties.put("supportsES6", getSupportsES6()); @@ -227,11 +234,15 @@ public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen imp } @Override - public String toModelImport( String name){ + public String toModelImport(String name){ if(isUnionType(name)){ LOGGER.warn("The import is a union type. Consider using the toModelImportMap method."); return toModelImportMap(name).values().stream().collect(Collectors.joining("|")); } + if(isIntersectionType(name)){ + LOGGER.warn("The import is a intersection type. Consider using the toModelImportMap method."); + return toModelImportMap(name).values().stream().collect(Collectors.joining("&")); + } return super.toModelImport(name); } @@ -243,26 +254,28 @@ public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen imp * @return Map between the fully qualified model import and the initial given name. */ @Override - public Map toModelImportMap( String name){ - if(isUnionType(name)){ - String[] names = splitUnionType(name); - return toImportMap(names); - } - return toImportMap(name); + public Map toModelImportMap(String name){ + return toImportMap(splitComposedType(name)); + } + + private String[] splitComposedType (String name) { + return name.replace(" ","").split("[|&<>]"); } private boolean isUnionType(String name){ return name.contains("|"); } - private String[] splitUnionType(String name){ - return name.replace(" ","").split("\\|"); + private boolean isIntersectionType(String name){ + return name.contains("&"); } private Map toImportMap(String... names){ Map result = Maps.newHashMap(); for(String name: names){ - result.put(toModelImport(name),name); + if(needToImport(name)){ + result.put(toModelImport(name), name); + } } return result; } @@ -324,7 +337,7 @@ public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen imp name = "_u"; } - name = camelize(name, true); + name = getNameUsingParamNaming(name); name = toSafeIdentifier(name); return name; @@ -384,20 +397,22 @@ public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen imp // this is unlikely to happen, because we have just camelized the name, while reserved words are usually all lowcase if (isReservedWord(sanName)) { String modelName = safePrefix + sanName; - LOGGER.warn(sanName + " (reserved word) cannot be used as model name. Renamed to " + modelName); + LOGGER.warn("{} (reserved word) cannot be used as model name. Renamed to {}", sanName, modelName); return modelName; } // model name starts with number if (sanName.matches("^\\d.*")) { String modelName = safePrefix + sanName; // e.g. 200Response => Model200Response - LOGGER.warn(sanName + " (model name starts with number) cannot be used as model name. Renamed to " + modelName); + LOGGER.warn("{} (model name starts with number) cannot be used as model name. Renamed to {}", sanName, + modelName); return modelName; } if (languageSpecificPrimitives.contains(sanName)) { String modelName = safePrefix + sanName; - LOGGER.warn(sanName + " (model name matches existing language type) cannot be used as a model name. Renamed to " + modelName); + LOGGER.warn("{} (model name matches existing language type) cannot be used as a model name. Renamed to {}", + sanName, modelName); return modelName; } @@ -589,10 +604,45 @@ public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen imp } } + public void setParamNaming(String naming) { + try { + paramNaming = PARAM_NAMING_TYPE.valueOf(naming); + } catch (IllegalArgumentException e) { + String values = Stream.of(PARAM_NAMING_TYPE.values()) + .map(value -> "'" + value.name() + "'") + .collect(Collectors.joining(", ")); + + String msg = String.format(Locale.ROOT, "Invalid parameter naming '%s'. Must be one of %s.", naming, values); + throw new IllegalArgumentException(msg); + } + } + public MODEL_PROPERTY_NAMING_TYPE getModelPropertyNaming() { return modelPropertyNaming; } + public PARAM_NAMING_TYPE getParamNaming() { + return paramNaming; + } + + private String getNameUsingParamNaming(String name) { + switch (getParamNaming()) { + case original: + return name; + case camelCase: + return camelize(name, true); + case PascalCase: + return camelize(name); + case snake_case: + return underscore(name); + default: + throw new IllegalArgumentException("Invalid param naming '" + + name + "'. Must be 'original', 'camelCase', " + + "'PascalCase' or 'snake_case'"); + } + + } + private String getNameUsingModelPropertyNaming(String name) { switch (getModelPropertyNaming()) { case original: @@ -613,7 +663,7 @@ public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen imp @Override public String toEnumValue(String value, String datatype) { - if ("number".equals(datatype)) { + if ("number".equals(datatype) || "boolean".equals(datatype)) { return value; } else { return "\'" + escapeText(value) + "\'"; @@ -707,7 +757,7 @@ public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen imp return; } - String[] parts = type.split("( [|&] )|[<>]"); + String[] parts = splitComposedType(type); for (String s : parts) { if (needToImport(s)) { m.imports.add(s); @@ -854,7 +904,7 @@ public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen imp if (exitValue != 0) { LOGGER.error("Error running the command ({}). Exit value: {}", command, exitValue); } else { - LOGGER.info("Successfully executed: " + command); + LOGGER.info("Successfully executed: {}", command); } } catch (InterruptedException | IOException e) { LOGGER.error("Error running the command ({}). Exception: {}", command, e.getMessage()); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AndroidClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AndroidClientCodegen.java index 2fa04946c81..d3ead4fc86d 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AndroidClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AndroidClientCodegen.java @@ -301,14 +301,15 @@ public class AndroidClientCodegen extends DefaultCodegen implements CodegenConfi // model name cannot use reserved keyword, e.g. return if (isReservedWord(name)) { String modelName = "Model" + name; - LOGGER.warn(name + " (reserved word) cannot be used as model name. Renamed to " + modelName); + LOGGER.warn("{} (reserved word) cannot be used as model name. Renamed to {}", name, modelName); return modelName; } // model name starts with number if (name.matches("^\\d.*")) { String modelName = "Model" + name; // e.g. 200Response => Model200Response (after camelize) - LOGGER.warn(name + " (model name starts with number) cannot be used as model name. Renamed to " + modelName); + LOGGER.warn("{} (model name starts with number) cannot be used as model name. Renamed to {}", name, + modelName); return modelName; } @@ -398,7 +399,7 @@ public class AndroidClientCodegen extends DefaultCodegen implements CodegenConfi // method name cannot use reserved keyword, e.g. return if (isReservedWord(operationId)) { String newOperationId = camelize("call_" + operationId, true); - LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + newOperationId); + LOGGER.warn("{} (reserved word) cannot be used as method name. Renamed to {}", operationId, newOperationId); return newOperationId; } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AsciidocDocumentationCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AsciidocDocumentationCodegen.java index 6c2dd4ac434..fa66f2a33a2 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AsciidocDocumentationCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AsciidocDocumentationCodegen.java @@ -89,10 +89,10 @@ public class AsciidocDocumentationCodegen extends DefaultCodegen implements Code String includeStatement = "include::{" + attributePathReference + "}" + escapeCurlyBrackets(relativeFileName) + "[opts=optional]"; if (Files.isRegularFile(filePathToInclude)) { - LOGGER.debug("including " + ++includeCount + ". file into markup from: " + filePathToInclude.toString()); + LOGGER.debug("including {}. file into markup from: {}", ++includeCount, filePathToInclude.toString()); out.write("\n" + includeStatement + "\n"); } else { - LOGGER.debug(++notFoundCount + ". file not found, skip include for: " + filePathToInclude.toString()); + LOGGER.debug("{}. file not found, skip include for: {}", ++notFoundCount, filePathToInclude.toString()); out.write("\n// markup not found, no " + includeStatement + "\n"); } } @@ -140,10 +140,10 @@ public class AsciidocDocumentationCodegen extends DefaultCodegen implements Code final Path filePathToLinkTo = Paths.get(basePath, relativeFileName).toAbsolutePath(); if (Files.isRegularFile(filePathToLinkTo)) { - LOGGER.debug("linking " + ++linkedCount + ". file into markup from: " + filePathToLinkTo.toString()); + LOGGER.debug("linking {}. file into markup from: {}", ++linkedCount, filePathToLinkTo.toString()); out.write("\n" + linkName + " link:" + relativeFileName + "[]\n"); } else { - LOGGER.debug(++notFoundLinkCount + ". file not found, skip link for: " + filePathToLinkTo.toString()); + LOGGER.debug("{}. file not found, skip link for: {}", ++notFoundLinkCount, filePathToLinkTo.toString()); out.write("\n// file not found, no " + linkName + " link :" + relativeFileName + "[]\n"); } } @@ -163,6 +163,7 @@ public class AsciidocDocumentationCodegen extends DefaultCodegen implements Code private IncludeMarkupLambda includeSnippetMarkupLambda; private LinkMarkupLambda linkSnippetMarkupLambda; + @Override public CodegenType getTag() { return CodegenType.DOCUMENTATION; } @@ -181,10 +182,12 @@ public class AsciidocDocumentationCodegen extends DefaultCodegen implements Code return sanitized.startsWith(File.separator) || sanitized.startsWith("/") ? sanitized.substring(1) : sanitized; } + @Override public String getName() { return "asciidoc"; } + @Override public String getHelp() { return "Generates asciidoc markup based documentation."; } @@ -324,8 +327,7 @@ public class AsciidocDocumentationCodegen extends DefaultCodegen implements Code String specDir = this.additionalProperties.get(SPEC_DIR) + ""; if (!Files.isDirectory(Paths.get(specDir))) { - LOGGER.warn("base part for include markup lambda not found: " + specDir + " as " - + Paths.get(specDir).toAbsolutePath()); + LOGGER.warn("base part for include markup lambda not found: {} as {}", specDir, Paths.get(specDir).toAbsolutePath()); } this.includeSpecMarkupLambda = new IncludeMarkupLambda(SPEC_DIR,specDir); @@ -333,8 +335,7 @@ public class AsciidocDocumentationCodegen extends DefaultCodegen implements Code String snippetDir = this.additionalProperties.get(SNIPPET_DIR) + ""; if (!Files.isDirectory(Paths.get(snippetDir))) { - LOGGER.warn("base part for include markup lambda not found: " + snippetDir + " as " - + Paths.get(snippetDir).toAbsolutePath()); + LOGGER.warn("base part for include markup lambda not found: {} as {}", snippetDir, Paths.get(snippetDir).toAbsolutePath()); } this.includeSnippetMarkupLambda = new IncludeMarkupLambda(SNIPPET_DIR,snippetDir); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AspNetCoreServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AspNetCoreServerCodegen.java index f7c24196331..16957ff6b3b 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AspNetCoreServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AspNetCoreServerCodegen.java @@ -209,6 +209,10 @@ public class AspNetCoreServerCodegen extends AbstractCSharpCodegen { cliOptions.add(swashbuckleVersion); // CLI Switches + addSwitch(CodegenConstants.NULLABLE_REFERENCE_TYPES, + CodegenConstants.NULLABLE_REFERENCE_TYPES_DESC, + this.nullReferenceTypesFlag); + addSwitch(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG_DESC, sortParamsByRequiredFlag); @@ -261,7 +265,7 @@ public class AspNetCoreServerCodegen extends AbstractCSharpCodegen { classModifier.addEnum("abstract", "Make class abstract"); classModifier.setDefault(""); classModifier.setOptValue(classModifier.getDefault()); - cliOptions.add(classModifier); + addOption(classModifier.getOpt(), classModifier.getDescription(), classModifier.getOptValue()); operationModifier.addEnum("virtual", "Keep method virtual"); operationModifier.addEnum("abstract", "Make method abstract"); @@ -292,7 +296,7 @@ public class AspNetCoreServerCodegen extends AbstractCSharpCodegen { modelClassModifier.addEnum("partial", "Make model class partial"); modelClassModifier.setDefault("partial"); modelClassModifier.setOptValue(modelClassModifier.getDefault()); - cliOptions.add(modelClassModifier); + addOption(modelClassModifier.getOpt(), modelClassModifier.getDescription(), modelClassModifier.getOptValue()); } @Override @@ -435,7 +439,7 @@ public class AspNetCoreServerCodegen extends AbstractCSharpCodegen { String original = operation.path; operation.path = operation.path.replace("?", "/"); if (!original.equals(operation.path)) { - LOGGER.warn("Normalized " + original + " to " + operation.path + ". Please verify generated source."); + LOGGER.warn("Normalized {} to {}. Please verify generated source.", original, operation.path); } } @@ -520,7 +524,7 @@ public class AspNetCoreServerCodegen extends AbstractCSharpCodegen { @Override public String getNullableType(Schema p, String type) { if (languageSpecificPrimitives.contains(type)) { - if (isSupportNullable() && ModelUtils.isNullable(p) && nullableType.contains(type)) { + if (isSupportNullable() && ModelUtils.isNullable(p) && (nullableType.contains(type) || nullReferenceTypesFlag)) { return type + "?"; } else { return type; @@ -559,7 +563,7 @@ public class AspNetCoreServerCodegen extends AbstractCSharpCodegen { if ("abstract".equals(classModifier.getOptValue())) { operationModifier.setOptValue(classModifier.getOptValue()); additionalProperties.put(OPERATION_MODIFIER, operationModifier.getOptValue()); - LOGGER.warn("classModifier is " + classModifier.getOptValue() + " so forcing operatonModifier to " + operationModifier.getOptValue()); + LOGGER.warn("classModifier is {} so forcing operatonModifier to {}", classModifier.getOptValue(), operationModifier.getOptValue()); } } @@ -570,7 +574,7 @@ public class AspNetCoreServerCodegen extends AbstractCSharpCodegen { if ("abstract".equals(operationModifier.getOptValue())) { generateBody = false; additionalProperties.put(GENERATE_BODY, generateBody); - LOGGER.warn("operationModifier is " + operationModifier.getOptValue() + " so forcing generateBody to " + generateBody); + LOGGER.warn("operationModifier is {} so forcing generateBody to {}", operationModifier.getOptValue(), generateBody); } else if (additionalProperties.containsKey(GENERATE_BODY)) { generateBody = convertPropertyToBooleanAndWriteBack(GENERATE_BODY); } else { @@ -585,7 +589,7 @@ public class AspNetCoreServerCodegen extends AbstractCSharpCodegen { if (isLibrary) { modelClassModifier.setOptValue(""); additionalProperties.put(MODEL_CLASS_MODIFIER, modelClassModifier.getOptValue()); - LOGGER.warn("buildTarget is " + buildTarget.getOptValue() + " so removing any modelClassModifier "); + LOGGER.warn("buildTarget is {} so removing any modelClassModifier ", buildTarget.getOptValue()); } } @@ -614,7 +618,7 @@ public class AspNetCoreServerCodegen extends AbstractCSharpCodegen { // default, do nothing compatibilityVersion = "Version_" + aspnetCoreVersion.getOptValue().replace(".", "_"); } - LOGGER.info("ASP.NET core version: " + aspnetCoreVersion.getOptValue()); + LOGGER.info("ASP.NET core version: {}", aspnetCoreVersion.getOptValue()); if(!additionalProperties.containsKey(CodegenConstants.TEMPLATE_DIR)){ templateDir = embeddedTemplateDir = "aspnetcore" + File.separator + determineTemplateVersion(aspnetCoreVersion.getOptValue()); } @@ -662,12 +666,16 @@ public class AspNetCoreServerCodegen extends AbstractCSharpCodegen { private void setIsFramework() { if (aspnetCoreVersion.getOptValue().startsWith("3.")) {// default, do nothing - LOGGER.warn("ASP.NET core version is " + aspnetCoreVersion.getOptValue() + " so changing to use frameworkReference instead of packageReference "); + 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, "netcoreapp" + aspnetCoreVersion.getOptValue()); } else if (aspnetCoreVersion.getOptValue().startsWith("5.")) {// default, do nothing - LOGGER.warn("ASP.NET core version is " + aspnetCoreVersion.getOptValue() + " so changing to use frameworkReference instead of packageReference "); + 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, "net5.0"); @@ -684,7 +692,7 @@ public class AspNetCoreServerCodegen extends AbstractCSharpCodegen { private void setUseNewtonsoft() { if (aspnetCoreVersion.getOptValue().startsWith("2.")) { LOGGER.warn("ASP.NET core version 2.X support has been deprecated. Please use ASP.NET core version 3.1 instead"); - LOGGER.warn("ASP.NET core version is " + aspnetCoreVersion.getOptValue() + " so staying on default json library."); + LOGGER.warn("ASP.NET core version is {} so staying on default json library.", aspnetCoreVersion.getOptValue()); useNewtonsoft = false; additionalProperties.put(USE_NEWTONSOFT, useNewtonsoft); } else { @@ -698,7 +706,7 @@ public class AspNetCoreServerCodegen extends AbstractCSharpCodegen { private void setUseEndpointRouting() { if (aspnetCoreVersion.getOptValue().startsWith("3.") || aspnetCoreVersion.getOptValue().startsWith("5.")) { - LOGGER.warn("ASP.NET core version is " + aspnetCoreVersion.getOptValue() + " so switching to old style endpoint routing."); + LOGGER.warn("ASP.NET core version is {} so switching to old style endpoint routing.", aspnetCoreVersion.getOptValue()); useDefaultRouting = false; additionalProperties.put(USE_DEFAULT_ROUTING, useDefaultRouting); } else { @@ -714,12 +722,12 @@ public class AspNetCoreServerCodegen extends AbstractCSharpCodegen { setCliOption(swashbuckleVersion); if (aspnetCoreVersion.getOptValue().startsWith("3.") || aspnetCoreVersion.getOptValue().startsWith("5.")) { - LOGGER.warn("ASP.NET core version is " + aspnetCoreVersion.getOptValue() + " so changing default Swashbuckle version to 5.0.0."); + LOGGER.warn("ASP.NET core version is {} so changing default Swashbuckle version to 5.0.0.", aspnetCoreVersion.getOptValue()); swashbuckleVersion.setOptValue("5.0.0"); additionalProperties.put(SWASHBUCKLE_VERSION, swashbuckleVersion.getOptValue()); } else { // default, do nothing - LOGGER.info("Swashbuckle version: " + swashbuckleVersion.getOptValue()); + LOGGER.info("Swashbuckle version: {}", swashbuckleVersion.getOptValue()); } } } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/BashClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/BashClientCodegen.java index ea212c92f18..8f2c32f2a7e 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/BashClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/BashClientCodegen.java @@ -75,6 +75,7 @@ public class BashClientCodegen extends DefaultCodegen implements CodegenConfig { * * @return the CodegenType for this generator */ + @Override public CodegenType getTag() { return CodegenType.CLIENT; } @@ -85,6 +86,7 @@ public class BashClientCodegen extends DefaultCodegen implements CodegenConfig { * * @return the friendly name for the generator */ + @Override public String getName() { return "bash"; } @@ -95,6 +97,7 @@ public class BashClientCodegen extends DefaultCodegen implements CodegenConfig { * * @return A string value for the help message */ + @Override public String getHelp() { return "Generates a Bash client script based on cURL."; } @@ -380,6 +383,7 @@ public class BashClientCodegen extends DefaultCodegen implements CodegenConfig { * Location to write model files. You can use the modelPackage() as defined * when the class is instantiated. */ + @Override public String modelFileFolder() { return outputFolder; } @@ -497,7 +501,7 @@ public class BashClientCodegen extends DefaultCodegen implements CodegenConfig { } else if ("pipes".equals(p.collectionFormat)) { p.vendorExtensions.put("x-codegen-collection-pipes", true); } else { - LOGGER.warn("Unsupported collection format in Bash generator: " + p.collectionFormat); + LOGGER.warn("Unsupported collection format in Bash generator: {}", p.collectionFormat); } } } @@ -509,6 +513,7 @@ public class BashClientCodegen extends DefaultCodegen implements CodegenConfig { /** * Override with any special text escaping logic */ + @Override @SuppressWarnings("static-method") public String escapeText(String input) { if (input == null) { @@ -605,6 +610,7 @@ public class BashClientCodegen extends DefaultCodegen implements CodegenConfig { * @param input String to be cleaned up * @return string with unsafe characters removed or escaped */ + @Override public String escapeUnsafeCharacters(String input) { /** @@ -778,7 +784,7 @@ public class BashClientCodegen extends DefaultCodegen implements CodegenConfig { } else if ("array".equalsIgnoreCase(type) || "map".equalsIgnoreCase(type)) { // skip map/array as it will be handled below } else { - LOGGER.warn("Type " + type + " not handled properly in setParameterExampleValue"); + LOGGER.warn("Type {} not handled properly in setParameterExampleValue", type); } if (example == null) { @@ -802,20 +808,20 @@ public class BashClientCodegen extends DefaultCodegen implements CodegenConfig { // rename to empty_method_name_1 (e.g.) if method name is empty if (StringUtils.isEmpty(operationId)) { operationId = camelize("empty_method_name_" + emptyMethodNameCounter++, true); - LOGGER.warn("Empty method name (operationId) found. Renamed to " + operationId); + LOGGER.warn("Empty method name (operationId) found. Renamed to {}", operationId); return operationId; } // method name cannot use reserved keyword, e.g. return if (isReservedWord(operationId)) { String newOperationId = underscore("call" + camelize(operationId)); - LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + newOperationId); + LOGGER.warn("{} (reserved word) cannot be used as method name. Renamed to {}", operationId, newOperationId); return newOperationId; } // operationId starts with a number if (operationId.matches("^\\d.*")) { - LOGGER.warn(operationId + " (starting with a number) cannot be used as method name. Renamed to " + underscore(sanitizeName("call_" + operationId))); + LOGGER.warn("{} (starting with a number) cannot be used as method name. Renamed to {}", operationId, underscore(sanitizeName("call_" + operationId))); operationId = "call_" + operationId; } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CLibcurlClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CLibcurlClientCodegen.java index 78c6e2507e5..4c7a0c74160 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CLibcurlClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CLibcurlClientCodegen.java @@ -519,7 +519,7 @@ public class CLibcurlClientCodegen extends DefaultCodegen implements CodegenConf } else if (ModelUtils.isObjectSchema(schema)) { return null; // models are managed at moustache level } else { - LOGGER.warn("Type " + schema.getType() + " not handled properly in toExampleValue"); + LOGGER.warn("Type {} not handled properly in toExampleValue", schema.getType()); } if (ModelUtils.isStringSchema(schema)) { @@ -593,13 +593,14 @@ public class CLibcurlClientCodegen extends DefaultCodegen implements CodegenConf // model name cannot use reserved keyword, e.g. return if (isReservedWord(name)) { String modelName = camelize("Model" + name); - LOGGER.warn(name + " (reserved word) cannot be used as model name. Renamed to " + modelName); + LOGGER.warn("{} (reserved word) cannot be used as model name. Renamed to {}", name, modelName); return modelName; } // model name starts with number if (name.matches("^\\d.*")) { - LOGGER.warn(name + " (model name starts with number) cannot be used as model name. Renamed to " + camelize("model_" + name)); + LOGGER.warn("{} (model name starts with number) cannot be used as model name. Renamed to {}", name, + camelize("model_" + name)); name = "model_" + name; // e.g. 200Response => Model200Response (after camelize) } @@ -719,21 +720,21 @@ public class CLibcurlClientCodegen extends DefaultCodegen implements CodegenConf // rename to empty_method_name_1 (e.g.) if method name is empty if (StringUtils.isEmpty(operationId)) { operationId = camelize("empty_method_name_" + emptyMethodNameCounter++); - LOGGER.warn("Empty method name (operationId) found. Renamed to " + operationId); + LOGGER.warn("Empty method name (operationId) found. Renamed to {}", operationId); return operationId; } // method name cannot use reserved keyword, e.g. return if (isReservedWord(operationId)) { String newOperationId = camelize(sanitizeName("call_" + operationId), true); - LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + newOperationId); + LOGGER.warn("{} (reserved word) cannot be used as method name. Renamed to {}", operationId, newOperationId); return newOperationId; } // operationId starts with a number if (operationId.matches("^\\d.*")) { String newOperationId = camelize(sanitizeName("call_" + operationId), true); - LOGGER.warn(operationId + " (starting with a number) cannot be used as method name. Renamed to " + newOperationId); + LOGGER.warn("{} (starting with a number) cannot be used as method name. Renamed to {}", operationId, newOperationId); return newOperationId; } @@ -889,7 +890,7 @@ public class CLibcurlClientCodegen extends DefaultCodegen implements CodegenConf if (exitValue != 0) { LOGGER.error("Error running the command ({}). Exit code: {}", command, exitValue); } else { - LOGGER.info("Successfully executed: " + command); + LOGGER.info("Successfully executed: {}", command); } } catch (InterruptedException | IOException e) { LOGGER.error("Error running the command ({}). Exception: {}", command, e.getMessage()); 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 052868899f2..f69ffd9237f 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 @@ -311,7 +311,7 @@ public class CSharpClientCodegen extends AbstractCSharpCodegen { LOGGER.warn(".NET Standard 1.3 support has been DEPRECATED in this generator. Please use `csharp-netcore` generator instead."); additionalProperties.put(MCS_NET_VERSION_KEY, "4.6-api"); if (additionalProperties.containsKey("supportsUWP")) { - LOGGER.warn(".NET " + NETSTANDARD + " generator does not support UWP."); + LOGGER.warn(".NET {} generator does not support UWP.", NETSTANDARD); additionalProperties.remove("supportsUWP"); } @@ -332,7 +332,7 @@ public class CSharpClientCodegen extends AbstractCSharpCodegen { } else if (NET40.equals(this.targetFramework)) { additionalProperties.put(MCS_NET_VERSION_KEY, "4"); if (additionalProperties.containsKey(CodegenConstants.SUPPORTS_ASYNC)) { - LOGGER.warn(".NET " + NET40 + " generator does not support async."); + LOGGER.warn(".NET {} generator does not support async.", NET40); additionalProperties.remove(CodegenConstants.SUPPORTS_ASYNC); } @@ -350,13 +350,13 @@ public class CSharpClientCodegen extends AbstractCSharpCodegen { if (additionalProperties.containsKey(CodegenConstants.GENERATE_PROPERTY_CHANGED)) { if (NET35.equals(targetFramework)) { - LOGGER.warn(CodegenConstants.GENERATE_PROPERTY_CHANGED + " is only supported by generated code for .NET 4+."); + LOGGER.warn("{} is only supported by generated code for .NET 4+.", CodegenConstants.GENERATE_PROPERTY_CHANGED); additionalProperties.remove(CodegenConstants.GENERATE_PROPERTY_CHANGED); } else if (NETSTANDARD.equals(targetFramework)) { - LOGGER.warn(CodegenConstants.GENERATE_PROPERTY_CHANGED + " is not supported in .NET Standard generated code."); + LOGGER.warn("{} is not supported in .NET Standard generated code.", CodegenConstants.GENERATE_PROPERTY_CHANGED); additionalProperties.remove(CodegenConstants.GENERATE_PROPERTY_CHANGED); } else if (Boolean.TRUE.equals(netCoreProjectFileFlag)) { - LOGGER.warn(CodegenConstants.GENERATE_PROPERTY_CHANGED + " is not supported in .NET Core csproj project format."); + LOGGER.warn("{} is not supported in .NET Core csproj project format.", CodegenConstants.GENERATE_PROPERTY_CHANGED); additionalProperties.remove(CodegenConstants.GENERATE_PROPERTY_CHANGED); } else { setGeneratePropertyChanged(convertPropertyToBooleanAndWriteBack(CodegenConstants.GENERATE_PROPERTY_CHANGED)); @@ -714,7 +714,7 @@ public class CSharpClientCodegen extends AbstractCSharpCodegen { public void setTargetFramework(String dotnetFramework) { if (!frameworks.containsKey(dotnetFramework)) { - LOGGER.warn("Invalid .NET framework version, defaulting to " + this.targetFramework); + LOGGER.warn("Invalid .NET framework version, defaulting to {}", this.targetFramework); } else { this.targetFramework = dotnetFramework; } @@ -758,7 +758,7 @@ public class CSharpClientCodegen extends AbstractCSharpCodegen { break; } - LOGGER.info("Generating code for .NET Framework " + this.targetFramework); + LOGGER.info("Generating code for .NET Framework {}", this.targetFramework); } private CodegenModel reconcileInlineEnums(CodegenModel codegenModel, CodegenModel parentCodegenModel) { @@ -874,10 +874,12 @@ public class CSharpClientCodegen extends AbstractCSharpCodegen { } } + @Override public void setPackageName(String packageName) { this.packageName = packageName; } + @Override public void setPackageVersion(String packageVersion) { this.packageVersion = packageVersion; } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CSharpNancyFXServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CSharpNancyFXServerCodegen.java index 74db8d4ca2d..a99243ab359 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CSharpNancyFXServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CSharpNancyFXServerCodegen.java @@ -268,7 +268,7 @@ public class CSharpNancyFXServerCodegen extends AbstractCSharpCodegen { } private void postProcessParentModels(final Map models) { - LOGGER.debug("Processing parents: " + parentModels); + LOGGER.debug("Processing parents: {}", parentModels); for (final String parent : parentModels) { final CodegenModel parentModel = ModelUtils.getModelByName(parent, models); if (parentModel != null) { diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CSharpNetCoreClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CSharpNetCoreClientCodegen.java index ff90d1e30e2..2e0a3bd1223 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CSharpNetCoreClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CSharpNetCoreClientCodegen.java @@ -230,6 +230,10 @@ public class CSharpNetCoreClientCodegen extends AbstractCSharpCodegen { cliOptions.add(modelPropertyNaming.defaultValue("PascalCase")); // CLI Switches + addSwitch(CodegenConstants.NULLABLE_REFERENCE_TYPES, + CodegenConstants.NULLABLE_REFERENCE_TYPES_DESC, + this.nullReferenceTypesFlag); + addSwitch(CodegenConstants.HIDE_GENERATION_TIMESTAMP, CodegenConstants.HIDE_GENERATION_TIMESTAMP_DESC, this.hideGenerationTimestamp); @@ -261,6 +265,10 @@ public class CSharpNetCoreClientCodegen extends AbstractCSharpCodegen { addSwitch(CodegenConstants.OPTIONAL_EMIT_DEFAULT_VALUES, CodegenConstants.OPTIONAL_EMIT_DEFAULT_VALUES_DESC, this.optionalEmitDefaultValuesFlag); + + addSwitch(CodegenConstants.OPTIONAL_CONDITIONAL_SERIALIZATION, + CodegenConstants.OPTIONAL_CONDITIONAL_SERIALIZATION_DESC, + this.conditionalSerialization); addSwitch(CodegenConstants.OPTIONAL_PROJECT_FILE, CodegenConstants.OPTIONAL_PROJECT_FILE_DESC, @@ -566,6 +574,12 @@ public class CSharpNetCoreClientCodegen extends AbstractCSharpCodegen { additionalProperties.put(CodegenConstants.OPTIONAL_EMIT_DEFAULT_VALUES, optionalEmitDefaultValuesFlag); } + if (additionalProperties.containsKey(CodegenConstants.OPTIONAL_CONDITIONAL_SERIALIZATION)) { + setConditionalSerialization(convertPropertyToBooleanAndWriteBack(CodegenConstants.OPTIONAL_CONDITIONAL_SERIALIZATION)); + } else { + additionalProperties.put(CodegenConstants.OPTIONAL_CONDITIONAL_SERIALIZATION, conditionalSerialization); + } + if (additionalProperties.containsKey(CodegenConstants.MODEL_PROPERTY_NAMING)) { setModelPropertyNaming((String) additionalProperties.get(CodegenConstants.MODEL_PROPERTY_NAMING)); } @@ -639,7 +653,7 @@ public class CSharpNetCoreClientCodegen extends AbstractCSharpCodegen { } if (additionalProperties.containsKey(CodegenConstants.GENERATE_PROPERTY_CHANGED)) { - LOGGER.warn(CodegenConstants.GENERATE_PROPERTY_CHANGED + " is not supported in the .NET Standard generator."); + LOGGER.warn("{} is not supported in the .NET Standard generator.", CodegenConstants.GENERATE_PROPERTY_CHANGED); additionalProperties.remove(CodegenConstants.GENERATE_PROPERTY_CHANGED); } @@ -681,6 +695,11 @@ public class CSharpNetCoreClientCodegen extends AbstractCSharpCodegen { binRelativePath += "vendor"; additionalProperties.put("binRelativePath", binRelativePath); + if(HTTPCLIENT.equals(getLibrary())) { + supportingFiles.add(new SupportingFile("FileParameter.mustache", clientPackageDir, "FileParameter.cs")); + typeMapping.put("file", "FileParameter"); + } + supportingFiles.add(new SupportingFile("IApiAccessor.mustache", clientPackageDir, "IApiAccessor.cs")); supportingFiles.add(new SupportingFile("Configuration.mustache", clientPackageDir, "Configuration.cs")); supportingFiles.add(new SupportingFile("ApiClient.mustache", clientPackageDir, "ApiClient.cs")); @@ -750,6 +769,10 @@ public class CSharpNetCoreClientCodegen extends AbstractCSharpCodegen { this.optionalEmitDefaultValuesFlag = flag; } + public void setConditionalSerialization(boolean flag){ + this.conditionalSerialization = flag; + } + public void setOptionalProjectFileFlag(boolean flag) { this.optionalProjectFileFlag = flag; } @@ -758,10 +781,12 @@ public class CSharpNetCoreClientCodegen extends AbstractCSharpCodegen { this.packageGuid = packageGuid; } + @Override public void setPackageName(String packageName) { this.packageName = packageName; } + @Override public void setPackageVersion(String packageVersion) { this.packageVersion = packageVersion; } @@ -784,7 +809,7 @@ public class CSharpNetCoreClientCodegen extends AbstractCSharpCodegen { } else { this.targetFramework = dotnetFramework; } - LOGGER.info("Generating code for .NET Framework " + this.targetFramework); + LOGGER.info("Generating code for .NET Framework {}", this.targetFramework); } public void setTargetFramework(List strategies) { @@ -799,7 +824,7 @@ public class CSharpNetCoreClientCodegen extends AbstractCSharpCodegen { } this.targetFramework = strategies.stream().map(p -> p.name) .collect(Collectors.joining(";")); - LOGGER.info("Generating code for .NET Framework " + this.targetFramework); + LOGGER.info("Generating code for .NET Framework {}", this.targetFramework); } public void setTestTargetFramework(String testTargetFramework) { @@ -832,6 +857,7 @@ public class CSharpNetCoreClientCodegen extends AbstractCSharpCodegen { this.licenseId = licenseId; } + @Override public void setReleaseNote(String releaseNote) { this.releaseNote = releaseNote; } @@ -1021,7 +1047,8 @@ public class CSharpNetCoreClientCodegen extends AbstractCSharpCodegen { properties.put(NET_STANDARD, this.isNetStandard); if (properties.containsKey(SUPPORTS_UWP)) { - LOGGER.warn(".NET " + this.name + " generator does not support the UWP option. Use the csharp generator instead."); + LOGGER.warn(".NET {} generator does not support the UWP option. Use the csharp generator instead.", + this.name); properties.remove(SUPPORTS_UWP); } } 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 3064af52c20..18cfb324f9a 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 @@ -218,6 +218,14 @@ public class CppPistacheServerCodegen extends AbstractCppCodegen { } } + if(!codegenModel.isEnum + && codegenModel.anyOf.size()>1 + && codegenModel.anyOf.contains("std::string") + && !codegenModel.anyOf.contains("AnyType") + && codegenModel.interfaces.size()==1 + ){ + codegenModel.vendorExtensions.put("x-is-string-enum-container",true); + } return codegenModel; } @@ -401,7 +409,11 @@ public class CppPistacheServerCodegen extends AbstractCppCodegen { } else if (!StringUtils.isEmpty(p.get$ref())) { // model return toModelName(ModelUtils.getSimpleRef(p.get$ref())) + "()"; } else if (ModelUtils.isStringSchema(p)) { - return "\"\""; + if (p.getDefault() == null) { + return "\"\""; + } else { + return "\"" + p.getDefault().toString() + "\""; + } } return ""; @@ -411,6 +423,7 @@ public class CppPistacheServerCodegen extends AbstractCppCodegen { * Location to write model files. You can use the modelPackage() as defined * when the class is instantiated */ + @Override public String modelFileFolder() { return (outputFolder + "/model").replace("/", File.separator); } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppQt5AbstractCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppQtAbstractCodegen.java similarity index 98% rename from modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppQt5AbstractCodegen.java rename to modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppQtAbstractCodegen.java index af8323258da..2dff94f15c3 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppQt5AbstractCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppQtAbstractCodegen.java @@ -13,8 +13,8 @@ import org.slf4j.LoggerFactory; import java.io.File; import java.util.*; -public class CppQt5AbstractCodegen extends AbstractCppCodegen implements CodegenConfig { - private final Logger LOGGER = LoggerFactory.getLogger(CppQt5AbstractCodegen.class); +public class CppQtAbstractCodegen extends AbstractCppCodegen implements CodegenConfig { + private final Logger LOGGER = LoggerFactory.getLogger(CppQtAbstractCodegen.class); protected final String PREFIX = "OAI"; protected String apiVersion = "1.0.0"; protected static final String CPP_NAMESPACE = "cppNamespace"; @@ -29,7 +29,7 @@ public class CppQt5AbstractCodegen extends AbstractCppCodegen implements Codegen protected Set nonFrameworkPrimitives = new HashSet(); - public CppQt5AbstractCodegen() { + public CppQtAbstractCodegen() { super(); modifyFeatureSet(features -> features diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppQt5ClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppQtClientCodegen.java similarity index 89% rename from modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppQt5ClientCodegen.java rename to modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppQtClientCodegen.java index 00e489ee6ee..e93ae32541a 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppQt5ClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppQtClientCodegen.java @@ -29,28 +29,28 @@ import java.io.File; import static org.openapitools.codegen.utils.StringUtils.*; -public class CppQt5ClientCodegen extends CppQt5AbstractCodegen implements CodegenConfig { +public class CppQtClientCodegen extends CppQtAbstractCodegen implements CodegenConfig { public static final String OPTIONAL_PROJECT_FILE_DESC = "Generate client.pri."; // source folder where to write the files protected String sourceFolder = "client"; protected boolean optionalProjectFileFlag = true; - public CppQt5ClientCodegen() { + public CppQtClientCodegen() { super(); modifyFeatureSet(features -> features - .includeDocumentationFeatures(DocumentationFeature.Readme) - .includeGlobalFeatures(GlobalFeature.ParameterizedServer) - .includeGlobalFeatures(GlobalFeature.MultiServer) - .includeSecurityFeatures(SecurityFeature.BasicAuth) - .includeSecurityFeatures(SecurityFeature.ApiKey) - .includeSecurityFeatures(SecurityFeature.BearerToken) - .includeGlobalFeatures(GlobalFeature.ParameterStyling) + .includeDocumentationFeatures(DocumentationFeature.Readme) + .includeGlobalFeatures(GlobalFeature.ParameterizedServer) + .includeGlobalFeatures(GlobalFeature.MultiServer) + .includeSecurityFeatures(SecurityFeature.BasicAuth) + .includeSecurityFeatures(SecurityFeature.ApiKey) + .includeSecurityFeatures(SecurityFeature.BearerToken) + .includeGlobalFeatures(GlobalFeature.ParameterStyling) ); // set the output folder here - outputFolder = "generated-code/qt5cpp"; + outputFolder = "generated-code/cpp-qt-client"; /* * Models. You can write model files using the modelTemplateFiles map. @@ -83,7 +83,7 @@ public class CppQt5ClientCodegen extends CppQt5AbstractCodegen implements Codege * Template Location. This is the location which templates will be read from. The generator * will use the resource stream to attempt to read the templates. */ - embeddedTemplateDir = templateDir = "cpp-qt5-client"; + embeddedTemplateDir = templateDir = "cpp-qt-client"; addSwitch(CodegenConstants.OPTIONAL_PROJECT_FILE, OPTIONAL_PROJECT_FILE_DESC, this.optionalProjectFileFlag); supportingFiles.add(new SupportingFile("helpers-header.mustache", sourceFolder, PREFIX + "Helpers.h")); @@ -94,9 +94,9 @@ public class CppQt5ClientCodegen extends CppQt5AbstractCodegen implements Codege supportingFiles.add(new SupportingFile("HttpFileElement.cpp.mustache", sourceFolder, PREFIX + "HttpFileElement.cpp")); supportingFiles.add(new SupportingFile("object.mustache", sourceFolder, PREFIX + "Object.h")); supportingFiles.add(new SupportingFile("enum.mustache", sourceFolder, PREFIX + "Enum.h")); - supportingFiles.add(new SupportingFile("ServerConfiguration.mustache", sourceFolder, PREFIX +"ServerConfiguration.h")); - supportingFiles.add(new SupportingFile("ServerVariable.mustache", sourceFolder, PREFIX +"ServerVariable.h")); - supportingFiles.add(new SupportingFile("README.mustache", "","README.md")); + supportingFiles.add(new SupportingFile("ServerConfiguration.mustache", sourceFolder, PREFIX + "ServerConfiguration.h")); + supportingFiles.add(new SupportingFile("ServerVariable.mustache", sourceFolder, PREFIX + "ServerVariable.h")); + supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); supportingFiles.add(new SupportingFile("CMakeLists.txt.mustache", sourceFolder, "CMakeLists.txt")); if (optionalProjectFileFlag) { supportingFiles.add(new SupportingFile("Project.mustache", sourceFolder, "client.pri")); @@ -127,7 +127,7 @@ public class CppQt5ClientCodegen extends CppQt5AbstractCodegen implements Codege supportingFiles.add(new SupportingFile("enum.mustache", sourceFolder, modelNamePrefix + "Enum.h")); supportingFiles.add(new SupportingFile("ServerConfiguration.mustache", sourceFolder, modelNamePrefix + "ServerConfiguration.h")); supportingFiles.add(new SupportingFile("ServerVariable.mustache", sourceFolder, modelNamePrefix + "ServerVariable.h")); - supportingFiles.add(new SupportingFile("README.mustache", "","README.md")); + supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); supportingFiles.add(new SupportingFile("CMakeLists.txt.mustache", sourceFolder, "CMakeLists.txt")); @@ -158,7 +158,7 @@ public class CppQt5ClientCodegen extends CppQt5AbstractCodegen implements Codege */ @Override public String getName() { - return "cpp-qt5-client"; + return "cpp-qt-client"; } /** @@ -169,7 +169,7 @@ public class CppQt5ClientCodegen extends CppQt5AbstractCodegen implements Codege */ @Override public String getHelp() { - return "Generates a Qt5 C++ client library."; + return "Generates a Qt C++ client library."; } /** diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppQt5QHttpEngineServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppQtQHttpEngineServerCodegen.java similarity index 95% rename from modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppQt5QHttpEngineServerCodegen.java rename to modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppQtQHttpEngineServerCodegen.java index 7c35de11720..938211f6787 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppQt5QHttpEngineServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppQtQHttpEngineServerCodegen.java @@ -26,7 +26,7 @@ import java.io.File; import static org.openapitools.codegen.utils.StringUtils.camelize; -public class CppQt5QHttpEngineServerCodegen extends CppQt5AbstractCodegen implements CodegenConfig { +public class CppQtQHttpEngineServerCodegen extends CppQtAbstractCodegen implements CodegenConfig { protected final String SRC_DIR = "/src"; protected final String MODEL_DIR = "/src/models"; @@ -36,13 +36,13 @@ public class CppQt5QHttpEngineServerCodegen extends CppQt5AbstractCodegen implem // source folder where to write the files protected String sourceFolder = "server"; - public CppQt5QHttpEngineServerCodegen() { + public CppQtQHttpEngineServerCodegen() { super(); modifyFeatureSet(features -> features.includeDocumentationFeatures(DocumentationFeature.Readme)); // set the output folder here - outputFolder = "generated-code/cpp-qt5-qhttpengine-server"; + outputFolder = "generated-code/cpp-qt-qhttpengine-server"; /* * Models. You can write model files using the modelTemplateFiles map. @@ -83,7 +83,7 @@ public class CppQt5QHttpEngineServerCodegen extends CppQt5AbstractCodegen implem * Template Location. This is the location which templates will be read from. The generator * will use the resource stream to attempt to read the templates. */ - embeddedTemplateDir = templateDir = "cpp-qt5-qhttpengine-server"; + embeddedTemplateDir = templateDir = "cpp-qt-qhttpengine-server"; supportingFiles.add(new SupportingFile("helpers-header.mustache", sourceFolder + MODEL_DIR, PREFIX + "Helpers.h")); supportingFiles.add(new SupportingFile("helpers-body.mustache", sourceFolder + MODEL_DIR, PREFIX + "Helpers.cpp")); @@ -154,7 +154,7 @@ public class CppQt5QHttpEngineServerCodegen extends CppQt5AbstractCodegen implem */ @Override public String getName() { - return "cpp-qt5-qhttpengine-server"; + return "cpp-qt-qhttpengine-server"; } /** @@ -165,7 +165,7 @@ public class CppQt5QHttpEngineServerCodegen extends CppQt5AbstractCodegen implem */ @Override public String getHelp() { - return "Generates a Qt5 C++ Server using the QHTTPEngine HTTP Library."; + return "Generates a Qt C++ Server using the QHTTPEngine HTTP Library."; } /** 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 8dd888dd7db..f6b62cdd144 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 @@ -52,6 +52,7 @@ public class CppRestSdkClientCodegen extends AbstractCppCodegen { * @return the CodegenType for this generator * @see org.openapitools.codegen.CodegenType */ + @Override public CodegenType getTag() { return CodegenType.CLIENT; } @@ -62,6 +63,7 @@ public class CppRestSdkClientCodegen extends AbstractCppCodegen { * * @return the friendly name for the generator */ + @Override public String getName() { return "cpp-restsdk"; } @@ -72,6 +74,7 @@ public class CppRestSdkClientCodegen extends AbstractCppCodegen { * * @return A string value for the help message */ + @Override public String getHelp() { return "Generates a C++ API client with C++ REST SDK (https://github.com/Microsoft/cpprestsdk)."; } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppRestbedServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppRestbedServerCodegen.java index 6cd87d18f2c..9d9bc5932c9 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppRestbedServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppRestbedServerCodegen.java @@ -175,6 +175,7 @@ public class CppRestbedServerCodegen extends AbstractCppCodegen { * * @return the CodegenType for this generator */ + @Override public CodegenType getTag() { return CodegenType.SERVER; } @@ -185,6 +186,7 @@ public class CppRestbedServerCodegen extends AbstractCppCodegen { * * @return the friendly name for the generator */ + @Override public String getName() { return "cpp-restbed-server"; } @@ -195,6 +197,7 @@ public class CppRestbedServerCodegen extends AbstractCppCodegen { * * @return A string value for the help message */ + @Override public String getHelp() { return "Generates a C++ API Server with Restbed (https://github.com/Corvusoft/restbed)."; } @@ -228,6 +231,7 @@ public class CppRestbedServerCodegen extends AbstractCppCodegen { * Location to write model files. You can use the modelPackage() as defined * when the class is instantiated */ + @Override public String modelFileFolder() { return (outputFolder + "/model").replace("/", File.separator); } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppTinyClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppTinyClientCodegen.java new file mode 100644 index 00000000000..3229730bfa6 --- /dev/null +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppTinyClientCodegen.java @@ -0,0 +1,347 @@ +/* + * 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.languages; + +import org.openapitools.codegen.*; +import io.swagger.v3.oas.models.media.Schema; + +import io.swagger.v3.parser.util.SchemaTypeUtil; +import org.openapitools.codegen.meta.features.*; +import org.openapitools.codegen.meta.GeneratorMetadata; +import org.openapitools.codegen.meta.Stability; +import org.openapitools.codegen.utils.ModelUtils; + +import java.io.File; +import java.util.*; + +import org.apache.commons.lang3.StringUtils; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class CppTinyClientCodegen extends AbstractCppCodegen implements CodegenConfig { + public static final String PROJECT_NAME = "TinyClient"; + + static final Logger LOGGER = LoggerFactory.getLogger(CppTinyClientCodegen.class); + + public static final String MICROCONTROLLER = "controller"; + public static final String rootFolder = ""; + protected String controller = "esp32"; + + + @Override + public CodegenType getTag() { + return CodegenType.CLIENT; + } + + /** + * Configures a friendly name for the generator. This will be used by the + * generator to select the library with the -g flag. + * + * @return the friendly name for the generator + */ + @Override + public String getName() { + return "cpp-tiny"; + } + + /** + * Returns human-friendly help for the generator. Provide the consumer with + * help tips, parameters here + * + * @return A string value for the help message + */ + @Override + public String getHelp() { + return "Generates a C++ Arduino REST API client."; + } + + public void addControllerToAdditionalProperties() { + Map supportedControllers = new HashMap() {{ + put("esp32", "isESP32"); + put("esp8266", "isESP8266"); + }}; + if (supportedControllers.containsKey(controller)) { + additionalProperties.put(supportedControllers.get(controller), true); + } else { + //String msg = String.format("The specified controller: %s is not supported.\nSupported controllers are: %s", + // controller, + // supportedControllers.keySet()); + throw new UnsupportedOperationException("Supported controllers are: ESP32, ESP8266"); + } + } + + public CppTinyClientCodegen() { + super(); + + modifyFeatureSet(feature -> feature + .excludeGlobalFeatures( + GlobalFeature.XMLStructureDefinitions, + GlobalFeature.Callbacks, + GlobalFeature.LinkObjects, + GlobalFeature.ParameterStyling, + GlobalFeature.MultiServer) + .excludeSchemaSupportFeatures( + SchemaSupportFeature.Polymorphism + ) + .excludeParameterFeatures( + ParameterFeature.Cookie, + ParameterFeature.Header, + ParameterFeature.FormUnencoded, + ParameterFeature.FormMultipart, + ParameterFeature.Query + ) + .excludeDataTypeFeatures( + DataTypeFeature.Enum, + DataTypeFeature.Maps, + DataTypeFeature.MapOfCollectionOfEnum, + DataTypeFeature.MapOfCollectionOfModel, + DataTypeFeature.MapOfCollectionOfPrimitives, + DataTypeFeature.MapOfEnum, + DataTypeFeature.MapOfModel + + ) + .excludeWireFormatFeatures( + WireFormatFeature.XML, + WireFormatFeature.PROTOBUF, + WireFormatFeature.Custom + ) + .includeDocumentationFeatures( + DocumentationFeature.Readme + )); + + generatorMetadata = GeneratorMetadata.newBuilder(generatorMetadata) + .stability(Stability.BETA) + .build(); + + outputFolder = "generated-code" + File.separator + "cpp-tiny"; + embeddedTemplateDir = templateDir = "cpp-tiny"; + + String libFolder = "lib"; + // MODELS + modelPackage = libFolder + File.separator + "Models"; + modelTemplateFiles.put("model-header.mustache", ".h"); + modelTemplateFiles.put("model-body.mustache", ".cpp"); + + // MODELS: Helpers + supportingFiles.add(new SupportingFile("helpers-header.mustache", modelPackage, "Helpers.h")); + supportingFiles.add(new SupportingFile("helpers-body.mustache", modelPackage, "Helpers.cpp")); + + // MODELS: TESTS + testPackage = libFolder + File.separator + "TestFiles"; + modelTestTemplateFiles.put("unit-test-model.mustache", ".cpp"); + supportingFiles.add(new SupportingFile("run-tests.mustache", "test", "RunTests.cpp")); + + // SERVICES + apiPackage = CppTinyClientCodegen.libFolder + File.separator + "service"; + apiTemplateFiles.put("service/api-header.mustache".replace('/', File.separatorChar), ".h"); + apiTemplateFiles.put("service/api-body.mustache".replace('/', File.separatorChar), ".cpp"); + + // SERVICES: Helpers + supportingFiles.add(new SupportingFile("service/Response.h.mustache", serviceFolder, "Response.h")); + supportingFiles.add(new SupportingFile("service/AbstractService.h.mustache", serviceFolder, "AbstractService.h")); + supportingFiles.add(new SupportingFile("service/AbstractService.cpp.mustache", serviceFolder, "AbstractService.cpp")); + + // Main + supportingFiles.add(new SupportingFile("main.mustache", CppTinyClientCodegen.sourceFolder, "main.cpp")); + + // Config files + supportingFiles.add(new SupportingFile("README.mustache", rootFolder, "README.md")); + supportingFiles.add(new SupportingFile("platformio.ini.mustache", rootFolder, "platformio.ini")); + supportingFiles.add(new SupportingFile("root.cert.mustache", rootFolder, "root.cert")); + supportingFiles.add(new SupportingFile("README.mustache", rootFolder, "README.md")); + supportingFiles.add(new SupportingFile("pre_compiling_bourne.py.mustache", rootFolder, "pre_compiling_bourne.py")); + + defaultIncludes = new HashSet( + Arrays.asList( + "bool", + "int", + "long", + "double", + "float") + ); + languageSpecificPrimitives = new HashSet( + Arrays.asList( + "bool", + "int", + "long", + "double", + "float", + "std::string") + ); + + super.typeMapping = new HashMap(); + typeMapping.put("string", "std::string"); + typeMapping.put("integer", "int"); + typeMapping.put("boolean", "bool"); + typeMapping.put("array", "std::list"); + typeMapping.put("DateTime", "std::string"); + + cliOptions.add(new CliOption(MICROCONTROLLER, "name of microcontroller (e.g esp32 or esp8266)"). + defaultValue("esp32")); + + makeTypeMappings(); + + } + + // FilePaths + private static final String sourceFolder = "src"; + private static final String libFolder = "lib"; + private static final String serviceFolder = libFolder + File.separator + "service"; + + @Override + public String getTypeDeclaration(String str) { + return str; + } + + private void makeTypeMappings() { + // Types + String cpp_array_type = "std::list"; + typeMapping = new HashMap<>(); + + typeMapping.put("string", "std::string"); + typeMapping.put("integer", "int"); + typeMapping.put("float", "float"); + typeMapping.put("long", "long"); + typeMapping.put("boolean", "bool"); + typeMapping.put("double", "double"); + typeMapping.put("array", cpp_array_type); + typeMapping.put("number", "long"); + typeMapping.put("binary", "std::string"); + typeMapping.put("password", "std::string"); + typeMapping.put("file", "std::string"); + typeMapping.put("DateTime", "std::string"); + typeMapping.put("Date", "std::string"); + typeMapping.put("UUID", "std::string"); + typeMapping.put("URI", "std::string"); + } + + @Override + public void processOpts() { + super.processOpts(); + // Throw exception if http and esp8266 + + // -- --additional-properties=controller= + if (additionalProperties.containsKey(MICROCONTROLLER)) { + controller = additionalProperties.get(MICROCONTROLLER).toString(); + } + + addControllerToAdditionalProperties(); + + LOGGER.info("Generator targeting the following microcontroller: {}", controller); + } + + @Override + public String toInstantiationType(Schema p) { + if (ModelUtils.isArraySchema(p)) { + return instantiationTypes.get("array"); + } else { + return null; + } + } + + @Override + public String getTypeDeclaration(Schema p) { + String openAPIType = getSchemaType(p); + if (languageSpecificPrimitives.contains(openAPIType)) { + return toModelName(openAPIType); + } else { + return openAPIType + ""; + } + } + + @Override + public String getSchemaType(Schema p) { + String openAPIType = super.getSchemaType(p); + String type = null; + if (typeMapping.containsKey(openAPIType)) { + type = typeMapping.get(openAPIType); + if (languageSpecificPrimitives.contains(type)) { + return toModelName(type); + } + } else { + type = openAPIType; + } + return toModelName(type); + } + + @Override + public String toModelName(String type) { + if (typeMapping.keySet().contains(type) || + typeMapping.values().contains(type) || + defaultIncludes.contains(type) || + languageSpecificPrimitives.contains(type)) { + return type; + } else { + return Character.toUpperCase(type.charAt(0)) + type.substring(1); + } + } + + @Override + public String toModelImport(String name) { + if (name.equals("std::string")) { + return "#include "; + } else if (name.equals("std::list")) { + return "#include "; + } else if (name.equals("Map")) { + return "#include "; + } + return "#include \"" + name + ".h\""; + } + + @Override + public String toApiImport(String name) { + return super.toApiImport(name); + } + + @Override + public String toVarName(String name) { + String paramName = name.replaceAll("[^a-zA-Z0-9_]", ""); + if (name.length() > 0) { + paramName = Character.toLowerCase(paramName.charAt(0)) + paramName.substring(1); + } + if (isReservedWord(paramName)) { + return escapeReservedWord(paramName); + } + return "" + paramName; + } + + @Override + public String toDefaultValue(Schema p) { + if (ModelUtils.isBooleanSchema(p)) { + return "bool(false)"; + } else if (ModelUtils.isNumberSchema(p)) { + return "float(0)"; + } else if (ModelUtils.isIntegerSchema(p)) { + if (SchemaTypeUtil.INTEGER64_FORMAT.equals(p.getFormat())) { + return "long(0)"; + } + return "int(0)"; + } else if (ModelUtils.isArraySchema(p)) { + return "std::list"; + } else if (!StringUtils.isEmpty(p.get$ref())) { + return toModelName(ModelUtils.getSimpleRef(p.get$ref())) + "()"; + } else if (ModelUtils.isDateSchema(p) || ModelUtils.isDateTimeSchema(p)) { + return "std::string()"; + } else if (ModelUtils.isStringSchema(p)) { + return "std::string()"; + } + return "null"; + } + + +} diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppTizenClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppTizenClientCodegen.java index 16bd058996f..d23bf246cac 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppTizenClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppTizenClientCodegen.java @@ -319,6 +319,7 @@ public class CppTizenClientCodegen extends AbstractCppCodegen implements Codegen * @param name the name of the property * @return getter name based on naming convention */ + @Override public String toBooleanGetter(String name) { return "get" + getterAndSetterCapitalize(name); } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppUE4ClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppUE4ClientCodegen.java index 7ee6cac252a..223a4f7644b 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppUE4ClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppUE4ClientCodegen.java @@ -539,14 +539,17 @@ public class CppUE4ClientCodegen extends AbstractCppCodegen { return input.replace("*/", "*_/").replace("/*", "/_*"); } + @Override public String toBooleanGetter(String name) { return "Is" + getterAndSetterCapitalize(name); } + @Override public String toGetter(String name) { return "Get" + getterAndSetterCapitalize(name); } + @Override public String toSetter(String name) { return "Set" + getterAndSetterCapitalize(name); } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CrystalClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CrystalClientCodegen.java index c092a8b5acd..38e95c67d26 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CrystalClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CrystalClientCodegen.java @@ -363,13 +363,14 @@ public class CrystalClientCodegen extends DefaultCodegen { // model name cannot use reserved keyword, e.g. return if (isReservedWord(modelName)) { modelName = camelize("Model" + modelName); - LOGGER.warn(name + " (reserved word) cannot be used as model name. Renamed to " + modelName); + LOGGER.warn("{} (reserved word) cannot be used as model name. Renamed to {}", name, modelName); return modelName; } // model name starts with number if (modelName.matches("^\\d.*")) { - LOGGER.warn(modelName + " (model name starts with number) cannot be used as model name. Renamed to " + camelize("model_" + modelName)); + LOGGER.warn("{} (model name starts with number) cannot be used as model name. Renamed to {}", modelName, + camelize("model_" + modelName)); modelName = "model_" + modelName; // e.g. 200Response => Model200Response (after camelize) } @@ -482,20 +483,20 @@ public class CrystalClientCodegen extends DefaultCodegen { // rename to empty_method_name_1 (e.g.) if method name is empty if (StringUtils.isEmpty(operationId)) { operationId = underscore("empty_method_name_" + emptyMethodNameCounter++); - LOGGER.warn("Empty method name (operationId) found. Renamed to " + operationId); + LOGGER.warn("Empty method name (operationId) found. Renamed to {}", operationId); return operationId; } // method name cannot use reserved keyword, e.g. return if (isReservedWord(operationId)) { String newOperationId = underscore("call_" + operationId); - LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + newOperationId); + LOGGER.warn("{} (reserved word) cannot be used as method name. Renamed to {}", operationId, newOperationId); return newOperationId; } // operationId starts with a number if (operationId.matches("^\\d.*")) { - LOGGER.warn(operationId + " (starting with a number) cannot be used as method name. Renamed to " + underscore(sanitizeName("call_" + operationId))); + LOGGER.warn("{} (starting with a number) cannot be used as method name. Renamed to {}", operationId, underscore(sanitizeName("call_" + operationId))); operationId = "call_" + operationId; } @@ -836,6 +837,7 @@ public class CrystalClientCodegen extends DefaultCodegen { return varName; } + @Override public String toRegularExpression(String pattern) { return addRegularExpressionDelimiter(pattern); } @@ -881,7 +883,7 @@ public class CrystalClientCodegen extends DefaultCodegen { } LOGGER.error("Error running the command ({}). Exit value: {}, Error output: {}", command, exitValue, sb.toString()); } else { - LOGGER.info("Successfully executed: " + command); + LOGGER.info("Successfully executed: {}", command); } } catch (InterruptedException | IOException e) { LOGGER.error("Error running the command ({}). Exception: {}", command, e.getMessage()); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/DartClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/DartClientCodegen.java index 589ef137f34..b26f23891c0 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/DartClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/DartClientCodegen.java @@ -64,6 +64,7 @@ public class DartClientCodegen extends AbstractDartCodegen { final String libFolder = sourceFolder + File.separator + "lib"; supportingFiles.add(new SupportingFile("pubspec.mustache", "", "pubspec.yaml")); + supportingFiles.add(new SupportingFile("analysis_options.mustache", "", "analysis_options.yaml")); supportingFiles.add(new SupportingFile("api_client.mustache", libFolder, "api_client.dart")); supportingFiles.add(new SupportingFile("api_exception.mustache", libFolder, "api_exception.dart")); supportingFiles.add(new SupportingFile("api_helper.mustache", libFolder, "api_helper.dart")); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/DartDioClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/DartDioClientCodegen.java index 23b50b2f756..517d1023b98 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/DartDioClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/DartDioClientCodegen.java @@ -264,7 +264,7 @@ public class DartDioClientCodegen extends AbstractDartCodegen { @Override public Map postProcessOperationsWithModels(Map objs, List allModels) { - objs = super.postProcessOperationsWithModels(objs, allModels); + super.postProcessOperationsWithModels(objs, allModels); Map operations = (Map) objs.get("operations"); List operationList = (List) operations.get("operation"); @@ -272,24 +272,8 @@ public class DartDioClientCodegen extends AbstractDartCodegen { Set resultImports = new HashSet<>(); for (CodegenOperation op : operationList) { - op.httpMethod = op.httpMethod.toLowerCase(Locale.ROOT); - boolean isJson = true; //default to JSON - boolean isForm = false; - boolean isMultipart = false; - if (op.consumes != null) { - for (Map consume : op.consumes) { - if (consume.containsKey("mediaType")) { - String type = consume.get("mediaType"); - isJson = type.equalsIgnoreCase("application/json"); - isForm = type.equalsIgnoreCase("application/x-www-form-urlencoded"); - isMultipart = type.equalsIgnoreCase("multipart/form-data"); - break; - } - } - } - for (CodegenParameter param : op.bodyParams) { - if (param.baseType != null && param.baseType.equalsIgnoreCase("Uint8List") && isMultipart) { + if (param.baseType != null && param.baseType.equalsIgnoreCase("Uint8List") && op.isMultipart) { param.baseType = "MultipartFile"; param.dataType = "MultipartFile"; } @@ -303,10 +287,6 @@ public class DartDioClientCodegen extends AbstractDartCodegen { } } - op.vendorExtensions.put("x-is-json", isJson); - op.vendorExtensions.put("x-is-form", isForm); - op.vendorExtensions.put("x-is-multipart", isMultipart); - resultImports.addAll(rewriteImports(op.imports)); if (op.getHasFormParams()) { resultImports.add("package:" + pubName + "/api_util.dart"); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/DartDioNextClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/DartDioNextClientCodegen.java index 764c1146426..6557d7cad3e 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/DartDioNextClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/DartDioNextClientCodegen.java @@ -46,6 +46,7 @@ public class DartDioNextClientCodegen extends AbstractDartCodegen { public static final String SERIALIZATION_LIBRARY_BUILT_VALUE = "built_value"; public static final String SERIALIZATION_LIBRARY_DEFAULT = SERIALIZATION_LIBRARY_BUILT_VALUE; + private static final String DIO_IMPORT = "package:dio/dio.dart"; private static final String CLIENT_NAME = "clientName"; private String dateLibrary; @@ -152,7 +153,6 @@ public class DartDioNextClientCodegen extends AbstractDartCodegen { final String srcFolder = libFolder + File.separator + "src"; supportingFiles.add(new SupportingFile("api_client.mustache", srcFolder, "api.dart")); - supportingFiles.add(new SupportingFile("api_util.mustache", srcFolder, "api_util.dart")); final String authFolder = srcFolder + File.separator + "auth"; supportingFiles.add(new SupportingFile("auth/api_key_auth.mustache", authFolder, "api_key_auth.dart")); @@ -176,6 +176,7 @@ public class DartDioNextClientCodegen extends AbstractDartCodegen { private void configureSerializationLibraryBuiltValue(String srcFolder) { supportingFiles.add(new SupportingFile("serialization/built_value/serializers.mustache", srcFolder, "serializers.dart")); + supportingFiles.add(new SupportingFile("serialization/built_value/api_util.mustache", srcFolder, "api_util.dart")); typeMapping.put("Array", "BuiltList"); typeMapping.put("array", "BuiltList"); @@ -192,6 +193,7 @@ public class DartDioNextClientCodegen extends AbstractDartCodegen { imports.put("BuiltMap", "package:built_collection/built_collection.dart"); imports.put("JsonObject", "package:built_value/json_object.dart"); imports.put("Uint8List", "dart:typed_data"); + imports.put("MultipartFile", DIO_IMPORT); } private void configureDateLibrary(String srcFolder) { @@ -257,7 +259,7 @@ public class DartDioNextClientCodegen extends AbstractDartCodegen { for (Object _mo : models) { Map mo = (Map) _mo; CodegenModel cm = (CodegenModel) mo.get("model"); - cm.imports = rewriteImports(cm.imports); + cm.imports = rewriteImports(cm.imports, true); cm.vendorExtensions.put("x-has-vars", !cm.vars.isEmpty()); } return objs; @@ -302,10 +304,9 @@ public class DartDioNextClientCodegen extends AbstractDartCodegen { sb.append(")]"); } - @Override public Map postProcessOperationsWithModels(Map objs, List allModels) { - objs = super.postProcessOperationsWithModels(objs, allModels); + super.postProcessOperationsWithModels(objs, allModels); Map operations = (Map) objs.get("operations"); List operationList = (List) operations.get("operation"); @@ -313,27 +314,15 @@ public class DartDioNextClientCodegen extends AbstractDartCodegen { Set resultImports = new HashSet<>(); for (CodegenOperation op : operationList) { - op.httpMethod = op.httpMethod.toLowerCase(Locale.ROOT); - boolean isJson = true; //default to JSON - boolean isForm = false; - boolean isMultipart = false; - if (op.consumes != null) { - for (Map consume : op.consumes) { - if (consume.containsKey("mediaType")) { - String type = consume.get("mediaType"); - isJson = type.equalsIgnoreCase("application/json"); - isForm = type.equalsIgnoreCase("application/x-www-form-urlencoded"); - isMultipart = type.equalsIgnoreCase("multipart/form-data"); - break; - } + for (CodegenParameter param : op.allParams) { + if (((op.isMultipart && param.isFormParam) || param.isBodyParam) && (param.isBinary || param.isFile)) { + param.baseType = "MultipartFile"; + param.dataType = "MultipartFile"; + op.imports.add("MultipartFile"); } } for (CodegenParameter param : op.bodyParams) { - if (param.baseType != null && param.baseType.equalsIgnoreCase("Uint8List") && isMultipart) { - param.baseType = "MultipartFile"; - param.dataType = "MultipartFile"; - } if (param.isContainer) { final Map serializer = new HashMap<>(); serializer.put("isArray", param.isArray); @@ -344,12 +333,13 @@ public class DartDioNextClientCodegen extends AbstractDartCodegen { } } - op.vendorExtensions.put("x-is-json", isJson); - op.vendorExtensions.put("x-is-form", isForm); - op.vendorExtensions.put("x-is-multipart", isMultipart); + if (op.allParams.stream().noneMatch(param -> param.dataType.equals("Uint8List"))) { + // Remove unused imports after processing + op.imports.remove("Uint8List"); + } - resultImports.addAll(rewriteImports(op.imports)); - if (op.getHasFormParams()) { + resultImports.addAll(rewriteImports(op.imports, false)); + if (op.getHasFormParams() || op.getHasQueryParams()) { resultImports.add("package:" + pubName + "/src/api_util.dart"); } @@ -369,11 +359,16 @@ public class DartDioNextClientCodegen extends AbstractDartCodegen { return objs; } - private Set rewriteImports(Set originalImports) { + private Set rewriteImports(Set originalImports, boolean isModel) { Set resultImports = Sets.newHashSet(); for (String modelImport : originalImports) { if (imports.containsKey(modelImport)) { - resultImports.add(imports.get(modelImport)); + String i = imports.get(modelImport); + if (Objects.equals(i, DIO_IMPORT) && !isModel) { + // Don't add imports to operations that are already imported + continue; + } + resultImports.add(i); } else { resultImports.add("package:" + pubName + "/src/model/" + underscore(modelImport) + ".dart"); } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ElixirClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ElixirClientCodegen.java index 51ce18efe45..78c1235c9df 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ElixirClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ElixirClientCodegen.java @@ -449,13 +449,14 @@ public class ElixirClientCodegen extends DefaultCodegen implements CodegenConfig // model name cannot use reserved keyword, e.g. return if (isReservedWord(name)) { - LOGGER.warn(name + " (reserved word) cannot be used as model name. Renamed to " + ("model_" + name)); + LOGGER.warn("{} (reserved word) cannot be used as model name. Renamed to {}", name, "model_" + name); name = "model_" + name; // e.g. return => ModelReturn (after camelize) } // model name starts with number if (name.matches("^\\d.*")) { - LOGGER.warn(name + " (model name starts with number) cannot be used as model name. Renamed to " + ("model_" + name)); + LOGGER.warn("{} (model name starts with number) cannot be used as model name. Renamed to {}", name, + "model_" + name); name = "model_" + name; // e.g. 200Response => Model200Response (after camelize) } @@ -471,13 +472,13 @@ public class ElixirClientCodegen extends DefaultCodegen implements CodegenConfig // method name cannot use reserved keyword, e.g. return if (isReservedWord(operationId)) { - LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + underscore(sanitizeName("call_" + operationId))); + LOGGER.warn("{} (reserved word) cannot be used as method name. Renamed to {}", operationId, underscore(sanitizeName("call_" + operationId))); return underscore(sanitizeName("call_" + operationId)); } // operationId starts with a number if (operationId.matches("^\\d.*")) { - LOGGER.warn(operationId + " (starting with a number) cannot be used as method name. Renamed to " + underscore(sanitizeName("call_" + operationId))); + LOGGER.warn("{} (starting with a number) cannot be used as method name. Renamed to {}", operationId, underscore(sanitizeName("call_" + operationId))); operationId = "call_" + operationId; } @@ -602,7 +603,7 @@ public class ElixirClientCodegen extends DefaultCodegen implements CodegenConfig return code; } - LOGGER.warn("Unknown HTTP status code: " + this.code); + LOGGER.warn("Unknown HTTP status code: {}", this.code); return "\"" + code + "\""; } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ElmClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ElmClientCodegen.java index e7aaf1a3695..ba89d67819c 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ElmClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ElmClientCodegen.java @@ -188,7 +188,7 @@ public class ElmClientCodegen extends DefaultCodegen implements CodegenConfig { // method name cannot use reserved keyword, e.g. return if (isReservedWord(operationId)) { String newOperationId = camelize("call_" + operationId, true); - LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + newOperationId); + LOGGER.warn("{} (reserved word) cannot be used as method name. Renamed to {}", operationId, newOperationId); return newOperationId; } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ErlangClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ErlangClientCodegen.java index 00013976a9b..3349e256072 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ErlangClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ErlangClientCodegen.java @@ -300,7 +300,7 @@ public class ErlangClientCodegen extends DefaultCodegen implements CodegenConfig public String toOperationId(String operationId) { // method name cannot use reserved keyword, e.g. if if (isReservedWord(operationId)) { - LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + underscore(sanitizeName("call_" + operationId)).replaceAll("\\.", "_")); + LOGGER.warn("{} (reserved word) cannot be used as method name. Renamed to {}", operationId, underscore(sanitizeName("call_" + operationId)).replaceAll("\\.", "_")); operationId = "call_" + operationId; } @@ -474,4 +474,9 @@ public class ErlangClientCodegen extends DefaultCodegen implements CodegenConfig this.replacedPathName = replacedPathName; } } + + @Override + public String addRegularExpressionDelimiter(String pattern) { + return pattern; + } } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ErlangProperCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ErlangProperCodegen.java index 9e9c1186a25..aec98664149 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ErlangProperCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ErlangProperCodegen.java @@ -359,7 +359,7 @@ public class ErlangProperCodegen extends DefaultCodegen implements CodegenConfig public String toOperationId(String operationId) { // method name cannot use reserved keyword, e.g. return if (isReservedWord(operationId)) { - LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + underscore(sanitizeName("call_" + operationId)).replaceAll("\\.", "_")); + LOGGER.warn("{} (reserved word) cannot be used as method name. Renamed to {}", operationId, underscore(sanitizeName("call_" + operationId)).replaceAll("\\.", "_")); operationId = "call_" + operationId; } @@ -568,4 +568,9 @@ public class ErlangProperCodegen extends DefaultCodegen implements CodegenConfig this.replacedPathName = replacedPathName; } } + + @Override + public String addRegularExpressionDelimiter(String pattern) { + return pattern; + } } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ErlangServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ErlangServerCodegen.java index 117a8aed937..0c9fc2dcc19 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ErlangServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ErlangServerCodegen.java @@ -256,7 +256,7 @@ public class ErlangServerCodegen extends DefaultCodegen implements CodegenConfig public String toOperationId(String operationId) { // method name cannot use reserved keyword, e.g. return if (isReservedWord(operationId)) { - LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + camelize(sanitizeName("call_" + operationId))); + LOGGER.warn("{} (reserved word) cannot be used as method name. Renamed to {}", operationId, camelize(sanitizeName("call_" + operationId))); operationId = "call_" + operationId; } @@ -326,4 +326,8 @@ public class ErlangServerCodegen extends DefaultCodegen implements CodegenConfig return input.replace("-ifdef", "- if def").replace("-endif", "- end if"); } + @Override + public String addRegularExpressionDelimiter(String pattern) { + return pattern; + } } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/FlashClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/FlashClientCodegen.java index 89a5a2ae69a..8f2d6ce052e 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/FlashClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/FlashClientCodegen.java @@ -327,7 +327,7 @@ public class FlashClientCodegen extends DefaultCodegen implements CodegenConfig // model name cannot use reserved keyword, e.g. return if (isReservedWord(name)) { - LOGGER.warn(name + " (reserved word) cannot be used as model name. Renamed to " + camelize("model_" + name)); + LOGGER.warn("{} (reserved word) cannot be used as model name. Renamed to {}", name, camelize("model_" + name)); name = "model_" + name; // e.g. return => ModelReturn (after camelize) } @@ -377,7 +377,7 @@ public class FlashClientCodegen extends DefaultCodegen implements CodegenConfig // method name cannot use reserved keyword, e.g. return if (isReservedWord(operationId)) { - LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + underscore(sanitizeName("call_" + operationId))); + LOGGER.warn("{} (reserved word) cannot be used as method name. Renamed to {}", operationId, underscore(sanitizeName("call_" + operationId))); operationId = "call_" + operationId; } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/FsharpGiraffeServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/FsharpGiraffeServerCodegen.java index b62591c1d0e..3764f2c4b72 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/FsharpGiraffeServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/FsharpGiraffeServerCodegen.java @@ -262,7 +262,7 @@ public class FsharpGiraffeServerCodegen extends AbstractFSharpCodegen { String original = operation.path; operation.path = operation.path.replace("?", "/"); if (!original.equals(operation.path)) { - LOGGER.warn("Normalized " + original + " to " + operation.path + ". Please verify generated source."); + LOGGER.warn("Normalized {} to {}. Please verify generated source.", original, operation.path); } } 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 a0f76b8c299..49ab62e2b68 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 @@ -23,13 +23,25 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; -import java.util.Arrays; -import java.util.EnumSet; -import java.util.List; -import java.util.Map; +import java.util.*; public class GoServerCodegen extends AbstractGoCodegen { + /** + * Name of additional property for switching routers + */ + private static final String ROUTER_SWITCH = "router"; + + /** + * Description of additional property for switching routers + */ + private static final String ROUTER_SWITCH_DESC = "Specify the router which should be used."; + + /** + * List of available routers + */ + private static final String[] ROUTERS = { "mux", "chi" }; + private final Logger LOGGER = LoggerFactory.getLogger(GoServerCodegen.class); protected String packageVersion = "1.0.0"; @@ -69,6 +81,13 @@ public class GoServerCodegen extends AbstractGoCodegen { cliOptions.add(new CliOption(CodegenConstants.SOURCE_FOLDER, CodegenConstants.SOURCE_FOLDER_DESC) .defaultValue(sourceFolder)); + CliOption frameworkOption = new CliOption(ROUTER_SWITCH, ROUTER_SWITCH_DESC); + for (String option: ROUTERS) { + frameworkOption.addEnum(option, option); + } + frameworkOption.defaultValue(ROUTERS[0]); + cliOptions.add(frameworkOption); + CliOption optServerPort = new CliOption("serverPort", "The network port the generated server binds to"); optServerPort.setType("int"); optServerPort.defaultValue(Integer.toString(serverPort)); @@ -199,6 +218,15 @@ public class GoServerCodegen extends AbstractGoCodegen { } } + additionalProperties.putIfAbsent(ROUTER_SWITCH, ROUTERS[0]); + + final Object propRouter = additionalProperties.get(ROUTER_SWITCH); + final Map routers = new HashMap<>(); + for (String router: ROUTERS) { + routers.put(router, router.equals(propRouter)); + } + additionalProperties.put("routers", routers); + modelPackage = packageName; apiPackage = packageName; diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/HaskellHttpClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/HaskellHttpClientCodegen.java index 8b264bf325f..497634d1d9f 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/HaskellHttpClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/HaskellHttpClientCodegen.java @@ -655,8 +655,7 @@ public class HaskellHttpClientCodegen extends DefaultCodegen implements CodegenC Schema additionalProperties2 = getAdditionalProperties(p); String type = additionalProperties2.getType(); if (null == type) { - LOGGER.error("No Type defined for Additional Schema " + additionalProperties2 + "\n" // - + "\tIn Schema: " + p); + LOGGER.error("No Type defined for Additional Schema {}\n\tIn Schema: {}", additionalProperties2, p); } String inner = getSchemaType(additionalProperties2); return "(Map.Map Text " + inner + ")"; @@ -693,7 +692,7 @@ public class HaskellHttpClientCodegen extends DefaultCodegen implements CodegenC counter++; } if (!op.operationId.equals(uniqueName)) { - LOGGER.warn("generated unique operationId `" + uniqueName + "`"); + LOGGER.warn("generated unique operationId `{}`", uniqueName); } op.operationId = uniqueName; op.operationIdLowerCase = uniqueName.toLowerCase(Locale.ROOT); @@ -1455,7 +1454,7 @@ public class HaskellHttpClientCodegen extends DefaultCodegen implements CodegenC if (exitValue != 0) { LOGGER.error("Error running the command ({}). Exit value: {}", command, exitValue); } else { - LOGGER.info("Successfully executed: " + command); + LOGGER.info("Successfully executed: {}", command); } } catch (InterruptedException | IOException e) { LOGGER.error("Error running the command ({}). Exception: {}", command, e.getMessage()); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/HaskellServantCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/HaskellServantCodegen.java index cefd7cebde8..9887d5c6f1e 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/HaskellServantCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/HaskellServantCodegen.java @@ -201,6 +201,7 @@ public class HaskellServantCodegen extends DefaultCodegen implements CodegenConf typeMapping.put("number", "Double"); typeMapping.put("BigDecimal", "Double"); typeMapping.put("any", "Value"); + typeMapping.put("AnyType", "Value"); typeMapping.put("UUID", "UUID"); typeMapping.put("URI", "Text"); typeMapping.put("ByteArray", "Text"); @@ -388,7 +389,7 @@ public class HaskellServantCodegen extends DefaultCodegen implements CodegenConf @Override public String getSchemaType(Schema p) { String schemaType = super.getSchemaType(p); - LOGGER.debug("debugging OpenAPI type: " + p.getType() + ", " + p.getFormat() + " => " + schemaType); + LOGGER.debug("debugging OpenAPI type: {}, {} => {}", p.getType(), p.getFormat(), schemaType); String type = null; if (typeMapping.containsKey(schemaType)) { type = typeMapping.get(schemaType); @@ -411,8 +412,7 @@ public class HaskellServantCodegen extends DefaultCodegen implements CodegenConf Schema additionalProperties2 = getAdditionalProperties(p); String type = additionalProperties2.getType(); if (null == type) { - LOGGER.error("No Type defined for Additional Property " + additionalProperties2 + "\n" // - + "\tIn Property: " + p); + LOGGER.error("No Type defined for Additional Property {}\n\tIn Property: {}", additionalProperties2, p); } String inner = getSchemaType(additionalProperties2); return "(Map.Map Text " + inner + ")"; @@ -564,7 +564,7 @@ public class HaskellServantCodegen extends DefaultCodegen implements CodegenConf // Add the HTTP method and return type String returnType = op.returnType; if (returnType == null || returnType.equals("null")) { - returnType = "()"; + returnType = "NoContent"; } if (returnType.indexOf(" ") >= 0) { returnType = "(" + returnType + ")"; @@ -692,7 +692,7 @@ public class HaskellServantCodegen extends DefaultCodegen implements CodegenConf if (exitValue != 0) { LOGGER.error("Error running the command ({}). Exit value: {}", command, exitValue); } else { - LOGGER.info("Successfully executed: " + command); + LOGGER.info("Successfully executed: {}", command); } } catch (InterruptedException | IOException e) { LOGGER.error("Error running the command ({}). Exception: {}", command, e.getMessage()); 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 f82aba5b284..509b2ebb778 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 @@ -395,9 +395,6 @@ public class JavaClientCodegen extends AbstractJavaCodegen supportingFiles.add(new SupportingFile("ParamExpander.mustache", invokerFolder, "ParamExpander.java")); supportingFiles.add(new SupportingFile("EncodingUtils.mustache", invokerFolder, "EncodingUtils.java")); supportingFiles.add(new SupportingFile("auth/DefaultApi20Impl.mustache", authFolder, "DefaultApi20Impl.java")); - supportingFiles.add(new SupportingFile("auth/OauthPasswordGrant.mustache", authFolder, "OauthPasswordGrant.java")); - supportingFiles.add(new SupportingFile("auth/OauthClientCredentialsGrant.mustache", authFolder, "OauthClientCredentialsGrant.java")); - } else if (OKHTTP_GSON.equals(getLibrary()) || StringUtils.isEmpty(getLibrary())) { // the "okhttp-gson" library template requires "ApiCallback.mustache" for async call supportingFiles.add(new SupportingFile("ApiCallback.mustache", invokerFolder, "ApiCallback.java")); @@ -436,13 +433,13 @@ public class JavaClientCodegen extends AbstractJavaCodegen supportsAdditionalPropertiesWithComposedSchema = true; } else if (NATIVE.equals(getLibrary())) { - setJava8Mode(true); - additionalProperties.put("java8", "true"); + setJava8ModeAndAdditionalProperties(true); supportingFiles.add(new SupportingFile("ApiResponse.mustache", invokerFolder, "ApiResponse.java")); supportingFiles.add(new SupportingFile("JSON.mustache", invokerFolder, "JSON.java")); supportingFiles.add(new SupportingFile("AbstractOpenApiSchema.mustache", (sourceFolder + File.separator + modelPackage().replace('.', File.separatorChar)).replace('/', File.separatorChar), "AbstractOpenApiSchema.java")); forceSerializationLibrary(SERIALIZATION_LIBRARY_JACKSON); } else if (RESTEASY.equals(getLibrary())) { + setJava8ModeAndAdditionalProperties(true); supportingFiles.add(new SupportingFile("JSON.mustache", invokerFolder, "JSON.java")); forceSerializationLibrary(SERIALIZATION_LIBRARY_JACKSON); } else if (JERSEY1.equals(getLibrary())) { @@ -451,14 +448,12 @@ public class JavaClientCodegen extends AbstractJavaCodegen forceSerializationLibrary(SERIALIZATION_LIBRARY_JACKSON); supportingFiles.add(new SupportingFile("auth/Authentication.mustache", authFolder, "Authentication.java")); } else if (WEBCLIENT.equals(getLibrary())) { - setJava8Mode(true); - additionalProperties.put("java8", "true"); + setJava8ModeAndAdditionalProperties(true); forceSerializationLibrary(SERIALIZATION_LIBRARY_JACKSON); } else if (VERTX.equals(getLibrary())) { typeMapping.put("file", "AsyncFile"); importMapping.put("AsyncFile", "io.vertx.core.file.AsyncFile"); - setJava8Mode(true); - additionalProperties.put("java8", "true"); + setJava8ModeAndAdditionalProperties(true); forceSerializationLibrary(SERIALIZATION_LIBRARY_JACKSON); apiTemplateFiles.put("apiImpl.mustache", "Impl.java"); apiTemplateFiles.put("rxApiImpl.mustache", ".java"); @@ -468,7 +463,7 @@ public class JavaClientCodegen extends AbstractJavaCodegen } else if (REST_ASSURED.equals(getLibrary())) { if (getSerializationLibrary() == null) { - LOGGER.info("No serializationLibrary configured, using '" + SERIALIZATION_LIBRARY_GSON + "' as fallback"); + LOGGER.info("No serializationLibrary configured, using '{}' as fallback", SERIALIZATION_LIBRARY_GSON); setSerializationLibrary(SERIALIZATION_LIBRARY_GSON); } if (SERIALIZATION_LIBRARY_JACKSON.equals(getSerializationLibrary())) { @@ -496,7 +491,7 @@ public class JavaClientCodegen extends AbstractJavaCodegen supportingFiles.add(new SupportingFile("kumuluzee.beans.xml.mustache", "src/main/resources/META-INF", "beans.xml")); } } else { - LOGGER.error("Unknown library option (-l/--library): " + getLibrary()); + LOGGER.error("Unknown library option (-l/--library): {}", getLibrary()); } if (usePlayWS) { @@ -531,7 +526,7 @@ public class JavaClientCodegen extends AbstractJavaCodegen supportingFiles.add(new SupportingFile("play25/Play25CallFactory.mustache", invokerFolder, "Play25CallFactory.java")); supportingFiles.add(new SupportingFile("play25/Play25CallAdapterFactory.mustache", invokerFolder, "Play25CallAdapterFactory.java")); - additionalProperties.put("java8", "true"); + setJava8ModeAndAdditionalProperties(true); } if (PLAY_26.equals(playVersion)) { @@ -542,7 +537,7 @@ public class JavaClientCodegen extends AbstractJavaCodegen supportingFiles.add(new SupportingFile("play26/Play26CallFactory.mustache", invokerFolder, "Play26CallFactory.java")); supportingFiles.add(new SupportingFile("play26/Play26CallAdapterFactory.mustache", invokerFolder, "Play26CallAdapterFactory.java")); - additionalProperties.put("java8", "true"); + setJava8ModeAndAdditionalProperties(true); } supportingFiles.add(new SupportingFile("play-common/auth/ApiKeyAuth.mustache", authFolder, "ApiKeyAuth.java")); @@ -553,7 +548,7 @@ public class JavaClientCodegen extends AbstractJavaCodegen } if (getSerializationLibrary() == null) { - LOGGER.info("No serializationLibrary configured, using '" + SERIALIZATION_LIBRARY_GSON + "' as fallback"); + LOGGER.info("No serializationLibrary configured, using '{}' as fallback", SERIALIZATION_LIBRARY_GSON); setSerializationLibrary(SERIALIZATION_LIBRARY_GSON); } switch (getSerializationLibrary()) { @@ -600,6 +595,12 @@ public class JavaClientCodegen extends AbstractJavaCodegen supportingFiles.add(new SupportingFile("auth/OAuth.mustache", authFolder, "OAuth.java")); supportingFiles.add(new SupportingFile("auth/OAuthFlow.mustache", authFolder, "OAuthFlow.java")); } + + // Add OauthPasswordGrant.java and OauthClientCredentialsGrant.java for feign library + if (FEIGN.equals(getLibrary())) { + supportingFiles.add(new SupportingFile("auth/OauthPasswordGrant.mustache", authFolder, "OauthPasswordGrant.java")); + supportingFiles.add(new SupportingFile("auth/OauthClientCredentialsGrant.mustache", authFolder, "OauthClientCredentialsGrant.java")); + } } } @@ -997,7 +998,9 @@ public class JavaClientCodegen extends AbstractJavaCodegen public void forceSerializationLibrary(String serializationLibrary) { if ((this.serializationLibrary != null) && !this.serializationLibrary.equalsIgnoreCase(serializationLibrary)) { - LOGGER.warn("The configured serializationLibrary '" + this.serializationLibrary + "', is not supported by the library: '" + getLibrary() + "', switching back to: " + serializationLibrary); + LOGGER.warn( + "The configured serializationLibrary '{}', is not supported by the library: '{}', switching back to: {}", + this.serializationLibrary, getLibrary(), serializationLibrary); } setSerializationLibrary(serializationLibrary); } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavascriptApolloClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavascriptApolloClientCodegen.java index 058d544f52a..3023ff6ab2e 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavascriptApolloClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavascriptApolloClientCodegen.java @@ -528,14 +528,15 @@ public class JavascriptApolloClientCodegen extends DefaultCodegen implements Cod // model name cannot use reserved keyword, e.g. return if (isReservedWord(name)) { String modelName = "Model" + name; - LOGGER.warn(name + " (reserved word) cannot be used as model name. Renamed to " + modelName); + LOGGER.warn("{} (reserved word) cannot be used as model name. Renamed to {}", name, modelName); return modelName; } // model name starts with number if (name.matches("^\\d.*")) { String modelName = "Model" + name; // e.g. 200Response => Model200Response (after camelize) - LOGGER.warn(name + " (model name starts with number) cannot be used as model name. Renamed to " + modelName); + LOGGER.warn("{} (model name starts with number) cannot be used as model name. Renamed to {}", name, + modelName); return modelName; } @@ -780,7 +781,7 @@ public class JavascriptApolloClientCodegen extends DefaultCodegen implements Cod type = openAPIType; } if (null == type) { - LOGGER.error("No Type defined for Schema " + p); + LOGGER.error("No Type defined for Schema {}", p); } return toModelName(type); } @@ -797,14 +798,14 @@ public class JavascriptApolloClientCodegen extends DefaultCodegen implements Cod // method name cannot use reserved keyword, e.g. return if (isReservedWord(operationId)) { String newOperationId = camelize("call_" + operationId, true); - LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + newOperationId); + LOGGER.warn("{} (reserved word) cannot be used as method name. Renamed to {}", operationId, newOperationId); return newOperationId; } // operationId starts with a number if (operationId.matches("^\\d.*")) { String newOperationId = camelize("call_" + operationId, true); - LOGGER.warn(operationId + " (starting with a number) cannot be used as method name. Renamed to " + newOperationId); + LOGGER.warn("{} (starting with a number) cannot be used as method name. Renamed to {}", operationId, newOperationId); return newOperationId; } @@ -1134,7 +1135,7 @@ public class JavascriptApolloClientCodegen extends DefaultCodegen implements Cod if (exitValue != 0) { LOGGER.error("Error running the command ({}). Exit code: {}", command, exitValue); } - LOGGER.info("Successfully executed: " + command); + LOGGER.info("Successfully executed: {}", command); } catch (InterruptedException | IOException e) { LOGGER.error("Error running the command ({}). Exception: {}", command, e.getMessage()); // Restore interrupted state diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavascriptClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavascriptClientCodegen.java index 2f7a34e1818..71a93675a0d 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavascriptClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavascriptClientCodegen.java @@ -584,14 +584,15 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo // model name cannot use reserved keyword, e.g. return if (isReservedWord(name)) { String modelName = "Model" + name; - LOGGER.warn(name + " (reserved word) cannot be used as model name. Renamed to " + modelName); + LOGGER.warn("{} (reserved word) cannot be used as model name. Renamed to {}", name, modelName); return modelName; } // model name starts with number if (name.matches("^\\d.*")) { String modelName = "Model" + name; // e.g. 200Response => Model200Response (after camelize) - LOGGER.warn(name + " (model name starts with number) cannot be used as model name. Renamed to " + modelName); + LOGGER.warn("{} (model name starts with number) cannot be used as model name. Renamed to {}", name, + modelName); return modelName; } @@ -836,7 +837,7 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo type = openAPIType; } if (null == type) { - LOGGER.error("No Type defined for Schema " + p); + LOGGER.error("No Type defined for Schema {}", p); } return toModelName(type); } @@ -853,14 +854,14 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo // method name cannot use reserved keyword, e.g. return if (isReservedWord(operationId)) { String newOperationId = camelize("call_" + operationId, true); - LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + newOperationId); + LOGGER.warn("{} (reserved word) cannot be used as method name. Renamed to {}", operationId, newOperationId); return newOperationId; } // operationId starts with a number if (operationId.matches("^\\d.*")) { String newOperationId = camelize("call_" + operationId, true); - LOGGER.warn(operationId + " (starting with a number) cannot be used as method name. Renamed to " + newOperationId); + LOGGER.warn("{} (starting with a number) cannot be used as method name. Renamed to {}", operationId, newOperationId); return newOperationId; } @@ -1219,7 +1220,7 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo if (exitValue != 0) { LOGGER.error("Error running the command ({}). Exit code: {}", command, exitValue); } - LOGGER.info("Successfully executed: " + command); + LOGGER.info("Successfully executed: {}", command); } catch (InterruptedException | IOException e) { LOGGER.error("Error running the command ({}). Exception: {}", command, e.getMessage()); // Restore interrupted state diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavascriptClosureAngularClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavascriptClosureAngularClientCodegen.java index 751d75e4f21..5b8bf164a60 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavascriptClosureAngularClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavascriptClosureAngularClientCodegen.java @@ -203,7 +203,7 @@ public class JavascriptClosureAngularClientCodegen extends DefaultCodegen implem // model name cannot use reserved keyword, e.g. return if (isReservedWord(name)) { - LOGGER.warn(name + " (reserved word) cannot be used as model name. Renamed to " + camelize("model_" + name)); + LOGGER.warn("{} (reserved word) cannot be used as model name. Renamed to {}", name, camelize("model_" + name)); name = "model_" + name; // e.g. return => ModelReturn (after camelize) } @@ -298,7 +298,7 @@ public class JavascriptClosureAngularClientCodegen extends DefaultCodegen implem // method name cannot use reserved keyword, e.g. return if (isReservedWord(operationId)) { String newOperationId = camelize("call_" + operationId, true); - LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + newOperationId); + LOGGER.warn("{} (reserved word) cannot be used as method name. Renamed to {}", operationId, newOperationId); return newOperationId; } 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 3ff2429d99d..1b71f1a9e27 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 @@ -63,6 +63,8 @@ public class KotlinClientCodegen extends AbstractKotlinCodegen { public static final String MOSHI_CODE_GEN = "moshiCodeGen"; + public static final String SUPPORT_ANDROID_API_LEVEL_25_AND_BELLOW = "supportAndroidApiLevel25AndBelow"; + protected static final String VENDOR_EXTENSION_BASE_NAME_LITERAL = "x-base-name-literal"; protected String dateLibrary = DateLibrary.JAVA8.value; @@ -186,7 +188,7 @@ public class KotlinClientCodegen extends AbstractKotlinCodegen { 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."); supportedLibraries.put(JVM_RETROFIT2, "Platform: Java Virtual Machine. HTTP client: Retrofit 2.6.2."); - supportedLibraries.put(MULTIPLATFORM, "Platform: Kotlin multiplatform. HTTP client: Ktor 1.2.4. JSON processing: Kotlinx Serialization: 0.12.0."); + supportedLibraries.put(MULTIPLATFORM, "Platform: Kotlin multiplatform. HTTP client: Ktor 1.6.0. JSON processing: Kotlinx Serialization: 1.2.1."); CliOption libraryOption = new CliOption(CodegenConstants.LIBRARY, "Library template (sub-template) to use"); libraryOption.setEnum(supportedLibraries); @@ -208,6 +210,8 @@ public class KotlinClientCodegen extends AbstractKotlinCodegen { cliOptions.add(CliOption.newBoolean(USE_COROUTINES, "Whether to use the Coroutines adapter with the retrofit2 library.")); cliOptions.add(CliOption.newBoolean(MOSHI_CODE_GEN, "Whether to enable codegen with the Moshi library. Refer to the [official Moshi doc](https://github.com/square/moshi#codegen) for more info.")); + + cliOptions.add(CliOption.newBoolean(SUPPORT_ANDROID_API_LEVEL_25_AND_BELLOW, "[WARNING] This flag will generate code that has a known security vulnerability. It uses `kotlin.io.createTempFile` instead of `java.nio.file.Files.createTempFile` in oder to support Android API level 25 and bellow. For more info, please check the following links https://github.com/OpenAPITools/openapi-generator/security/advisories/GHSA-23x4-m842-fmwf, https://github.com/OpenAPITools/openapi-generator/pull/9284")); } public CodegenType getTag() { @@ -471,6 +475,7 @@ public class KotlinClientCodegen extends AbstractKotlinCodegen { supportingFiles.add(new SupportingFile("jvm-common/infrastructure/OffsetDateTimeAdapter.kt.mustache", infrastructureFolder, "OffsetDateTimeAdapter.kt")); 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")); break; case gson: @@ -520,7 +525,6 @@ public class KotlinClientCodegen extends AbstractKotlinCodegen { setLibrary(JVM_OKHTTP); // jvm specific supporting files - supportingFiles.add(new SupportingFile("infrastructure/ApplicationDelegates.kt.mustache", infrastructureFolder, "ApplicationDelegates.kt")); supportingFiles.add(new SupportingFile("infrastructure/Errors.kt.mustache", infrastructureFolder, "Errors.kt")); supportingFiles.add(new SupportingFile("infrastructure/ResponseExtensions.kt.mustache", infrastructureFolder, "ResponseExtensions.kt")); supportingFiles.add(new SupportingFile("infrastructure/ApiInfrastructureResponse.kt.mustache", infrastructureFolder, "ApiInfrastructureResponse.kt")); @@ -587,8 +591,13 @@ public class KotlinClientCodegen extends AbstractKotlinCodegen { private void commonSupportingFiles() { supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); - supportingFiles.add(new SupportingFile("build.gradle.mustache", "", "build.gradle")); - supportingFiles.add(new SupportingFile("settings.gradle.mustache", "", "settings.gradle")); + if(getLibrary().equals(MULTIPLATFORM)) { + supportingFiles.add(new SupportingFile("build.gradle.kts.mustache", "", "build.gradle.kts")); + supportingFiles.add(new SupportingFile("settings.gradle.kts.mustache", "", "settings.gradle.kts")); + } else { + supportingFiles.add(new SupportingFile("build.gradle.mustache", "", "build.gradle")); + supportingFiles.add(new SupportingFile("settings.gradle.mustache", "", "settings.gradle")); + } // gradle wrapper supporting files supportingFiles.add(new SupportingFile("gradlew.mustache", "", "gradlew")); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/KotlinServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/KotlinServerCodegen.java index 0c182417c94..3ad47e68fee 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/KotlinServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/KotlinServerCodegen.java @@ -34,7 +34,6 @@ import java.util.List; import java.util.Map; public class KotlinServerCodegen extends AbstractKotlinCodegen { - public static final String DEFAULT_LIBRARY = Constants.KTOR; private final Logger LOGGER = LoggerFactory.getLogger(KotlinServerCodegen.class); private Boolean autoHeadFeatureEnabled = true; @@ -43,6 +42,7 @@ public class KotlinServerCodegen extends AbstractKotlinCodegen { private Boolean corsFeatureEnabled = false; private Boolean compressionFeatureEnabled = true; private Boolean locationsFeatureEnabled = true; + private Boolean metricsFeatureEnabled = true; // This is here to potentially warn the user when an option is not supported by the target framework. private Map> optionsSupportedPerFramework = new ImmutableMap.Builder>() @@ -52,7 +52,8 @@ public class KotlinServerCodegen extends AbstractKotlinCodegen { Constants.HSTS, Constants.CORS, Constants.COMPRESSION, - Constants.LOCATIONS + Constants.LOCATIONS, + Constants.METRICS )) .build(); @@ -115,6 +116,7 @@ public class KotlinServerCodegen extends AbstractKotlinCodegen { addSwitch(Constants.CORS, Constants.CORS_DESC, getCorsFeatureEnabled()); addSwitch(Constants.COMPRESSION, Constants.COMPRESSION_DESC, getCompressionFeatureEnabled()); addSwitch(Constants.LOCATIONS, Constants.LOCATIONS_DESC, getLocationsFeatureEnabled()); + addSwitch(Constants.METRICS, Constants.METRICS_DESC, getMetricsFeatureEnabled()); } public Boolean getAutoHeadFeatureEnabled() { @@ -169,6 +171,14 @@ public class KotlinServerCodegen extends AbstractKotlinCodegen { this.locationsFeatureEnabled = locationsFeatureEnabled; } + public Boolean getMetricsFeatureEnabled() { + return metricsFeatureEnabled; + } + + public void setMetricsFeatureEnabled(Boolean metricsEnabled) { + this.metricsFeatureEnabled = metricsEnabled; + } + public String getName() { return "kotlin-server"; } @@ -189,7 +199,7 @@ public class KotlinServerCodegen extends AbstractKotlinCodegen { if (StringUtils.isEmpty(library)) { this.setLibrary(DEFAULT_LIBRARY); additionalProperties.put(CodegenConstants.LIBRARY, DEFAULT_LIBRARY); - LOGGER.info("`library` option is empty. Default to " + DEFAULT_LIBRARY); + LOGGER.info("`library` option is empty. Default to {}", DEFAULT_LIBRARY); } if (additionalProperties.containsKey(Constants.AUTOMATIC_HEAD_REQUESTS)) { @@ -228,6 +238,12 @@ public class KotlinServerCodegen extends AbstractKotlinCodegen { additionalProperties.put(Constants.LOCATIONS, getLocationsFeatureEnabled()); } + if (additionalProperties.containsKey(Constants.METRICS)) { + setMetricsFeatureEnabled(convertPropertyToBooleanAndWriteBack(Constants.METRICS)); + } else { + additionalProperties.put(Constants.METRICS, getMetricsFeatureEnabled()); + } + boolean generateApis = additionalProperties.containsKey(CodegenConstants.GENERATE_APIS) && (Boolean) additionalProperties.get(CodegenConstants.GENERATE_APIS); String packageFolder = (sourceFolder + File.separator + packageName).replace(".", File.separator); String resourcesFolder = "src/main/resources"; // not sure this can be user configurable. @@ -268,17 +284,19 @@ public class KotlinServerCodegen extends AbstractKotlinCodegen { public final static String COMPRESSION_DESC = "Adds ability to compress outgoing content using gzip, deflate or custom encoder and thus reduce size of the response."; public final static String LOCATIONS = "featureLocations"; public final static String LOCATIONS_DESC = "Generates routes in a typed way, for both: constructing URLs and reading the parameters."; + public final static String METRICS = "featureMetrics"; + public final static String METRICS_DESC = "Enables metrics feature."; } @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("# 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("# Please support his work directly via https://patreon.com/jimschubert \uD83D\uDE4F #"); System.out.println("################################################################################"); } } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/KotlinServerDeprecatedCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/KotlinServerDeprecatedCodegen.java index 84cee1d2aa9..5c5ec533ded 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/KotlinServerDeprecatedCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/KotlinServerDeprecatedCodegen.java @@ -183,7 +183,7 @@ public class KotlinServerDeprecatedCodegen extends AbstractKotlinCodegen { if (StringUtils.isEmpty(library)) { this.setLibrary(DEFAULT_LIBRARY); additionalProperties.put(CodegenConstants.LIBRARY, DEFAULT_LIBRARY); - LOGGER.info("`library` option is empty. Default to " + DEFAULT_LIBRARY); + LOGGER.info("`library` option is empty. Default to {}", DEFAULT_LIBRARY); } if (additionalProperties.containsKey(Constants.AUTOMATIC_HEAD_REQUESTS)) { 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 cdaae2afe67..4af648fbac4 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 @@ -303,7 +303,7 @@ public class KotlinSpringServerCodegen extends AbstractKotlinCodegen this.setBasePackage((String) additionalProperties.get(CodegenConstants.INVOKER_PACKAGE)); this.setInvokerPackage((String) additionalProperties.get(CodegenConstants.INVOKER_PACKAGE)); additionalProperties.put(BASE_PACKAGE, basePackage); - LOGGER.info("Set base package to invoker package (" + basePackage + ")"); + LOGGER.info("Set base package to invoker package ({})", basePackage); } if (additionalProperties.containsKey(BASE_PACKAGE)) { diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/KtormSchemaCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/KtormSchemaCodegen.java index 979d6e34207..043b4d64cc4 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/KtormSchemaCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/KtormSchemaCodegen.java @@ -301,7 +301,7 @@ public class KtormSchemaCodegen extends AbstractKotlinCodegen { if (modelVendorExtensions.containsKey(VENDOR_EXTENSION_SCHEMA)) { // user already specified schema values - LOGGER.info("Found vendor extension in '" + modelName + "' model, autogeneration skipped"); + LOGGER.info("Found vendor extension in '{}' model, autogeneration skipped", modelName); } else { modelVendorExtensions.put(VENDOR_EXTENSION_SCHEMA, ktormSchema); ktormSchema.put("tableDefinition", tableDefinition); @@ -359,7 +359,7 @@ public class KtormSchemaCodegen extends AbstractKotlinCodegen { if (vendorExtensions.containsKey(VENDOR_EXTENSION_SCHEMA)) { // user already specified schema values - LOGGER.info("Found vendor extension in '" + baseName + "' property, autogeneration skipped"); + LOGGER.info("Found vendor extension in '{}' property, autogeneration skipped", baseName); return; } @@ -688,7 +688,8 @@ public class KtormSchemaCodegen extends AbstractKotlinCodegen { try { columnDefinition.put("colDefault", toColumnTypeDefault(defaultValue, dataType, dataFormat)); } catch (RuntimeException exception) { - LOGGER.warn("Property '" + baseName + "' of model '" + model.getName() + "' mapped to data type which doesn't support default value"); + LOGGER.warn("Property '{}' of model '{}' mapped to data type which doesn't support default value", + baseName, model.getName()); columnDefinition.put("colDefault", null); } } @@ -985,7 +986,7 @@ public class KtormSchemaCodegen extends AbstractKotlinCodegen { public String toDatabaseName(String name) { String identifier = toIdentifier(name, databaseNamePrefix, databaseNameSuffix); if (identifier.length() > IDENTIFIER_MAX_LENGTH) { - LOGGER.warn("Database name too long. Name '" + name + "' will be truncated"); + LOGGER.warn("Database name too long. Name '{}' will be truncated", name); identifier = identifier.substring(0, IDENTIFIER_MAX_LENGTH); } return identifier; @@ -1004,7 +1005,7 @@ public class KtormSchemaCodegen extends AbstractKotlinCodegen { identifier = underscore(identifier); } if (identifier.length() > IDENTIFIER_MAX_LENGTH) { - LOGGER.warn("Table name too long. Name '" + name + "' will be truncated"); + LOGGER.warn("Table name too long. Name '{}' will be truncated", name); identifier = identifier.substring(0, IDENTIFIER_MAX_LENGTH); } return identifier; @@ -1023,7 +1024,7 @@ public class KtormSchemaCodegen extends AbstractKotlinCodegen { identifier = underscore(identifier); } if (identifier.length() > IDENTIFIER_MAX_LENGTH) { - LOGGER.warn("Column name too long. Name '" + name + "' will be truncated"); + LOGGER.warn("Column name too long. Name '{}' will be truncated", name); identifier = identifier.substring(0, IDENTIFIER_MAX_LENGTH); } return identifier; @@ -1042,13 +1043,13 @@ public class KtormSchemaCodegen extends AbstractKotlinCodegen { String escapedName = escapeQuotedIdentifier(name); // Database, table, and column names cannot end with space characters. if (escapedName.matches(".*\\s$")) { - LOGGER.warn("Database, table, and column names cannot end with space characters. Check '" + name + "' name"); + LOGGER.warn("Database, table, and column names cannot end with space characters. Check '{}' name", name); escapedName = escapedName.replaceAll("\\s+$", ""); } // Identifiers may begin with a digit but unless quoted may not consist solely of digits. if (escapedName.matches("^\\d+$")) { - LOGGER.warn("Database, table, and column names cannot consist solely of digits. Check '" + name + "' name"); + LOGGER.warn("Database, table, and column names cannot consist solely of digits. Check '{}' name", name); escapedName = prefix + escapedName + suffix; } @@ -1074,7 +1075,8 @@ public class KtormSchemaCodegen extends AbstractKotlinCodegen { Pattern regexp = Pattern.compile("[^0-9a-zA-z$_\\x0080-\\xFFFF]"); Matcher matcher = regexp.matcher(identifier); if (matcher.find()) { - LOGGER.warn("Identifier '" + identifier + "' contains unsafe characters out of [0-9,a-z,A-Z$_] and U+0080..U+FFFF range"); + LOGGER.warn("Identifier '{}' contains unsafe characters out of [0-9,a-z,A-Z$_] and U+0080..U+FFFF range", + identifier); identifier = identifier.replaceAll("[^0-9a-zA-z$_\\x0080-\\xFFFF]", ""); } return identifier; @@ -1106,7 +1108,9 @@ public class KtormSchemaCodegen extends AbstractKotlinCodegen { public void setDefaultDatabaseName(String databaseName) { String escapedName = toDatabaseName(databaseName); if (!escapedName.equals(databaseName)) { - LOGGER.error("Invalid database name. '" + databaseName + "' cannot be used as identifier. Escaped value '" + escapedName + "' will be used instead."); + LOGGER.error( + "Invalid database name. '{}' cannot be used as identifier. Escaped value '{}' will be used instead.", + databaseName, escapedName); } this.defaultDatabaseName = escapedName; } @@ -1152,7 +1156,8 @@ public class KtormSchemaCodegen extends AbstractKotlinCodegen { this.identifierNamingConvention = naming; break; default: - LOGGER.warn("\"" + naming + "\" is invalid \"identifierNamingConvention\" argument. Current \"" + this.identifierNamingConvention + "\" used instead."); + LOGGER.warn("\"{}\" is invalid \"identifierNamingConvention\" argument. Current \"{}\" used instead.", + naming, this.identifierNamingConvention); } } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/LuaClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/LuaClientCodegen.java index 819dcf6bf44..41aae956c97 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/LuaClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/LuaClientCodegen.java @@ -281,13 +281,14 @@ public class LuaClientCodegen extends DefaultCodegen implements CodegenConfig { // model name cannot use reserved keyword, e.g. return if (isReservedWord(name)) { - LOGGER.warn(name + " (reserved word) cannot be used as model name. Renamed to " + ("model_" + name)); + LOGGER.warn("{} (reserved word) cannot be used as model name. Renamed to {}", name, "model_" + name); name = "model_" + name; // e.g. return => ModelReturn (after camelize) } // model name starts with number if (name.matches("^\\d.*")) { - LOGGER.warn(name + " (model name starts with number) cannot be used as model name. Renamed to " + ("model_" + name)); + LOGGER.warn("{} (model name starts with number) cannot be used as model name. Renamed to {}", name, + "model_" + name); name = "model_" + name; // e.g. 200Response => Model200Response (after camelize) } @@ -409,7 +410,7 @@ public class LuaClientCodegen extends DefaultCodegen implements CodegenConfig { // method name cannot use reserved keyword, e.g. return if (isReservedWord(sanitizedOperationId)) { - LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + underscore("call_" + operationId)); + LOGGER.warn("{} (reserved word) cannot be used as method name. Renamed to {}", operationId, underscore("call_" + operationId)); sanitizedOperationId = "call_" + sanitizedOperationId; } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/MysqlSchemaCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/MysqlSchemaCodegen.java index abc3b4e657e..fa217e1635f 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/MysqlSchemaCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/MysqlSchemaCodegen.java @@ -274,7 +274,7 @@ public class MysqlSchemaCodegen extends DefaultCodegen implements CodegenConfig if (modelVendorExtensions.containsKey(VENDOR_EXTENSION_MYSQL_SCHEMA)) { // user already specified schema values - LOGGER.info("Found vendor extension in '" + modelName + "' model, autogeneration skipped"); + LOGGER.info("Found vendor extension in '{}' model, autogeneration skipped", modelName); } else { modelVendorExtensions.put(VENDOR_EXTENSION_MYSQL_SCHEMA, mysqlSchema); mysqlSchema.put("tableDefinition", tableDefinition); @@ -345,7 +345,7 @@ public class MysqlSchemaCodegen extends DefaultCodegen implements CodegenConfig if (vendorExtensions.containsKey(VENDOR_EXTENSION_MYSQL_SCHEMA)) { // user already specified schema values - LOGGER.info("Found vendor extension in '" + baseName + "' property, autogeneration skipped"); + LOGGER.info("Found vendor extension in '{}' property, autogeneration skipped", baseName); return; } @@ -364,7 +364,9 @@ public class MysqlSchemaCodegen extends DefaultCodegen implements CodegenConfig List enumValues = (List) allowableValues.get("values"); for (int i = 0; i < enumValues.size(); i++) { if (i > ENUM_MAX_ELEMENTS - 1) { - LOGGER.warn("ENUM column can have maximum of " + ENUM_MAX_ELEMENTS.toString() + " distinct elements, following value will be skipped: " + (String) enumValues.get(i)); + LOGGER.warn( + "ENUM column can have maximum of {} distinct elements, following value will be skipped: {}", + ENUM_MAX_ELEMENTS.toString(), (String) enumValues.get(i)); break; } String value = String.valueOf(enumValues.get(i)); @@ -395,7 +397,9 @@ public class MysqlSchemaCodegen extends DefaultCodegen implements CodegenConfig try { columnDefinition.put("colDefault", toCodegenMysqlDataTypeDefault(defaultValue, (String) columnDefinition.get("colDataType"))); } catch (RuntimeException exception) { - LOGGER.warn("Property '" + baseName + "' of model '" + model.getName() + "' mapped to MySQL data type which doesn't support default value"); + LOGGER.warn( + "Property '{}' of model '{}' mapped to MySQL data type which doesn't support default value", + baseName, model.getName()); columnDefinition.put("colDefault", null); } } @@ -432,7 +436,7 @@ public class MysqlSchemaCodegen extends DefaultCodegen implements CodegenConfig if (vendorExtensions.containsKey(VENDOR_EXTENSION_MYSQL_SCHEMA)) { // user already specified schema values - LOGGER.info("Found vendor extension in '" + baseName + "' property, autogeneration skipped"); + LOGGER.info("Found vendor extension in '{}' property, autogeneration skipped", baseName); return; } @@ -451,7 +455,9 @@ public class MysqlSchemaCodegen extends DefaultCodegen implements CodegenConfig List enumValues = (List) allowableValues.get("values"); for (int i = 0; i < enumValues.size(); i++) { if (i > ENUM_MAX_ELEMENTS - 1) { - LOGGER.warn("ENUM column can have maximum of " + ENUM_MAX_ELEMENTS.toString() + " distinct elements, following value will be skipped: " + (String) enumValues.get(i)); + LOGGER.warn( + "ENUM column can have maximum of {} distinct elements, following value will be skipped: {}", + ENUM_MAX_ELEMENTS.toString(), (String) enumValues.get(i)); break; } String value = String.valueOf(enumValues.get(i)); @@ -481,7 +487,9 @@ public class MysqlSchemaCodegen extends DefaultCodegen implements CodegenConfig try { columnDefinition.put("colDefault", toCodegenMysqlDataTypeDefault(defaultValue, (String) columnDefinition.get("colDataType"))); } catch (RuntimeException exception) { - LOGGER.warn("Property '" + baseName + "' of model '" + model.getName() + "' mapped to MySQL data type which doesn't support default value"); + LOGGER.warn( + "Property '{}' of model '{}' mapped to MySQL data type which doesn't support default value", + baseName, model.getName()); columnDefinition.put("colDefault", null); } } @@ -510,7 +518,7 @@ public class MysqlSchemaCodegen extends DefaultCodegen implements CodegenConfig if (vendorExtensions.containsKey(VENDOR_EXTENSION_MYSQL_SCHEMA)) { // user already specified schema values - LOGGER.info("Found vendor extension in '" + baseName + "' property, autogeneration skipped"); + LOGGER.info("Found vendor extension in '{}' property, autogeneration skipped", baseName); return; } @@ -534,7 +542,9 @@ public class MysqlSchemaCodegen extends DefaultCodegen implements CodegenConfig try { columnDefinition.put("colDefault", toCodegenMysqlDataTypeDefault(defaultValue, (String) columnDefinition.get("colDataType"))); } catch (RuntimeException exception) { - LOGGER.warn("Property '" + baseName + "' of model '" + model.getName() + "' mapped to MySQL data type which doesn't support default value"); + LOGGER.warn( + "Property '{}' of model '{}' mapped to MySQL data type which doesn't support default value", + baseName, model.getName()); columnDefinition.put("colDefault", null); } } @@ -568,7 +578,7 @@ public class MysqlSchemaCodegen extends DefaultCodegen implements CodegenConfig if (vendorExtensions.containsKey(VENDOR_EXTENSION_MYSQL_SCHEMA)) { // user already specified schema values - LOGGER.info("Found vendor extension in '" + baseName + "' property, autogeneration skipped"); + LOGGER.info("Found vendor extension in '{}' property, autogeneration skipped", baseName); return; } @@ -589,7 +599,9 @@ public class MysqlSchemaCodegen extends DefaultCodegen implements CodegenConfig columnDefinition.put("colDataTypeArguments", columnDataTypeArguments); for (int i = 0; i < enumValues.size(); i++) { if (i > ENUM_MAX_ELEMENTS - 1) { - LOGGER.warn("ENUM column can have maximum of " + ENUM_MAX_ELEMENTS.toString() + " distinct elements, following value will be skipped: " + (String) enumValues.get(i)); + LOGGER.warn( + "ENUM column can have maximum of {} distinct elements, following value will be skipped: {}", + ENUM_MAX_ELEMENTS.toString(), (String) enumValues.get(i)); break; } String value = String.valueOf(enumValues.get(i)); @@ -613,7 +625,9 @@ public class MysqlSchemaCodegen extends DefaultCodegen implements CodegenConfig try { columnDefinition.put("colDefault", toCodegenMysqlDataTypeDefault(defaultValue, (String) columnDefinition.get("colDataType"))); } catch (RuntimeException exception) { - LOGGER.warn("Property '" + baseName + "' of model '" + model.getName() + "' mapped to MySQL data type which doesn't support default value"); + LOGGER.warn( + "Property '{}' of model '{}' mapped to MySQL data type which doesn't support default value", + baseName, model.getName()); columnDefinition.put("colDefault", null); } } @@ -642,7 +656,7 @@ public class MysqlSchemaCodegen extends DefaultCodegen implements CodegenConfig if (vendorExtensions.containsKey(VENDOR_EXTENSION_MYSQL_SCHEMA)) { // user already specified schema values - LOGGER.info("Found vendor extension in '" + baseName + "' property, autogeneration skipped"); + LOGGER.info("Found vendor extension in '{}' property, autogeneration skipped", baseName); return; } @@ -664,7 +678,9 @@ public class MysqlSchemaCodegen extends DefaultCodegen implements CodegenConfig try { columnDefinition.put("colDefault", toCodegenMysqlDataTypeDefault(defaultValue, (String) columnDefinition.get("colDataType"))); } catch (RuntimeException exception) { - LOGGER.warn("Property '" + baseName + "' of model '" + model.getName() + "' mapped to MySQL data type which doesn't support default value"); + LOGGER.warn( + "Property '{}' of model '{}' mapped to MySQL data type which doesn't support default value", + baseName, model.getName()); columnDefinition.put("colDefault", null); } } @@ -693,7 +709,7 @@ public class MysqlSchemaCodegen extends DefaultCodegen implements CodegenConfig if (vendorExtensions.containsKey(VENDOR_EXTENSION_MYSQL_SCHEMA)) { // user already specified schema values - LOGGER.info("Found vendor extension in '" + baseName + "' property, autogeneration skipped"); + LOGGER.info("Found vendor extension in '{}' property, autogeneration skipped", baseName); return; } @@ -718,7 +734,9 @@ public class MysqlSchemaCodegen extends DefaultCodegen implements CodegenConfig try { columnDefinition.put("colDefault", toCodegenMysqlDataTypeDefault(defaultValue, (String) columnDefinition.get("colDataType"))); } catch (RuntimeException exception) { - LOGGER.warn("Property '" + baseName + "' of model '" + model.getName() + "' mapped to MySQL data type which doesn't support default value"); + LOGGER.warn( + "Property '{}' of model '{}' mapped to MySQL data type which doesn't support default value", + baseName, model.getName()); columnDefinition.put("colDefault", null); } } @@ -747,7 +765,7 @@ public class MysqlSchemaCodegen extends DefaultCodegen implements CodegenConfig if (vendorExtensions.containsKey(VENDOR_EXTENSION_MYSQL_SCHEMA)) { // user already specified schema values - LOGGER.info("Found vendor extension in '" + baseName + "' property, autogeneration skipped"); + LOGGER.info("Found vendor extension in '{}' property, autogeneration skipped", baseName); return; } @@ -769,7 +787,9 @@ public class MysqlSchemaCodegen extends DefaultCodegen implements CodegenConfig try { columnDefinition.put("colDefault", toCodegenMysqlDataTypeDefault(defaultValue, (String) columnDefinition.get("colDataType"))); } catch (RuntimeException exception) { - LOGGER.warn("Property '" + baseName + "' of model '" + model.getName() + "' mapped to MySQL data type which doesn't support default value"); + LOGGER.warn( + "Property '{}' of model '{}' mapped to MySQL data type which doesn't support default value", + baseName, model.getName()); columnDefinition.put("colDefault", null); } } @@ -803,7 +823,7 @@ public class MysqlSchemaCodegen extends DefaultCodegen implements CodegenConfig arg.put("isInteger", false); arg.put("isNumeric", true); } else { - LOGGER.warn("MySQL data type argument can be primitive type only. Class '" + value.getClass() + "' is provided"); + LOGGER.warn("MySQL data type argument can be primitive type only. Class '{}' is provided", value.getClass()); } arg.put("argumentValue", value); return arg; @@ -987,7 +1007,7 @@ public class MysqlSchemaCodegen extends DefaultCodegen implements CodegenConfig public String toDatabaseName(String name) { String identifier = toMysqlIdentifier(name, databaseNamePrefix, databaseNameSuffix); if (identifier.length() > IDENTIFIER_MAX_LENGTH) { - LOGGER.warn("Database name cannot exceed 64 chars. Name '" + name + "' will be truncated"); + LOGGER.warn("Database name cannot exceed 64 chars. Name '{}' will be truncated", name); identifier = identifier.substring(0, IDENTIFIER_MAX_LENGTH); } return identifier; @@ -1006,7 +1026,7 @@ public class MysqlSchemaCodegen extends DefaultCodegen implements CodegenConfig identifier = underscore(identifier); } if (identifier.length() > IDENTIFIER_MAX_LENGTH) { - LOGGER.warn("Table name cannot exceed 64 chars. Name '" + name + "' will be truncated"); + LOGGER.warn("Table name cannot exceed 64 chars. Name '{}' will be truncated", name); identifier = identifier.substring(0, IDENTIFIER_MAX_LENGTH); } return identifier; @@ -1025,7 +1045,7 @@ public class MysqlSchemaCodegen extends DefaultCodegen implements CodegenConfig identifier = underscore(identifier); } if (identifier.length() > IDENTIFIER_MAX_LENGTH) { - LOGGER.warn("Column name cannot exceed 64 chars. Name '" + name + "' will be truncated"); + LOGGER.warn("Column name cannot exceed 64 chars. Name '{}' will be truncated", name); identifier = identifier.substring(0, IDENTIFIER_MAX_LENGTH); } return identifier; @@ -1044,13 +1064,13 @@ public class MysqlSchemaCodegen extends DefaultCodegen implements CodegenConfig String escapedName = escapeMysqlQuotedIdentifier(name); // Database, table, and column names cannot end with space characters. if (escapedName.matches(".*\\s$")) { - LOGGER.warn("Database, table, and column names cannot end with space characters. Check '" + name + "' name"); + LOGGER.warn("Database, table, and column names cannot end with space characters. Check '{}' name", name); escapedName = escapedName.replaceAll("\\s+$", ""); } // Identifiers may begin with a digit but unless quoted may not consist solely of digits. if (escapedName.matches("^\\d+$")) { - LOGGER.warn("Database, table, and column names cannot consist solely of digits. Check '" + name + "' name"); + LOGGER.warn("Database, table, and column names cannot consist solely of digits. Check '{}' name", name); escapedName = prefix + escapedName + suffix; } @@ -1073,7 +1093,8 @@ public class MysqlSchemaCodegen extends DefaultCodegen implements CodegenConfig Pattern regexp = Pattern.compile("[^0-9a-zA-z$_\\u0080-\\uFFFF]"); Matcher matcher = regexp.matcher(identifier); if (matcher.find()) { - LOGGER.warn("Identifier '" + identifier + "' contains unsafe characters out of [0-9,a-z,A-Z$_] and U+0080..U+FFFF range"); + LOGGER.warn("Identifier '{}' contains unsafe characters out of [0-9,a-z,A-Z$_] and U+0080..U+FFFF range", + identifier); identifier = identifier.replaceAll("[^0-9a-zA-z$_\\u0080-\\uFFFF]", ""); } @@ -1095,7 +1116,8 @@ public class MysqlSchemaCodegen extends DefaultCodegen implements CodegenConfig Pattern regexp = Pattern.compile("[^\\u0001-\\u007F\\u0080-\\uFFFF]"); Matcher matcher = regexp.matcher(identifier); if (matcher.find()) { - LOGGER.warn("Identifier '" + identifier + "' contains unsafe characters out of U+0001..U+007F and U+0080..U+FFFF range"); + LOGGER.warn("Identifier '{}' contains unsafe characters out of U+0001..U+007F and U+0080..U+FFFF range", + identifier); identifier = identifier.replaceAll("[^\\u0001-\\u007F\\u0080-\\uFFFF]", ""); } @@ -1107,7 +1129,9 @@ public class MysqlSchemaCodegen extends DefaultCodegen implements CodegenConfig @Override public String escapeReservedWord(String name) { - LOGGER.warn("'" + name + "' is MySQL reserved word. Do not use that word or properly escape it with backticks in mustache template"); + LOGGER.warn( + "'{}' is MySQL reserved word. Do not use that word or properly escape it with backticks in mustache template", + name); return name; } @@ -1131,7 +1155,9 @@ public class MysqlSchemaCodegen extends DefaultCodegen implements CodegenConfig public void setDefaultDatabaseName(String databaseName) { String escapedName = toDatabaseName(databaseName); if (!escapedName.equals(databaseName)) { - LOGGER.error("Invalid database name. '" + databaseName + "' cannot be used as MySQL identifier. Escaped value '" + escapedName + "' will be used instead."); + LOGGER.error( + "Invalid database name. '{}' cannot be used as MySQL identifier. Escaped value '{}' will be used instead.", + databaseName, escapedName); } this.defaultDatabaseName = escapedName; } @@ -1196,7 +1222,8 @@ public class MysqlSchemaCodegen extends DefaultCodegen implements CodegenConfig this.identifierNamingConvention = naming; break; default: - LOGGER.warn("\"" + naming + "\" is invalid \"identifierNamingConvention\" argument. Current \"" + this.identifierNamingConvention + "\" used instead."); + LOGGER.warn("\"{}\" is invalid \"identifierNamingConvention\" argument. Current \"{}\" used instead.", + naming, this.identifierNamingConvention); } } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/NimClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/NimClientCodegen.java index ff07db2ede8..b5ee1575bd7 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/NimClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/NimClientCodegen.java @@ -195,7 +195,7 @@ public class NimClientCodegen extends DefaultCodegen implements CodegenConfig { @Override public String escapeReservedWord(String name) { - LOGGER.warn("A reserved word \"" + name + "\" is used. Consider renaming the field name"); + LOGGER.warn("A reserved word \"{}\" is used. Consider renaming the field name", name); if (this.reservedWordsMappings().containsKey(name)) { return this.reservedWordsMappings().get(name); } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/NodeJSExpressServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/NodeJSExpressServerCodegen.java index 4e6f0a0fb9d..c7edba19de0 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/NodeJSExpressServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/NodeJSExpressServerCodegen.java @@ -445,7 +445,7 @@ public class NodeJSExpressServerCodegen extends DefaultCodegen implements Codege if (exitValue != 0) { LOGGER.error("Error running the command ({}). Exit code: {}", command, exitValue); } - LOGGER.info("Successfully executed: " + command); + LOGGER.info("Successfully executed: {}", command); } catch (InterruptedException | IOException e) { LOGGER.error("Error running the command ({}). Exception: {}", command, e.getMessage()); // Restore interrupted state diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/OCamlClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/OCamlClientCodegen.java index 5d46a4af427..a1a7463937b 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/OCamlClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/OCamlClientCodegen.java @@ -530,13 +530,14 @@ public class OCamlClientCodegen extends DefaultCodegen implements CodegenConfig // model name cannot use reserved keyword, e.g. return if (isReservedWord(name)) { - LOGGER.warn(name + " (reserved word) cannot be used as model name. Renamed to " + ("model_" + name)); + LOGGER.warn("{} (reserved word) cannot be used as model name. Renamed to {}", name, "model_" + name); name = "model_" + name; // e.g. return => ModelReturn (after camelize) } // model name starts with number or _ if (name.matches("^\\d.*|^_.*")) { - LOGGER.warn(name + " (model name starts with number) cannot be used as model name. Renamed to " + ("model_" + name)); + LOGGER.warn("{} (model name starts with number) cannot be used as model name. Renamed to {}", name, + "model_" + name); name = "model_" + name; // e.g. 200Response => Model200Response (after camelize) } @@ -578,14 +579,15 @@ public class OCamlClientCodegen extends DefaultCodegen implements CodegenConfig ArraySchema ap = (ArraySchema) p; Schema inner = ap.getItems(); if (inner == null) { - LOGGER.warn(ap.getName() + "(array property) does not have a proper inner type defined.Default to string"); + LOGGER.warn("{}(array property) does not have a proper inner type defined.Default to string", + ap.getName()); inner = new StringSchema().description("TODO default missing array inner type to string"); } return getTypeDeclaration(inner) + " list"; } else if (ModelUtils.isMapSchema(p)) { Schema inner = getAdditionalProperties(p); if (inner == null) { - LOGGER.warn(p.getName() + "(map property) does not have a proper inner type defined. Default to string"); + LOGGER.warn("{}(map property) does not have a proper inner type defined. Default to string", p.getName()); inner = new StringSchema().description("TODO default missing map inner type to string"); } String prefix = inner.getEnum() != null ? "Enums." : ""; @@ -637,7 +639,7 @@ public class OCamlClientCodegen extends DefaultCodegen implements CodegenConfig // method name cannot use reserved keyword, e.g. return if (isReservedWord(sanitizedOperationId) || sanitizedOperationId.matches("^[0-9].*")) { - LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + underscore("call_" + operationId)); + LOGGER.warn("{} (reserved word) cannot be used as method name. Renamed to {}", operationId, underscore("call_" + operationId)); sanitizedOperationId = "call_" + sanitizedOperationId; } @@ -814,7 +816,7 @@ public class OCamlClientCodegen extends DefaultCodegen implements CodegenConfig if (exitValue != 0) { LOGGER.error("Error running the command ({}). Exit value: {}", command, exitValue); } else { - LOGGER.info("Successfully executed: " + command); + LOGGER.info("Successfully executed: {}", command); } } catch (InterruptedException | IOException e) { LOGGER.error("Error running the command ({}). Exception: {}", command, e.getMessage()); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ObjcClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ObjcClientCodegen.java index e8735b7e380..7ced61d9f4f 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ObjcClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ObjcClientCodegen.java @@ -435,7 +435,8 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { public String toModelName(String type) { // model name cannot use reserved keyword if (reservedWords.contains(type)) { - LOGGER.warn(type + " (reserved word) cannot be used as model name. Renamed to " + ("model_" + type) + " before further processing"); + LOGGER.warn("{} (reserved word) cannot be used as model name. Renamed to {} before further processing", + type, "model_" + type); type = "model_" + type; // e.g. return => ModelReturn (after camelize) } @@ -614,7 +615,7 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { // method name cannot use reserved keyword, e.g. return if (isReservedWord(operationId)) { - LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + camelize(sanitizeName("call_" + operationId), true)); + LOGGER.warn("{} (reserved word) cannot be used as method name. Renamed to {}", operationId, camelize(sanitizeName("call_" + operationId), true)); operationId = "call_" + operationId; } @@ -765,7 +766,7 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { // e.g. [[SWGPet alloc] init example = "[[" + type + " alloc] init]"; } else { - LOGGER.warn("Example value for " + type + " not handled properly in setParameterExampleValue"); + LOGGER.warn("Example value for {} not handled properly in setParameterExampleValue", type); } if (example == null) { diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/OpenAPIGenerator.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/OpenAPIGenerator.java index 9902ddb0740..ccd3ff685d6 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/OpenAPIGenerator.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/OpenAPIGenerator.java @@ -89,7 +89,7 @@ public class OpenAPIGenerator extends DefaultCodegen implements CodegenConfig { try { String outputFile = outputFolder + File.separator + outputFileName; FileUtils.writeStringToFile(new File(outputFile), jsonOpenAPI, StandardCharsets.UTF_8); - LOGGER.info("wrote file to " + outputFile); + LOGGER.info("wrote file to {}", outputFile); } catch (Exception e) { LOGGER.error(e.getMessage(), e); } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PerlClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PerlClientCodegen.java index fca307b1f66..b41bb590b36 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PerlClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PerlClientCodegen.java @@ -336,13 +336,14 @@ public class PerlClientCodegen extends DefaultCodegen implements CodegenConfig { // model name cannot use reserved keyword if (isReservedWord(name)) { - LOGGER.warn(name + " (reserved word) cannot be used as model name. Renamed to " + camelize("model_" + name)); + LOGGER.warn("{} (reserved word) cannot be used as model name. Renamed to {}", name, camelize("model_" + name)); name = "model_" + name; } // model name starts with number if (name.matches("^\\d.*")) { - LOGGER.warn(name + " (model name starts with number) cannot be used as model name. Renamed to " + camelize("model_" + name)); + LOGGER.warn("{} (model name starts with number) cannot be used as model name. Renamed to {}", name, + camelize("model_" + name)); name = "model_" + name; // e.g. 200Response => Model200Response (after camelize) } @@ -409,19 +410,19 @@ public class PerlClientCodegen extends DefaultCodegen implements CodegenConfig { //rename to empty_function_name_1 (e.g.) if method name is empty if (StringUtils.isEmpty(operationId)) { operationId = underscore("empty_function_name_" + emptyFunctionNameCounter++); - LOGGER.warn("Empty method name (operationId) found. Renamed to " + operationId); + LOGGER.warn("Empty method name (operationId) found. Renamed to {}", operationId); return operationId; } // method name cannot use reserved keyword, e.g. return if (isReservedWord(operationId)) { - LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + underscore(sanitizeName("call_" + operationId))); + LOGGER.warn("{} (reserved word) cannot be used as method name. Renamed to {}", operationId, underscore(sanitizeName("call_" + operationId))); return underscore(sanitizeName("call_" + operationId)); } // operationId starts with a number if (operationId.matches("^\\d.*")) { - LOGGER.warn(operationId + " (starting with a number) cannot be used as method name. Renamed to " + underscore(sanitizeName("call_" + operationId))); + LOGGER.warn("{} (starting with a number) cannot be used as method name. Renamed to {}", operationId, underscore(sanitizeName("call_" + operationId))); operationId = "call_" + operationId; } @@ -620,7 +621,7 @@ public class PerlClientCodegen extends DefaultCodegen implements CodegenConfig { if (exitValue != 0) { LOGGER.error("Error running the command ({}). Exit code: {}", command, exitValue); } else { - LOGGER.info("Successfully executed: " + command); + LOGGER.info("Successfully executed: {}", command); } } catch (InterruptedException | IOException e) { LOGGER.error("Error running the command ({}). Exception: {}", command, e.getMessage()); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpMezzioPathHandlerServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpMezzioPathHandlerServerCodegen.java index 658537e414b..529c5a27e21 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpMezzioPathHandlerServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpMezzioPathHandlerServerCodegen.java @@ -21,9 +21,13 @@ 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.PathItem.HttpMethod; +import io.swagger.v3.oas.models.Paths; 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; +import io.swagger.v3.oas.models.responses.ApiResponses; import org.openapitools.codegen.*; import org.openapitools.codegen.meta.features.*; import org.openapitools.codegen.utils.ModelUtils; @@ -35,12 +39,17 @@ import java.util.*; public class PhpMezzioPathHandlerServerCodegen extends AbstractPhpCodegen { private final Logger LOGGER = LoggerFactory.getLogger(PhpMezzioPathHandlerServerCodegen.class); - - // TODO: Rename to x- prefixed vendor extensions, per specification. + // Custom generator option names + public static final String OPT_MODERN = "modern"; + // Internal vendor extension names for extra template data that should not be set in specification public static final String VEN_FROM_QUERY = "internal.ze-ph.fromQuery"; public static final String VEN_COLLECTION_FORMAT = "internal.ze-ph.collectionFormat"; public static final String VEN_QUERY_DATA_TYPE = "internal.ze-ph.queryDataType"; public static final String VEN_HAS_QUERY_DATA = "internal.ze-ph.hasQueryData"; + public static final String VEN_FROM_CONTAINER = "internal.ze-ph.fromContainer"; + public static final String VEN_CONTAINER_DATA_TYPE = "internal.ze-ph.containerDataType"; + + private boolean useModernSyntax = false; @Override public CodegenType getTag() { @@ -85,6 +94,8 @@ public class PhpMezzioPathHandlerServerCodegen extends AbstractPhpCodegen { modelDirName = "DTO"; apiPackage = invokerPackage + "\\" + apiDirName; modelPackage = invokerPackage + "\\" + modelDirName; + //"Api" classes have dedicated namespace so there is no need to add non-empty suffix by default + apiNameSuffix = ""; apiTestTemplateFiles.clear(); modelTestTemplateFiles.clear(); @@ -103,6 +114,17 @@ public class PhpMezzioPathHandlerServerCodegen extends AbstractPhpCodegen { supportingFiles.add(new SupportingFile("InternalServerError.php.mustache", srcBasePath + File.separator + "Middleware", "InternalServerError.php")); additionalProperties.put(CodegenConstants.ARTIFACT_VERSION, "1.0.0"); + //Register custom CLI options + addSwitch(OPT_MODERN, "use modern language features (generated code will require PHP 8.0)", useModernSyntax); + } + + @Override + public void processOpts() { + super.processOpts(); + if (additionalProperties.containsKey(OPT_MODERN)) { + embeddedTemplateDir = templateDir = "php-mezzio-ph-modern"; + useModernSyntax = true; + } } /** @@ -136,29 +158,31 @@ public class PhpMezzioPathHandlerServerCodegen extends AbstractPhpCodegen { } } - /** - * Return the file name of the Api Test - * - * @param name the file name of the Api - * @return the file name of the Api - */ - @Override - public String toApiFilename(String name) { - return toApiName(name); - } - - /** - * Output the API (class) name (capitalized) ending with "Api" - * Return DefaultApi if name is empty - * - * @param name the name of the Api - * @return capitalized Api name ending with "Api" - */ @Override public String toApiName(String name) { - //Remove } - name = name.replaceAll("[\\}]", ""); - return super.toModelName(name); + return super.toApiName(toModelName(name)); + } + + @Override + public String getTypeDeclaration(Schema p) { + String result; + Map extensions = p.getExtensions(); + if ((extensions != null) && extensions.containsKey(VEN_CONTAINER_DATA_TYPE)) { + result = (String) extensions.get(VEN_CONTAINER_DATA_TYPE); + } else if (useModernSyntax && (ModelUtils.isArraySchema(p) || ModelUtils.isMapSchema(p))) { + result = "array"; + } else { + result = super.getTypeDeclaration(p); + } + return result; + } + + @Override + public void preprocessOpenAPI(OpenAPI openAPI) { + super.preprocessOpenAPI(openAPI); + + generateParameterSchemas(openAPI); + generateContainerSchemas(openAPI); } /** @@ -166,10 +190,7 @@ public class PhpMezzioPathHandlerServerCodegen extends AbstractPhpCodegen { * * @param openAPI OpenAPI object */ - @Override - public void preprocessOpenAPI(OpenAPI openAPI) { - super.preprocessOpenAPI(openAPI); - + protected void generateParameterSchemas(OpenAPI openAPI) { Map paths = openAPI.getPaths(); if (paths != null) { for (String pathname : paths.keySet()) { @@ -178,34 +199,34 @@ public class PhpMezzioPathHandlerServerCodegen extends AbstractPhpCodegen { if (operationMap != null) { for (HttpMethod method : operationMap.keySet()) { Operation operation = operationMap.get(method); - Map schemas = new HashMap<>(); + Map propertySchemas = new HashMap<>(); if (operation == null || operation.getParameters() == null) { continue; } List requiredProperties = new ArrayList<>(); for (Parameter parameter : operation.getParameters()) { - Schema schema = convertParameterToSchema(parameter); - if (schema != null) { - schemas.put(schema.getName(), schema); - if (Boolean.TRUE.equals(parameter.getRequired())) { - requiredProperties.add(schema.getName()); + Parameter referencedParameter = ModelUtils.getReferencedParameter(openAPI, parameter); + Schema propertySchema = convertParameterToSchema(openAPI, referencedParameter); + if (propertySchema != null) { + propertySchemas.put(propertySchema.getName(), propertySchema); + if (Boolean.TRUE.equals(referencedParameter.getRequired())) { + requiredProperties.add(propertySchema.getName()); } } } - if (!schemas.isEmpty()) { - ObjectSchema model = new ObjectSchema(); + if (!propertySchemas.isEmpty()) { + ObjectSchema schema = new ObjectSchema(); String operationId = getOrGenerateOperationId(operation, pathname, method.name()); - model.setDescription("Query parameters for " + operationId); - model.setProperties(schemas); - model.setRequired(requiredProperties); - //Add internal extension directly, because addExtension filters extension names - addInternalExtensionToSchema(model, VEN_FROM_QUERY, Boolean.TRUE); - String definitionName = generateUniqueDefinitionName(operationId + "QueryData", openAPI); - openAPI.getComponents().addSchemas(definitionName, model); - String definitionModel = "\\" + modelPackage + "\\" + toModelName(definitionName); - addInternalExtensionToOperation(operation, VEN_QUERY_DATA_TYPE, definitionModel); + schema.setDescription("Query parameters for " + operationId); + schema.setProperties(propertySchemas); + schema.setRequired(requiredProperties); + addInternalExtensionToSchema(schema, VEN_FROM_QUERY, Boolean.TRUE); + String schemaName = generateUniqueSchemaName(openAPI, operationId + "QueryData"); + openAPI.getComponents().addSchemas(schemaName, schema); + String schemaDataType = getTypeDeclaration(toModelName(schemaName)); + addInternalExtensionToOperation(operation, VEN_QUERY_DATA_TYPE, schemaDataType); addInternalExtensionToOperation(operation, VEN_HAS_QUERY_DATA, Boolean.TRUE); } } @@ -214,17 +235,18 @@ public class PhpMezzioPathHandlerServerCodegen extends AbstractPhpCodegen { } } - protected Schema convertParameterToSchema(Parameter parameter) { + protected Schema convertParameterToSchema(OpenAPI openAPI, Parameter parameter) { Schema property = null; if (parameter instanceof QueryParameter) { QueryParameter queryParameter = (QueryParameter) parameter; + Schema parameterSchema = ModelUtils.getReferencedSchema(openAPI, queryParameter.getSchema()); // array - if (ModelUtils.isArraySchema(queryParameter.getSchema())) { - Schema inner = ((ArraySchema) queryParameter.getSchema()).getItems(); + if (ModelUtils.isArraySchema(parameterSchema)) { + Schema itemSchema = ((ArraySchema) parameterSchema).getItems(); ArraySchema arraySchema = new ArraySchema(); - arraySchema.setMinItems(queryParameter.getSchema().getMinItems()); - arraySchema.setMaxItems(queryParameter.getSchema().getMaxItems()); - arraySchema.setItems(inner); + arraySchema.setMinItems(parameterSchema.getMinItems()); + arraySchema.setMaxItems(parameterSchema.getMaxItems()); + arraySchema.setItems(itemSchema); String collectionFormat = getCollectionFormat(queryParameter); if (collectionFormat == null) { collectionFormat = "csv"; @@ -232,25 +254,25 @@ public class PhpMezzioPathHandlerServerCodegen extends AbstractPhpCodegen { addInternalExtensionToSchema(arraySchema, VEN_COLLECTION_FORMAT, collectionFormat); property = arraySchema; } else { // non-array e.g. string, integer - switch (queryParameter.getSchema().getType()) { + switch (parameterSchema.getType()) { case "string": StringSchema stringSchema = new StringSchema(); - stringSchema.setMinLength(queryParameter.getSchema().getMinLength()); - stringSchema.setMaxLength(queryParameter.getSchema().getMaxLength()); - stringSchema.setPattern(queryParameter.getSchema().getPattern()); - stringSchema.setEnum(queryParameter.getSchema().getEnum()); + stringSchema.setMinLength(parameterSchema.getMinLength()); + stringSchema.setMaxLength(parameterSchema.getMaxLength()); + stringSchema.setPattern(parameterSchema.getPattern()); + stringSchema.setEnum(parameterSchema.getEnum()); property = stringSchema; break; case "integer": IntegerSchema integerSchema = new IntegerSchema(); - integerSchema.setMinimum(queryParameter.getSchema().getMinimum()); - integerSchema.setMaximum(queryParameter.getSchema().getMaximum()); + integerSchema.setMinimum(parameterSchema.getMinimum()); + integerSchema.setMaximum(parameterSchema.getMaximum()); property = integerSchema; break; case "number": NumberSchema floatSchema = new NumberSchema(); - floatSchema.setMinimum(queryParameter.getSchema().getMinimum()); - floatSchema.setMaximum(queryParameter.getSchema().getMaximum()); + floatSchema.setMinimum(parameterSchema.getMinimum()); + floatSchema.setMaximum(parameterSchema.getMaximum()); property = floatSchema; break; case "boolean": @@ -264,6 +286,7 @@ public class PhpMezzioPathHandlerServerCodegen extends AbstractPhpCodegen { break; } } + if (property != null) { property.setName(queryParameter.getName()); property.setDescription(queryParameter.getDescription()); @@ -289,7 +312,7 @@ public class PhpMezzioPathHandlerServerCodegen extends AbstractPhpCodegen { operation.getExtensions().put(name, value); } - protected String generateUniqueDefinitionName(String name, OpenAPI openAPI) { + protected String generateUniqueSchemaName(OpenAPI openAPI, String name) { String result = name; if (openAPI.getComponents().getSchemas() != null) { int count = 1; @@ -301,6 +324,90 @@ public class PhpMezzioPathHandlerServerCodegen extends AbstractPhpCodegen { return result; } + /** + * Generate additional model definitions for containers in whole specification + * + * @param openAPI OpenAPI object + */ + protected void generateContainerSchemas(OpenAPI openAPI) { + Paths paths = openAPI.getPaths(); + for (String pathName : paths.keySet()) { + for (Operation operation : paths.get(pathName).readOperations()) { + List parameters = operation.getParameters(); + if (parameters != null) { + for (Parameter parameter : parameters) { + generateContainerSchemas(openAPI, ModelUtils.getReferencedParameter(openAPI, parameter).getSchema()); + } + } + RequestBody requestBody = ModelUtils.getReferencedRequestBody(openAPI, operation.getRequestBody()); + if (requestBody != null) { + Content requestBodyContent = requestBody.getContent(); + if (requestBodyContent != null) { + for (String mediaTypeName : requestBodyContent.keySet()) { + generateContainerSchemas(openAPI, requestBodyContent.get(mediaTypeName).getSchema()); + } + } + } + ApiResponses responses = operation.getResponses(); + for (String responseCode : responses.keySet()) { + ApiResponse response = ModelUtils.getReferencedApiResponse(openAPI, responses.get(responseCode)); + Content responseContent = response.getContent(); + if (responseContent != null) { + for (String mediaTypeName : responseContent.keySet()) { + generateContainerSchemas(openAPI, responseContent.get(mediaTypeName).getSchema()); + } + } + } + } + } + } + + /** + * Generate additional model definitions for containers in specified schema + * + * @param openAPI OpenAPI object + * @param schema OAS schema to process + */ + protected void generateContainerSchemas(OpenAPI openAPI, Schema schema) { + if (schema != null) { + //Dereference schema + schema = ModelUtils.getReferencedSchema(openAPI, schema); + Boolean isContainer = Boolean.FALSE; + + if (ModelUtils.isObjectSchema(schema)) { + //Recursively process all schemas of object properties + Map properties = schema.getProperties(); + if (properties != null) { + for (String propertyName: properties.keySet()) { + generateContainerSchemas(openAPI, properties.get(propertyName)); + } + } + } else if (ModelUtils.isArraySchema(schema)) { + //Recursively process schema of array items + generateContainerSchemas(openAPI, ((ArraySchema) schema).getItems()); + isContainer = Boolean.TRUE; + } else if (ModelUtils.isMapSchema(schema)) { + //Recursively process schema of map items + Object itemSchema = schema.getAdditionalProperties(); + if (itemSchema instanceof Schema) { + generateContainerSchemas(openAPI, (Schema) itemSchema); + } + isContainer = Boolean.TRUE; + } + + if (isContainer) { + //Generate special component schema for container + String containerSchemaName = generateUniqueSchemaName(openAPI, "Collection"); + Schema containerSchema = new ObjectSchema(); + containerSchema.addProperties("inner", schema); + addInternalExtensionToSchema(containerSchema, VEN_FROM_CONTAINER, Boolean.TRUE); + openAPI.getComponents().addSchemas(containerSchemaName, containerSchema); + String containerDataType = getTypeDeclaration(toModelName(containerSchemaName)); + addInternalExtensionToSchema(schema, VEN_CONTAINER_DATA_TYPE, containerDataType); + } + } + } + @Override public Map postProcessOperationsWithModels(Map objs, List allModels) { objs = super.postProcessOperationsWithModels(objs, allModels); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpSlim4ServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpSlim4ServerCodegen.java index d45bf289e7f..23a9de74337 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpSlim4ServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpSlim4ServerCodegen.java @@ -16,6 +16,14 @@ package org.openapitools.codegen.languages; +import io.swagger.v3.oas.models.Operation; +import io.swagger.v3.oas.models.security.SecurityScheme; +import io.swagger.v3.oas.models.servers.Server; +import org.apache.commons.lang3.StringEscapeUtils; +import org.apache.commons.lang3.StringUtils; +import org.openapitools.codegen.CodegenType; +import org.openapitools.codegen.CodegenOperation; +import org.openapitools.codegen.CodegenSecurity; import org.openapitools.codegen.CliOption; import org.openapitools.codegen.CodegenConstants; import org.openapitools.codegen.SupportingFile; @@ -26,12 +34,22 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; +import java.io.UnsupportedEncodingException; +import java.net.URLEncoder; +import java.util.*; -public class PhpSlim4ServerCodegen extends PhpSlimServerCodegen { +import static org.openapitools.codegen.utils.StringUtils.camelize; + +public class PhpSlim4ServerCodegen extends AbstractPhpCodegen { private final Logger LOGGER = LoggerFactory.getLogger(PhpSlim4ServerCodegen.class); + public static final String USER_CLASSNAME_KEY = "userClassname"; public static final String PSR7_IMPLEMENTATION = "psr7Implementation"; + protected String groupId = "org.openapitools"; + protected String artifactId = "openapi-server"; + protected String authDirName = "Auth"; + protected String authPackage = ""; protected String psr7Implementation = "slim-psr7"; protected String interfacesDirName = "Interfaces"; protected String interfacesPackage = ""; @@ -40,6 +58,18 @@ public class PhpSlim4ServerCodegen extends PhpSlimServerCodegen { super(); modifyFeatureSet(features -> features + .includeDocumentationFeatures(DocumentationFeature.Readme) + .wireFormatFeatures(EnumSet.of(WireFormatFeature.JSON, WireFormatFeature.XML)) + .securityFeatures(EnumSet.noneOf(SecurityFeature.class)) + .excludeGlobalFeatures( + GlobalFeature.XMLStructureDefinitions, + GlobalFeature.Callbacks, + GlobalFeature.LinkObjects, + GlobalFeature.ParameterStyling + ) + .excludeSchemaSupportFeatures( + SchemaSupportFeature.Polymorphism + ) .includeClientModificationFeatures(ClientModificationFeature.MockServer) ); @@ -47,10 +77,29 @@ public class PhpSlim4ServerCodegen extends PhpSlimServerCodegen { .stability(Stability.STABLE) .build(); + // clear import mapping (from default generator) as slim does not use it + // at the moment + importMapping.clear(); + + variableNamingConvention = "camelCase"; + artifactVersion = "1.0.0"; + setInvokerPackage("OpenAPIServer"); + apiPackage = invokerPackage + "\\" + apiDirName; + modelPackage = invokerPackage + "\\" + modelDirName; + authPackage = invokerPackage + "\\" + authDirName; interfacesPackage = invokerPackage + "\\" + interfacesDirName; outputFolder = "generated-code" + File.separator + "slim4"; + + modelTestTemplateFiles.put("model_test.mustache", ".php"); + // no doc files + modelDocTemplateFiles.clear(); + apiDocTemplateFiles.clear(); + embeddedTemplateDir = templateDir = "php-slim4-server"; + additionalProperties.put(CodegenConstants.GROUP_ID, groupId); + additionalProperties.put(CodegenConstants.ARTIFACT_ID, artifactId); + // override cliOptions from AbstractPhpCodegen updateOption(AbstractPhpCodegen.VARIABLE_NAMING_CONVENTION, "camelCase"); @@ -68,6 +117,11 @@ public class PhpSlim4ServerCodegen extends PhpSlimServerCodegen { cliOptions.add(psr7Option); } + @Override + public CodegenType getTag() { + return CodegenType.SERVER; + } + @Override public String getName() { return "php-slim4"; @@ -78,15 +132,39 @@ public class PhpSlim4ServerCodegen extends PhpSlimServerCodegen { return "Generates a PHP Slim 4 Framework server library(with Mock server)."; } + @Override + public String apiFileFolder() { + if (apiPackage.startsWith(invokerPackage + "\\")) { + // need to strip out invokerPackage from path + return (outputFolder + File.separator + toSrcPath(StringUtils.removeStart(apiPackage, invokerPackage + "\\"), srcBasePath)); + } + return (outputFolder + File.separator + toSrcPath(apiPackage, srcBasePath)); + } + + @Override + public String modelFileFolder() { + if (modelPackage.startsWith(invokerPackage + "\\")) { + // need to strip out invokerPackage from path + return (outputFolder + File.separator + toSrcPath(StringUtils.removeStart(modelPackage, invokerPackage + "\\"), srcBasePath)); + } + return (outputFolder + File.separator + toSrcPath(modelPackage, srcBasePath)); + } + @Override public void processOpts() { super.processOpts(); if (additionalProperties.containsKey(CodegenConstants.INVOKER_PACKAGE)) { + // Update the invokerPackage for the default authPackage + authPackage = invokerPackage + "\\" + authDirName; // Update interfacesPackage interfacesPackage = invokerPackage + "\\" + interfacesDirName; } + // make auth src path available in mustache template + additionalProperties.put("authPackage", authPackage); + additionalProperties.put("authSrcPath", "./" + toSrcPath(authPackage, srcBasePath)); + // same for interfaces package additionalProperties.put("interfacesPackage", interfacesPackage); additionalProperties.put("interfacesSrcPath", "./" + toSrcPath(interfacesPackage, srcBasePath)); @@ -117,10 +195,20 @@ public class PhpSlim4ServerCodegen extends PhpSlimServerCodegen { additionalProperties.put("isZendDiactoros", Boolean.TRUE); break; default: - LOGGER.warn("\"" + getPsr7Implementation() + "\" is invalid \"psr7Implementation\" codegen option. Default \"slim-psr7\" used instead."); + LOGGER.warn( + "\"{}\" is invalid \"psr7Implementation\" codegen option. Default \"slim-psr7\" used instead.", + getPsr7Implementation()); additionalProperties.put("isSlimPsr7", Boolean.TRUE); } + supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); + supportingFiles.add(new SupportingFile("composer.mustache", "", "composer.json")); + supportingFiles.add(new SupportingFile("index.mustache", "", "index.php")); + supportingFiles.add(new SupportingFile(".htaccess", "", ".htaccess")); + supportingFiles.add(new SupportingFile("SlimRouter.mustache", toSrcPath(invokerPackage, srcBasePath), "SlimRouter.php")); + supportingFiles.add(new SupportingFile("phpunit.xml.mustache", "", "phpunit.xml.dist")); + supportingFiles.add(new SupportingFile("phpcs.xml.mustache", "", "phpcs.xml.dist")); + // Slim 4 doesn't parse JSON body anymore we need to add suggested middleware // ref: https://www.slimframework.com/docs/v4/objects/request.html#the-request-body supportingFiles.add(new SupportingFile("htaccess_deny_all", "config", ".htaccess")); @@ -131,6 +219,126 @@ public class PhpSlim4ServerCodegen extends PhpSlimServerCodegen { supportingFiles.add(new SupportingFile("base_model_test.mustache", toSrcPath(invokerPackage, testBasePath), "BaseModelTest.php")); } + @Override + public Map postProcessOperationsWithModels(Map objs, List allModels) { + Map operations = (Map) objs.get("operations"); + List operationList = (List) operations.get("operation"); + addUserClassnameToOperations(operations); + escapeMediaType(operationList); + return objs; + } + + @Override + public Map postProcessSupportingFileData(Map objs) { + Map apiInfo = (Map) objs.get("apiInfo"); + List> apiList = (List>) apiInfo.get("apis"); + for (HashMap api : apiList) { + HashMap operations = (HashMap) api.get("operations"); + List operationList = (List) operations.get("operation"); + + // Sort operations to avoid static routes shadowing + // ref: https://github.com/nikic/FastRoute/blob/master/src/DataGenerator/RegexBasedAbstract.php#L92-L101 + Collections.sort(operationList, new Comparator() { + @Override + public int compare(CodegenOperation one, CodegenOperation another) { + if (one.getHasPathParams() && !another.getHasPathParams()) return 1; + if (!one.getHasPathParams() && another.getHasPathParams()) return -1; + return 0; + } + }); + } + return objs; + } + + @Override + public List fromSecurity(Map securitySchemeMap) { + List codegenSecurities = super.fromSecurity(securitySchemeMap); + if (Boolean.FALSE.equals(codegenSecurities.isEmpty())) { + supportingFiles.add(new SupportingFile("abstract_authenticator.mustache", toSrcPath(authPackage, srcBasePath), toAbstractName("Authenticator") + ".php")); + } + return codegenSecurities; + } + + @Override + public String toApiName(String name) { + if (name.length() == 0) { + return toAbstractName("DefaultApi"); + } + return toAbstractName(camelize(name) + "Api"); + } + + @Override + public String toApiTestFilename(String name) { + if (name.length() == 0) { + return "DefaultApiTest"; + } + return camelize(name) + "ApiTest"; + } + + /** + * Strips out abstract prefix and suffix from classname and puts it in "userClassname" property of operations object. + * + * @param operations codegen object with operations + */ + private void addUserClassnameToOperations(Map operations) { + String classname = (String) operations.get("classname"); + classname = classname.replaceAll("^" + abstractNamePrefix, ""); + classname = classname.replaceAll(abstractNameSuffix + "$", ""); + operations.put(USER_CLASSNAME_KEY, classname); + } + + @Override + public String encodePath(String input) { + if (input == null) { + return input; + } + + // from DefaultCodegen.java + // remove \t, \n, \r + // replace \ with \\ + // replace " with \" + // outter unescape to retain the original multi-byte characters + // finally escalate characters avoiding code injection + input = super.escapeUnsafeCharacters( + StringEscapeUtils.unescapeJava( + StringEscapeUtils.escapeJava(input) + .replace("\\/", "/")) + .replaceAll("[\\t\\n\\r]", " ") + .replace("\\", "\\\\")); + // .replace("\"", "\\\"")); + + // from AbstractPhpCodegen.java + // Trim the string to avoid leading and trailing spaces. + input = input.trim(); + try { + + input = URLEncoder.encode(input, "UTF-8") + .replaceAll("\\+", "%20") + .replaceAll("\\%2F", "/") + .replaceAll("\\%7B", "{") // keep { part of complex placeholders + .replaceAll("\\%7D", "}") // } part + .replaceAll("\\%5B", "[") // [ part + .replaceAll("\\%5D", "]") // ] part + .replaceAll("\\%3A", ":") // : part + .replaceAll("\\%2B", "+") // + part + .replaceAll("\\%5C\\%5Cd", "\\\\d"); // \d part + } catch (UnsupportedEncodingException e) { + // continue + LOGGER.error(e.getMessage(), e); + } + return input; + } + + @Override + public CodegenOperation fromOperation(String path, + String httpMethod, + Operation operation, + List servers) { + CodegenOperation op = super.fromOperation(path, httpMethod, operation, servers); + op.path = encodePath(path); + return op; + } + /** * Set PSR-7 implementation package. * Ref: https://www.slimframework.com/docs/v4/concepts/value-objects.html @@ -147,7 +355,8 @@ public class PhpSlim4ServerCodegen extends PhpSlimServerCodegen { break; default: this.psr7Implementation = "slim-psr7"; - LOGGER.warn("\"" + psr7Implementation + "\" is invalid \"psr7Implementation\" argument. Default \"slim-psr7\" used instead."); + LOGGER.warn("\"{}\" is invalid \"psr7Implementation\" argument. Default \"slim-psr7\" used instead.", + psr7Implementation); } } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PowerShellClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PowerShellClientCodegen.java index 0b4add67606..97c3b260375 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PowerShellClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PowerShellClientCodegen.java @@ -63,6 +63,8 @@ public class PowerShellClientCodegen extends DefaultCodegen implements CodegenCo protected String tags; protected String iconUri; protected Set paramNameReservedWords; + protected String modelsCmdletVerb = "Initialize"; + protected boolean useClassNameInModelsExamples = true; /** * Constructs an instance of `PowerShellClientCodegen`. @@ -539,6 +541,13 @@ public class PowerShellClientCodegen extends DefaultCodegen implements CodegenCo cliOptions.add(new CliOption("iconUri","A URL to an icon representing the generated PowerShell module")); cliOptions.add(new CliOption("releaseNotes","Release notes of the generated PowerShell module")); cliOptions.add(new CliOption("skipVerbParsing", "Set skipVerbParsing to not try get powershell verbs of operation names")); + cliOptions.add(new CliOption("modelsCmdletVerb", "Verb to be used when generating the Models cmdlets in the examples.").defaultValue(this.modelsCmdletVerb)); + + CliOption useClassNameInModelsExamplesOpt = CliOption.newBoolean( + "useClassNameInModelsExamples", + "Use classname instead of name when generating the Models cmdlets in the examples." + ).defaultValue(this.useClassNameInModelsExamples ? Boolean.TRUE.toString() : Boolean.FALSE.toString()); + cliOptions.add(useClassNameInModelsExamplesOpt); // option to change how we process + set the data in the 'additionalProperties' keyword. CliOption disallowAdditionalPropertiesIfNotPresentOpt = CliOption.newBoolean( @@ -632,6 +641,10 @@ public class PowerShellClientCodegen extends DefaultCodegen implements CodegenCo public void setSkipVerbParsing(boolean skipVerbParsing) { this.skipVerbParsing = skipVerbParsing; } + public void SetModelsCmdletVerb(String modelsCmdletVerb) { this.modelsCmdletVerb = modelsCmdletVerb; } + + public void SetUseClassNameInModelsExamples(boolean useClassNameInModelsExamples) { this.useClassNameInModelsExamples = useClassNameInModelsExamples; } + @Override public void processOpts() { this.setLegacyDiscriminatorBehavior(false); @@ -704,6 +717,18 @@ public class PowerShellClientCodegen extends DefaultCodegen implements CodegenCo additionalProperties.put("iconUri", iconUri); } + if (additionalProperties.containsKey("modelsCmdletVerb")) { + this.SetModelsCmdletVerb((String) additionalProperties.get("modelsCmdletVerb")); + } else { + additionalProperties.put("modelsCmdletVerb", this.modelsCmdletVerb); + } + + if (additionalProperties.containsKey("useClassNameInModelsExamples")) { + this.SetUseClassNameInModelsExamples(convertPropertyToBoolean("useClassNameInModelsExamples")); + } else { + additionalProperties.put("useClassNameInModelsExamples", this.useClassNameInModelsExamples); + } + if (StringUtils.isNotBlank(powershellGalleryUrl)) { // get the last segment of the URL // e.g. https://www.powershellgallery.com/packages/PSTwitter => PSTwitter @@ -742,11 +767,15 @@ public class PowerShellClientCodegen extends DefaultCodegen implements CodegenCo } if (additionalProperties.containsKey(CodegenConstants.MODEL_PACKAGE)) { - LOGGER.warn(CodegenConstants.MODEL_PACKAGE + " with " + this.getName() + " generator is ignored. Setting this value independently of " + CodegenConstants.PACKAGE_NAME + " is not currently supported."); + LOGGER.warn( + "{} with {} generator is ignored. Setting this value independently of {} is not currently supported.", + CodegenConstants.MODEL_PACKAGE, this.getName(), CodegenConstants.PACKAGE_NAME); } if (additionalProperties.containsKey(CodegenConstants.API_PACKAGE)) { - LOGGER.warn(CodegenConstants.API_PACKAGE + " with " + this.getName() + " generator is ignored. Setting this value independently of " + CodegenConstants.PACKAGE_NAME + " is not currently supported."); + LOGGER.warn( + "{} with {} generator is ignored. Setting this value independently of {} is not currently supported.", + CodegenConstants.API_PACKAGE, this.getName(), CodegenConstants.PACKAGE_NAME); } if (additionalProperties.containsKey(CodegenConstants.DISALLOW_ADDITIONAL_PROPERTIES_IF_NOT_PRESENT)) { @@ -887,13 +916,15 @@ public class PowerShellClientCodegen extends DefaultCodegen implements CodegenCo // model name cannot use reserved keyword, e.g. return if (isReservedWord(name)) { - LOGGER.warn(name + " (reserved word or special variable name) cannot be used as model name. Renamed to " + camelize("model_" + name)); + LOGGER.warn("{} (reserved word or special variable name) cannot be used as model name. Renamed to {}", + name, camelize("model_" + name)); name = camelize("model_" + name); // e.g. return => ModelReturn (after camelize) } // model name starts with number if (name.matches("^\\d.*")) { - LOGGER.warn(name + " (model name starts with number) cannot be used as model name. Renamed to " + camelize("model_" + name)); + LOGGER.warn("{} (model name starts with number) cannot be used as model name. Renamed to {}", name, + camelize("model_" + name)); name = camelize("model_" + name); // e.g. 200Response => Model200Response (after camelize) } @@ -969,7 +1000,8 @@ public class PowerShellClientCodegen extends DefaultCodegen implements CodegenCo // for param name reserved word or word starting with number, append _ if (paramNameReservedWords.contains(name) || name.matches("^\\d.*")) { - LOGGER.warn(name + " (reserved word or special variable name) cannot be used in naming. Renamed to " + escapeReservedWord(name)); + LOGGER.warn("{} (reserved word or special variable name) cannot be used in naming. Renamed to {}", name, + escapeReservedWord(name)); name = escapeReservedWord(name); } @@ -993,11 +1025,22 @@ public class PowerShellClientCodegen extends DefaultCodegen implements CodegenCo int index = 0; for (CodegenParameter p : op.allParams) { p.vendorExtensions.put("x-powershell-data-type", getPSDataType(p)); - p.vendorExtensions.put("x-powershell-example", constructExampleCode(p, modelMaps, processedModelMaps)); + p.vendorExtensions.put("x-powershell-example", constructExampleCode(p, modelMaps, processedModelMaps, false)); + + if (p.required) { + // clear processed Models after each constructed API Operation full example. + processedModelMaps.clear(); + + p.vendorExtensions.put("x-powershell-example-required", constructExampleCode(p, modelMaps, processedModelMaps, true)); + } + p.vendorExtensions.put("x-index", index); index++; } + // clear processed Models after each constructed API Operation examples. + processedModelMaps.clear(); + if (!op.vendorExtensions.containsKey("x-powershell-method-name")) { // x-powershell-method-name not set String methodName = toMethodName(op.operationId); op.vendorExtensions.put("x-powershell-method-name", methodName); @@ -1018,13 +1061,6 @@ public class PowerShellClientCodegen extends DefaultCodegen implements CodegenCo } } - processedModelMaps.clear(); - for (CodegenOperation operation : operationList) { - for (CodegenParameter cp : operation.allParams) { - cp.vendorExtensions.put("x-powershell-example", constructExampleCode(cp, modelMaps, processedModelMaps)); - } - } - // check if return type is oneOf/anyeOf model for (CodegenOperation op : operationList) { if (op.returnType != null) { @@ -1100,133 +1136,267 @@ public class PowerShellClientCodegen extends DefaultCodegen implements CodegenCo // for reserved word or word starting with number, append _ if (isReservedWord(name) || name.matches("^\\d.*")) { - LOGGER.warn(name + " (reserved word or special variable name) cannot be used in naming. Renamed to " + escapeReservedWord(name)); + LOGGER.warn("{} (reserved word or special variable name) cannot be used in naming. Renamed to {}", name, + escapeReservedWord(name)); name = escapeReservedWord(name); } return name; } - private String constructExampleCode(CodegenParameter codegenParameter, HashMap modelMaps, HashMap processedModelMap) { - if (codegenParameter.isArray) { // array - return "@(" + constructExampleCode(codegenParameter.items, modelMaps, processedModelMap) + ")"; - } else if (codegenParameter.isMap) { // TODO: map, file type - return "@{ \"Key\" = \"Value\" }"; - } else if (languageSpecificPrimitives.contains(codegenParameter.dataType) || - nullablePrimitives.contains(codegenParameter.dataType)) { // primitive type - if ("String".equals(codegenParameter.dataType) || "Character".equals(codegenParameter.dataType)) { - if (StringUtils.isEmpty(codegenParameter.example)) { - return "\"" + codegenParameter.example + "\""; - } else { - if (Boolean.TRUE.equals(codegenParameter.isEnum)) { // enum - List enumValues = (List) codegenParameter.allowableValues.get("values"); - return "\"" + String.valueOf(enumValues.get(0)) + "\""; - } else { - return "\"" + codegenParameter.paramName + "_example\""; - } - } - } else if ("Boolean".equals(codegenParameter.dataType) || - "System.Nullable[Boolean]".equals(codegenParameter.dataType)) { // boolean - if (Boolean.parseBoolean(codegenParameter.example)) { - return "true"; - } else { - return "false"; - } - } else if ("URL".equals(codegenParameter.dataType)) { // URL - return "URL(string: \"https://example.com\")!"; - } else if ("System.DateTime".equals(codegenParameter.dataType)) { // datetime or date - return "Get-Date"; - } else { // numeric - if (StringUtils.isEmpty(codegenParameter.example)) { - return codegenParameter.example; - } else { - return "987"; - } + private String constructExampleCode(CodegenParameter codegenParameter, HashMap modelMaps, HashMap processedModelMap, boolean requiredOnly) { + StringBuilder example = new StringBuilder(); + + if (codegenParameter.isString) { + if (codegenParameter.isEnum || (codegenParameter.allowableValues != null && !codegenParameter.allowableValues.isEmpty())) { + example.append(constructEnumExample(codegenParameter.allowableValues)); + } else { + String genericStringExample = codegenParameter.paramName + "_example"; + example.append(constructStringExample(codegenParameter.paramName, codegenParameter.example, genericStringExample)); } - } else { // model - // look up the model + } else if (codegenParameter.isBoolean) { + example.append(constructBooleanExample(codegenParameter.example)); + } else if (codegenParameter.isDate || codegenParameter.isDateTime) { + example.append("(Get-Date)"); + } else if (codegenParameter.isArray) { + if (codegenParameter.items.isModel || (modelMaps.containsKey(codegenParameter.items.dataType) && codegenParameter.items.allowableValues == null)) { + String modelExample; + if (codegenParameter.items.isModel) { + modelExample = constructExampleCode(codegenParameter.items, modelMaps, processedModelMap, requiredOnly); + } else { + modelExample = constructExampleCode(modelMaps.get(codegenParameter.items.dataType), modelMaps, processedModelMap, requiredOnly); + } + + if (!StringUtils.isEmpty(modelExample)) { + example.append(modelExample); + } + } else if (codegenParameter.items.isString) { + if (codegenParameter.items.isEnum || (codegenParameter.items.allowableValues != null && !codegenParameter.items.allowableValues.isEmpty())) { + example.append(constructEnumExample(codegenParameter.items.allowableValues)); + } else { + String genericStringExample = codegenParameter.items.name + "_example"; + example.append(constructStringExample(codegenParameter.paramName, codegenParameter.items.example, genericStringExample)); + } + } else { + example.append(constructExampleCode(codegenParameter.items, modelMaps, processedModelMap, requiredOnly)); + } + } else if (codegenParameter.isMap) { + if (codegenParameter.items.isModel) { + String modelExample = constructExampleCode(codegenParameter.items, modelMaps, processedModelMap, requiredOnly); + if (!StringUtils.isEmpty(modelExample)) { + example.append(modelExample + "\n"); + } + + example.append("$" + codegenParameter.paramName + " = @{ key_example = $" + codegenParameter.items.dataType + " }"); + } else { + example.append("@{ key_example = "); + example.append(constructExampleCode(codegenParameter.items, modelMaps, processedModelMap, requiredOnly)); + example.append(" }"); + } + } else if (codegenParameter.isEnum || (codegenParameter.allowableValues != null && !codegenParameter.allowableValues.isEmpty())) { + example.append(constructEnumExample(codegenParameter.allowableValues)); + } else if (codegenParameter.isModel) { if (modelMaps.containsKey(codegenParameter.dataType)) { - return constructExampleCode(modelMaps.get(codegenParameter.dataType), modelMaps, processedModelMap); - } else { - //LOGGER.error("Error in constructing examples. Failed to look up the model " + codegenParameter.dataType); - return "TODO"; + String modelExample = constructExampleCode(modelMaps.get(codegenParameter.dataType), modelMaps, processedModelMap, requiredOnly); + if (!StringUtils.isEmpty(modelExample)) { + example.append(modelExample); + } } + } else if ((languageSpecificPrimitives.contains(codegenParameter.dataType) || nullablePrimitives.contains(codegenParameter.dataType)) && !codegenParameter.isFile) { + // If the data type is primitive and it is not a String, Enum, Boolean, File, Date or DateTime, then it's a number. + example.append(constructNumericExample(codegenParameter.example)); } + + // Replace multiple new lines with a single new line and trim leading and trailing spaces. + return example.toString().replaceAll("[\n]{2,}", "\n\n").trim(); } - private String constructExampleCode(CodegenProperty codegenProperty, HashMap modelMaps, HashMap processedModelMap) { - if (codegenProperty.isArray) { // array - return "@(" + constructExampleCode(codegenProperty.items, modelMaps, processedModelMap) + ")"; - } else if (codegenProperty.isMap) { // map - return "\"TODO\""; - } else if (languageSpecificPrimitives.contains(codegenProperty.dataType) || // primitive type - nullablePrimitives.contains(codegenProperty.dataType)) { // nullable primitive type - if ("String".equals(codegenProperty.dataType)) { - if (StringUtils.isEmpty(codegenProperty.example)) { - return "\"" + codegenProperty.example + "\""; - } else { - if (Boolean.TRUE.equals(codegenProperty.isEnum)) { // enum - List enumValues = (List) codegenProperty.allowableValues.get("values"); - return "\"" + String.valueOf(enumValues.get(0)) + "\""; - } else { - return "\"" + codegenProperty.name + "_example\""; - } - } - } else if ("Boolean".equals(codegenProperty.dataType) || - "System.Nullable[Boolean]".equals(codegenProperty.dataType)) { // boolean - if (Boolean.parseBoolean(codegenProperty.example)) { - return "$true"; - } else { - return "$false"; - } - } else if ("URL".equals(codegenProperty.dataType)) { // URL - return "URL(string: \"https://example.com\")!"; - } else if ("System.DateTime".equals(codegenProperty.dataType)) { // datetime or date - return "Get-Date"; - } else { // numeric - if (StringUtils.isEmpty(codegenProperty.example)) { - return codegenProperty.example; - } else { - return "123"; - } + private String constructExampleCode(CodegenProperty codegenProperty, HashMap modelMaps, HashMap processedModelMap, boolean requiredOnly) { + StringBuilder example = new StringBuilder(); + + if (codegenProperty.isString) { + if (codegenProperty.isEnum || (codegenProperty.allowableValues != null && !codegenProperty.allowableValues.isEmpty())) { + example.append(constructEnumExample(codegenProperty.allowableValues)); + } else { + String genericStringExample = codegenProperty.name + "_example"; + example.append(constructStringExample(codegenProperty.name, codegenProperty.example, genericStringExample)); } - } else { - // look up the model + } else if (codegenProperty.isBoolean) { + example.append(constructBooleanExample(codegenProperty.example)); + } else if (codegenProperty.isDate || codegenProperty.isDateTime) { + example.append("(Get-Date)"); + } else if (codegenProperty.isArray) { + example.append(constructExampleCode(codegenProperty.items, modelMaps, processedModelMap, requiredOnly)); + } else if (codegenProperty.isMap) { + example.append("@{ key_example = "); + example.append(constructExampleCode(codegenProperty.items, modelMaps, processedModelMap, requiredOnly)); + example.append(" }"); + } else if (codegenProperty.isEnum || (codegenProperty.allowableValues != null && !codegenProperty.allowableValues.isEmpty())) { + example.append(constructEnumExample(codegenProperty.allowableValues)); + } else if (codegenProperty.isModel) { if (modelMaps.containsKey(codegenProperty.dataType)) { - return constructExampleCode(modelMaps.get(codegenProperty.dataType), modelMaps, processedModelMap); - } else { - //LOGGER.error("Error in constructing examples. Failed to look up the model " + codegenProperty.dataType); - return "\"TODO\""; + String modelExample = constructExampleCode(modelMaps.get(codegenProperty.dataType), modelMaps, processedModelMap, requiredOnly); + if (!StringUtils.isEmpty(modelExample)) { + example.append(modelExample); + } } + } else if ((languageSpecificPrimitives.contains(codegenProperty.dataType) || nullablePrimitives.contains(codegenProperty.dataType)) && !codegenProperty.isFile) { + // If the data type is primitive and it is not a String, Enum, Boolean, File, Date or DateTime, then it's a number. + example.append(constructNumericExample(codegenProperty.example)); } + + return example.toString(); } - private String constructExampleCode(CodegenModel codegenModel, HashMap modelMaps, HashMap processedModelMap) { - String example; + private String constructExampleCode(CodegenModel codegenModel, HashMap modelMaps, HashMap processedModelMap, boolean requiredOnly) { + StringBuilder example = new StringBuilder(); + Boolean hasModelProperty = false; - // break infinite recursion. Return, in case a model is already processed in the current context. + // This behaviour is needed to break infinite recursion. Return, in case a model is already processed in the current context. String model = codegenModel.name; if (processedModelMap.containsKey(model)) { - int count = processedModelMap.get(model); - if (count == 1) { - processedModelMap.put(model, 2); - } else if (count == 2) { - return ""; - } else { - throw new RuntimeException("Invalid count when constructing example: " + count); - } + return ""; } else { processedModelMap.put(model, 1); } - example = "(Initialize-" + codegenModel.name + " "; List propertyExamples = new ArrayList<>(); for (CodegenProperty codegenProperty : codegenModel.allVars) { - propertyExamples.add("-" + codegenProperty.name + " " + constructExampleCode(codegenProperty, modelMaps, processedModelMap)); + if ( + !hasModelProperty && ( + codegenProperty.isModel || + (codegenProperty.isArray && (codegenProperty.items.isModel || (modelMaps.containsKey(codegenProperty.items.dataType) && codegenProperty.items.allowableValues == null))) || + (codegenProperty.isMap && codegenProperty.items.isModel)) + ) { + example.append("\n"); + hasModelProperty = true; + } + + if (requiredOnly && !codegenProperty.required) { + continue; + } + + if (codegenProperty.isModel) { + String modelExample = constructExampleCode(codegenProperty, modelMaps, processedModelMap, requiredOnly); + if (!StringUtils.isEmpty(modelExample)) { + example.append(modelExample + "\n"); + } + + propertyExamples.add("-" + codegenProperty.name + " " + "$" + codegenProperty.dataType); + } else if (codegenProperty.isArray && (codegenProperty.items.isModel || (modelMaps.containsKey(codegenProperty.items.dataType) && codegenProperty.items.allowableValues == null))) { + String modelExample; + if (codegenProperty.items.isModel) { + modelExample = constructExampleCode(codegenProperty.items, modelMaps, processedModelMap, requiredOnly); + } else { + modelExample = constructExampleCode(modelMaps.get(codegenProperty.items.dataType), modelMaps, processedModelMap, requiredOnly); + } + + if (!StringUtils.isEmpty(modelExample)) { + example.append(modelExample + "\n"); + } + + propertyExamples.add("-" + codegenProperty.name + " " + "$" + codegenProperty.complexType); + } else if (codegenProperty.isArray && codegenProperty.items.isString) { + if (codegenProperty.items.isEnum || (codegenProperty.items.allowableValues != null && !codegenProperty.items.allowableValues.isEmpty())) { + example.append(constructEnumExample(codegenProperty.items.allowableValues)); + propertyExamples.add("-" + codegenProperty.name + " " + example.toString()); + } else { + StringBuilder stringArrayPropertyValue = new StringBuilder(); + String genericStringExample = codegenProperty.items.name + "_example"; + + stringArrayPropertyValue.append(constructStringExample(codegenProperty.name, codegenProperty.items.example, genericStringExample)); + + propertyExamples.add("-" + codegenProperty.name + " " + stringArrayPropertyValue.toString()); + } + } else if (codegenProperty.isMap && codegenProperty.items.isModel) { + String modelExample = constructExampleCode(codegenProperty.items, modelMaps, processedModelMap, requiredOnly); + if (!StringUtils.isEmpty(modelExample)) { + example.append(modelExample + "\n"); + } + + propertyExamples.add("-" + codegenProperty.name + " " + "@{ key_example = " + "$" + codegenProperty.complexType + " }"); + } else { + propertyExamples.add("-" + codegenProperty.name + " " + constructExampleCode(codegenProperty, modelMaps, processedModelMap, requiredOnly)); + } } - example += StringUtils.join(propertyExamples, " "); - example += ")"; - return example; + + example.append("$"); + if (this.useClassNameInModelsExamples) { + example.append(codegenModel.classname); + } else { + example.append(codegenModel.name); + } + example.append(" = " + this.modelsCmdletVerb + "-"); + if (this.useClassNameInModelsExamples) { + example.append(codegenModel.classname); + } else { + example.append(codegenModel.name); + } + example.append(" "); + + example.append(StringUtils.join(propertyExamples, " ")); + + if (hasModelProperty) { + example.append("\n"); + } + + return example.toString(); + } + + private String constructStringExample(String codegenName, String codegenExample, String genericStringExample) { + StringBuilder example = new StringBuilder(); + example.append("\""); + + if ( + StringUtils.isEmpty(codegenExample) || + codegenExample.equals("null") || + codegenExample.equals(genericStringExample) + ) { + example.append("My" + codegenName); + } else { + example.append(codegenExample); + } + + example.append("\""); + + return example.toString(); + } + + private String constructEnumExample(Map allowableValues) { + StringBuilder example = new StringBuilder(); + + example.append("\""); + + List enumValues = (List) allowableValues.get("values"); + example.append(String.valueOf(enumValues.get(0))); + + example.append("\""); + + return example.toString(); + } + + private String constructNumericExample(String codegenExample) { + StringBuilder example = new StringBuilder(); + + if (StringUtils.isEmpty(codegenExample) || codegenExample.equals("null")) { + example.append("0"); + } else { + example.append(codegenExample); + } + + return example.toString(); + } + + private String constructBooleanExample(String codegenExample) { + StringBuilder example = new StringBuilder(); + + if (Boolean.parseBoolean(codegenExample)) { + example.append("$true"); + } else { + example.append("$false"); + } + + return example.toString(); } private String getPSDataType(CodegenProperty cp) { @@ -1310,7 +1480,7 @@ public class PowerShellClientCodegen extends DefaultCodegen implements CodegenCo if (exitValue != 0) { LOGGER.error("Error running the command ({}). Exit value: {}", command, exitValue); } else { - LOGGER.info("Successfully executed: " + command); + LOGGER.info("Successfully executed: {}", command); } } catch (InterruptedException | IOException e) { LOGGER.error("Error running the command ({}). Exception: {}", command, e.getMessage()); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ProtobufSchemaCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ProtobufSchemaCodegen.java index e7bc5b46ef5..02a01627dd6 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ProtobufSchemaCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ProtobufSchemaCodegen.java @@ -176,7 +176,7 @@ public class ProtobufSchemaCodegen extends DefaultCodegen implements CodegenConf // method name cannot use reserved keyword, e.g. return if (isReservedWord(operationId)) { - LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + camelize(sanitizeName("call_" + operationId))); + LOGGER.warn("{} (reserved word) cannot be used as method name. Renamed to {}", operationId, camelize(sanitizeName("call_" + operationId))); operationId = "call_" + operationId; } @@ -390,13 +390,14 @@ public class ProtobufSchemaCodegen extends DefaultCodegen implements CodegenConf // model name cannot use reserved keyword, e.g. return if (isReservedWord(name)) { - LOGGER.warn(name + " (reserved word) cannot be used as model name. Renamed to " + camelize("model_" + name)); + LOGGER.warn("{} (reserved word) cannot be used as model name. Renamed to {}", name, camelize("model_" + name)); name = "model_" + name; // e.g. return => ModelReturn (after camelize) } // model name starts with number if (name.matches("^\\d.*")) { - LOGGER.warn(name + " (model name starts with number) cannot be used as model name. Renamed to " + camelize("model_" + name)); + LOGGER.warn("{} (model name starts with number) cannot be used as model name. Renamed to {}", name, + camelize("model_" + name)); name = "model_" + name; // e.g. 200Response => Model200Response (after camelize) } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PythonClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PythonClientCodegen.java index a00683cbd4a..5612b1d7b0e 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PythonClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PythonClientCodegen.java @@ -163,7 +163,9 @@ public class PythonClientCodegen extends PythonLegacyClientCodegen { // default this to true so the python ModelSimple models will be generated ModelUtils.setGenerateAliasAsModel(true); - LOGGER.info(CodegenConstants.GENERATE_ALIAS_AS_MODEL + " is hard coded to true in this generator. Alias models will only be generated if they contain validations or enums"); + LOGGER.info( + "{} is hard coded to true in this generator. Alias models will only be generated if they contain validations or enums", + CodegenConstants.GENERATE_ALIAS_AS_MODEL); Boolean attrNoneIfUnset = false; if (additionalProperties.containsKey(CodegenConstants.PYTHON_ATTR_NONE_IF_UNSET)) { @@ -1106,7 +1108,7 @@ public class PythonClientCodegen extends PythonLegacyClientCodegen { String ref = ModelUtils.getSimpleRef(schema.get$ref()); Schema refSchema = allDefinitions.get(ref); if (null == refSchema) { - LOGGER.warn("Unable to find referenced schema " + schema.get$ref() + "\n"); + LOGGER.warn("Unable to find referenced schema {}\n", schema.get$ref()); return fullPrefix + "None" + closeChars; } String refModelName = getModelName(schema); @@ -1307,7 +1309,7 @@ public class PythonClientCodegen extends PythonLegacyClientCodegen { } return fullPrefix + closeChars; } else { - LOGGER.warn("Type " + schema.getType() + " not handled properly in toExampleValue"); + LOGGER.warn("Type {} not handled properly in toExampleValue", schema.getType()); } return example; diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PythonFastAPIServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PythonFastAPIServerCodegen.java new file mode 100644 index 00000000000..6ee1131973e --- /dev/null +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PythonFastAPIServerCodegen.java @@ -0,0 +1,297 @@ +/* + * 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.languages; + +import com.fasterxml.jackson.core.JsonGenerator; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.JsonSerializer; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializerProvider; +import com.fasterxml.jackson.databind.module.SimpleModule; +import io.swagger.v3.oas.models.media.ArraySchema; +import io.swagger.v3.oas.models.media.Schema; +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.*; +import org.openapitools.codegen.utils.ModelUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.File; +import java.io.IOException; +import java.util.*; + +import static org.openapitools.codegen.utils.StringUtils.underscore; + +public class PythonFastAPIServerCodegen extends AbstractPythonCodegen { + private static class SnakeCaseKeySerializer extends JsonSerializer { + @Override + public void serialize(String value, JsonGenerator gen, SerializerProvider serializers) throws IOException { + gen.writeFieldName(underscore(value)); + } + } + + private static class PythonBooleanSerializer extends JsonSerializer { + @Override + public void serialize(Boolean value, JsonGenerator gen, SerializerProvider serializers) throws IOException { + gen.writeNumber(value ? 1 : 0); + } + } + + // An object mapper that is used to convert an example string to + // a "python-compliant" example string (keys in snake case, boolean as 1/0). + final ObjectMapper MAPPER = new ObjectMapper(); + + final Logger LOGGER = LoggerFactory.getLogger(PythonFastAPIServerCodegen.class); + + private static final String NAME = "python-fastapi"; + private static final int DEFAULT_SERVER_PORT = 8080; + private static final String DEFAULT_PACKAGE_NAME = "openapi_server"; + private static final String SRC_DIR = "src"; + + @Override + public CodegenType getTag() { + return CodegenType.SERVER; + } + + @Override + public String getHelp() { + return "Generates a Python FastAPI server (beta)."; + } + + public PythonFastAPIServerCodegen() { + super(); + + generatorMetadata = GeneratorMetadata.newBuilder(generatorMetadata) + .stability(Stability.BETA) + .build(); + + SimpleModule simpleModule = new SimpleModule(); + simpleModule.addKeySerializer(String.class, new SnakeCaseKeySerializer()); + simpleModule.addSerializer(Boolean.class, new PythonBooleanSerializer()); + MAPPER.registerModule(simpleModule); + + /* + * Additional Properties. These values can be passed to the templates and + * are available in models, apis, and supporting files + */ + additionalProperties.put("serverPort", DEFAULT_SERVER_PORT); + additionalProperties.put(CodegenConstants.PACKAGE_NAME, DEFAULT_PACKAGE_NAME); + + languageSpecificPrimitives.add("List"); + languageSpecificPrimitives.add("Dict"); + typeMapping.put("array", "List"); + typeMapping.put("map", "Dict"); + + outputFolder = "generated-code" + File.separator + NAME; + modelTemplateFiles.put("model.mustache", ".py"); + apiTemplateFiles.put("api.mustache", ".py"); + embeddedTemplateDir = templateDir = NAME; + apiPackage = "apis"; + modelPackage = "models"; + testPackage = "tests"; + apiTestTemplateFiles().put("api_test.mustache", ".py"); + + cliOptions.add(new CliOption(CodegenConstants.PACKAGE_NAME, "python package name (convention: snake_case).") + .defaultValue(DEFAULT_PACKAGE_NAME)); + cliOptions.add(new CliOption(CodegenConstants.PACKAGE_VERSION, "python package version.") + .defaultValue("1.0.0")); + cliOptions.add(new CliOption("serverPort", "TCP port to listen to in app.run"). + defaultValue(String.valueOf(DEFAULT_SERVER_PORT))); + } + + @Override + public void processOpts() { + super.processOpts(); + + if (additionalProperties.containsKey(CodegenConstants.PACKAGE_NAME)) { + setPackageName((String) additionalProperties.get(CodegenConstants.PACKAGE_NAME)); + } + + modelPackage = packageName + "." + modelPackage; + apiPackage = packageName + "." + apiPackage; + + supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); + supportingFiles.add(new SupportingFile("openapi.mustache", "", "openapi.yaml")); + supportingFiles.add(new SupportingFile("main.mustache", SRC_DIR + File.separator + packageName.replace('.', File.separatorChar), "main.py")); + supportingFiles.add(new SupportingFile("docker-compose.mustache", "", "docker-compose.yaml")); + supportingFiles.add(new SupportingFile("Dockerfile.mustache", "", "Dockerfile")); + supportingFiles.add(new SupportingFile("requirements.mustache", "", "requirements.txt")); + supportingFiles.add(new SupportingFile("security_api.mustache", SRC_DIR + File.separator + packageName.replace('.', File.separatorChar), "security_api.py")); + supportingFiles.add(new SupportingFile("extra_models.mustache", StringUtils.substringAfter(modelFileFolder(), outputFolder), "extra_models.py")); + + // Add __init__.py to all sub-folders under namespace pkg + StringBuilder namespacePackagePath = new StringBuilder(SRC_DIR + File.separator + StringUtils.substringBefore(packageName, ".")); + for (String tmp : StringUtils.split(StringUtils.substringAfter(packageName, "."), '.')) { + namespacePackagePath.append(File.separator).append(tmp); + supportingFiles.add(new SupportingFile("__init__.mustache", namespacePackagePath.toString(), "__init__.py")); + } + supportingFiles.add(new SupportingFile("__init__.mustache", StringUtils.substringAfter(modelFileFolder(), outputFolder), "__init__.py")); + supportingFiles.add(new SupportingFile("__init__.mustache", StringUtils.substringAfter(apiFileFolder(), outputFolder), "__init__.py")); + + supportingFiles.add(new SupportingFile("conftest.mustache", testPackage.replace('.', File.separatorChar), "conftest.py")); + + supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore")); + supportingFiles.add(new SupportingFile("pyproject_toml.mustache", "", "pyproject.toml")); + supportingFiles.add(new SupportingFile("setup_cfg.mustache", "", "setup.cfg")); + supportingFiles.add(new SupportingFile(".flake8.mustache", "", ".flake8")); + } + + @Override + public String getName() { + return NAME; + } + + @Override + public String toModelImport(String name) { + String modelImport; + if (StringUtils.startsWithAny(name, "import", "from")) { + modelImport = name; + } else { + modelImport = "from "; + if (!"".equals(modelPackage())) { + modelImport += modelPackage() + "."; + } + modelImport += toModelFilename(name) + " import " + name; + } + return modelImport; + } + + @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 = getAdditionalProperties(p); + return getSchemaType(p) + "[str, " + getTypeDeclaration(inner) + "]"; + } + return super.getTypeDeclaration(p); + } + + @Override + public Map postProcessOperationsWithModels(Map objs, List allModels) { + Map operations = (Map) objs.get("operations"); + // Set will make sure that no duplicated items are used. + Set securityImports = new HashSet<>(); + if (operations != null) { + List ops = (List) operations.get("operation"); + for (final CodegenOperation operation : ops) { + List responses = operation.responses; + if (responses != null) { + for (final CodegenResponse resp : responses) { + // Convert "default" value (0) to OK (200). + if ("0".equals(resp.code)) { + resp.code = "200"; + } + } + } + List securityMethods = operation.authMethods; + if (securityMethods != null) { + for (final CodegenSecurity securityMethod : securityMethods) { + securityImports.add(securityMethod.name); + } + } + + if (operation.requestBodyExamples != null) { + for (Map example : operation.requestBodyExamples) { + if (example.get("contentType") != null && example.get("contentType").equals("application/json")) { + // Make an example dictionary more python-like (snake-case, etc.). + // If fails, use the original string. + try { + Map result = MAPPER.readValue(example.get("example"), + new TypeReference>() { + }); + operation.bodyParam.example = MAPPER.writeValueAsString(result); + } catch (IOException e) { + operation.bodyParam.example = example.get("example"); + } + } + } + } + } + } + + objs.put("securityImports", new ArrayList(securityImports)); + + return objs; + } + + @Override + public Map postProcessAllModels(Map objs) { + Map result = super.postProcessAllModels(objs); + for (Map.Entry entry : result.entrySet()) { + Map inner = (Map) entry.getValue(); + List> models = (List>) inner.get("models"); + for (Map mo : models) { + CodegenModel cm = (CodegenModel) mo.get("model"); + // Add additional filename information for imports + mo.put("pyImports", toPyImports(cm, cm.imports)); + } + } + return result; + } + + private List> toPyImports(CodegenModel cm, Set imports) { + List> pyImports = new ArrayList<>(); + for (String im : imports) { + if (!im.equals(cm.classname)) { + HashMap pyImport = new HashMap<>(); + pyImport.put("import", toModelImport(im)); + pyImports.add(pyImport); + } + } + return pyImports; + } + + @Override + public Map postProcessSupportingFileData(Map objs) { + generateYAMLSpecFile(objs); + return objs; + } + + @Override + public String apiFileFolder() { + return outputFolder + File.separator + SRC_DIR + File.separator + apiPackage().replace('.', File.separatorChar); + } + + @Override + public String modelFileFolder() { + return outputFolder + File.separator + SRC_DIR + File.separator + modelPackage().replace('.', File.separatorChar); + } + + @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 Nikita Vakula (https://github.com/krjakbrjak)#"); + System.out.println("# Please support his work directly via https://paypal.me/krjakbrjak \uD83D\uDE4F #"); + System.out.println("################################################################################"); + } + + @Override + public String toRegularExpression(String pattern) { + String regex = super.toRegularExpression(pattern); + return StringUtils.substring(regex, 1, -1); + } +} diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RClientCodegen.java index df86492ffbd..5b34726bcbe 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RClientCodegen.java @@ -306,13 +306,14 @@ public class RClientCodegen extends DefaultCodegen implements CodegenConfig { // model name cannot use reserved keyword, e.g. return if (isReservedWord(name)) { - LOGGER.warn(name + " (reserved word) cannot be used as model name. Renamed to " + camelize("model_" + name)); + LOGGER.warn("{} (reserved word) cannot be used as model name. Renamed to {}", name, camelize("model_" + name)); name = "model_" + name; // e.g. return => ModelReturn (after camelize) } // model name starts with number if (name.matches("^\\d.*")) { - LOGGER.warn(name + " (model name starts with number) cannot be used as model name. Renamed to " + camelize("model_" + name)); + LOGGER.warn("{} (model name starts with number) cannot be used as model name. Renamed to {}", name, + camelize("model_" + name)); name = "model_" + name; // e.g. 200Response => Model200Response (after camelize) } @@ -402,7 +403,7 @@ public class RClientCodegen extends DefaultCodegen implements CodegenConfig { // method name cannot use reserved keyword, e.g. return if (isReservedWord(sanitizedOperationId)) { - LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + underscore("call_" + operationId)); + LOGGER.warn("{} (reserved word) cannot be used as method name. Renamed to {}", operationId, underscore("call_" + operationId)); sanitizedOperationId = "call_" + sanitizedOperationId; } @@ -706,7 +707,7 @@ public class RClientCodegen extends DefaultCodegen implements CodegenConfig { public String constructExampleCode(CodegenParameter codegenParameter, HashMap modelMaps) { if (codegenParameter.isArray) { // array - return "list(" + constructExampleCode(codegenParameter.items, modelMaps) + ")"; + return "list(" + constructExampleCode(codegenParameter.items, modelMaps, 0) + ")"; } else if (codegenParameter.isMap) { // TODO: map return "TODO"; } else if (languageSpecificPrimitives.contains(codegenParameter.dataType)) { // primitive type @@ -714,17 +715,20 @@ public class RClientCodegen extends DefaultCodegen implements CodegenConfig { } else { // model // look up the model if (modelMaps.containsKey(codegenParameter.dataType)) { - return constructExampleCode(modelMaps.get(codegenParameter.dataType), modelMaps); + return constructExampleCode(modelMaps.get(codegenParameter.dataType), modelMaps, 0); } else { - LOGGER.error("Error in constructing examples. Failed to look up the model " + codegenParameter.dataType); + LOGGER.error("Error in constructing examples. Failed to look up the model {}", codegenParameter.dataType); return "TODO"; } } } - public String constructExampleCode(CodegenProperty codegenProperty, HashMap modelMaps) { + public String constructExampleCode(CodegenProperty codegenProperty, HashMap modelMaps, int depth) { + if (depth > 10) return "..."; + depth++; + if (codegenProperty.isArray) { // array - return "list(" + constructExampleCode(codegenProperty.items, modelMaps) + ")"; + return "list(" + constructExampleCode(codegenProperty.items, modelMaps, depth) + ")"; } else if (codegenProperty.isMap) { // TODO: map return "TODO"; } else if (languageSpecificPrimitives.contains(codegenProperty.dataType)) { // primitive type @@ -748,26 +752,29 @@ public class RClientCodegen extends DefaultCodegen implements CodegenConfig { } else { // look up the model if (modelMaps.containsKey(codegenProperty.dataType)) { - return constructExampleCode(modelMaps.get(codegenProperty.dataType), modelMaps); + return constructExampleCode(modelMaps.get(codegenProperty.dataType), modelMaps, depth); } else { - LOGGER.error("Error in constructing examples. Failed to look up the model " + codegenProperty.dataType); + LOGGER.error("Error in constructing examples. Failed to look up the model {}", codegenProperty.dataType); return "TODO"; } } } - public String constructExampleCode(CodegenModel codegenModel, HashMap modelMaps) { + public String constructExampleCode(CodegenModel codegenModel, HashMap modelMaps, int depth) { + if (depth > 10) return "..."; + depth++; + String example; example = codegenModel.name + "$new("; List propertyExamples = new ArrayList<>(); // required properties first for (CodegenProperty codegenProperty : codegenModel.requiredVars) { - propertyExamples.add(constructExampleCode(codegenProperty, modelMaps)); + propertyExamples.add(constructExampleCode(codegenProperty, modelMaps, depth)); } // optional properties second for (CodegenProperty codegenProperty : codegenModel.optionalVars) { - propertyExamples.add(constructExampleCode(codegenProperty, modelMaps)); + propertyExamples.add(constructExampleCode(codegenProperty, modelMaps, depth)); } example += StringUtils.join(propertyExamples, ", "); 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 96a5f5d7c3f..23f8fcd7cf5 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 @@ -376,13 +376,14 @@ public class RubyClientCodegen extends AbstractRubyCodegen { // model name cannot use reserved keyword, e.g. return if (isReservedWord(modelName)) { modelName = camelize("Model" + modelName); - LOGGER.warn(name + " (reserved word) cannot be used as model name. Renamed to " + modelName); + LOGGER.warn("{} (reserved word) cannot be used as model name. Renamed to {}", name, modelName); return modelName; } // model name starts with number if (modelName.matches("^\\d.*")) { - LOGGER.warn(modelName + " (model name starts with number) cannot be used as model name. Renamed to " + camelize("model_" + modelName)); + LOGGER.warn("{} (model name starts with number) cannot be used as model name. Renamed to {}", modelName, + camelize("model_" + modelName)); modelName = "model_" + modelName; // e.g. 200Response => Model200Response (after camelize) } @@ -495,20 +496,20 @@ public class RubyClientCodegen extends AbstractRubyCodegen { // rename to empty_method_name_1 (e.g.) if method name is empty if (StringUtils.isEmpty(operationId)) { operationId = underscore("empty_method_name_" + emptyMethodNameCounter++); - LOGGER.warn("Empty method name (operationId) found. Renamed to " + operationId); + LOGGER.warn("Empty method name (operationId) found. Renamed to {}", operationId); return operationId; } // method name cannot use reserved keyword, e.g. return if (isReservedWord(operationId)) { String newOperationId = underscore("call_" + operationId); - LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + newOperationId); + LOGGER.warn("{} (reserved word) cannot be used as method name. Renamed to {}", operationId, newOperationId); return newOperationId; } // operationId starts with a number if (operationId.matches("^\\d.*")) { - LOGGER.warn(operationId + " (starting with a number) cannot be used as method name. Renamed to " + underscore(sanitizeName("call_" + operationId))); + LOGGER.warn("{} (starting with a number) cannot be used as method name. Renamed to {}", operationId, underscore(sanitizeName("call_" + operationId))); operationId = "call_" + operationId; } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RubyOnRailsServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RubyOnRailsServerCodegen.java index 1cc82c8827b..adcb79dc2f9 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RubyOnRailsServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RubyOnRailsServerCodegen.java @@ -238,7 +238,7 @@ public class RubyOnRailsServerCodegen extends AbstractRubyCodegen { // model name cannot use reserved keyword, e.g. return if (isReservedWord(name)) { String modelName = camelize("Model" + name); - LOGGER.warn(name + " (reserved word) cannot be used as model name. Renamed to " + modelName); + LOGGER.warn("{} (reserved word) cannot be used as model name. Renamed to {}", name, modelName); return modelName; } @@ -252,7 +252,7 @@ public class RubyOnRailsServerCodegen extends AbstractRubyCodegen { // model name cannot use reserved keyword, e.g. return if (isReservedWord(name)) { String filename = underscore("model_" + name); - LOGGER.warn(name + " (reserved word) cannot be used as model filename. Renamed to " + filename); + LOGGER.warn("{} (reserved word) cannot be used as model filename. Renamed to {}", name, filename); return filename; } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RubySinatraServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RubySinatraServerCodegen.java index c81426eb017..1e51a349e0d 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RubySinatraServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RubySinatraServerCodegen.java @@ -132,7 +132,7 @@ public class RubySinatraServerCodegen extends AbstractRubyCodegen { public String toModelName(String name) { // model name cannot use reserved keyword, e.g. return if (isReservedWord(name)) { - LOGGER.warn(name + " (reserved word) cannot be used as model filename. Renamed to " + camelize("model_" + name)); + LOGGER.warn("{} (reserved word) cannot be used as model filename. Renamed to {}", name, camelize("model_" + name)); name = "model_" + name; // e.g. return => ModelReturn (after camelize) } @@ -145,7 +145,7 @@ public class RubySinatraServerCodegen extends AbstractRubyCodegen { public String toModelFilename(String name) { // model name cannot use reserved keyword, e.g. return if (isReservedWord(name)) { - LOGGER.warn(name + " (reserved word) cannot be used as model filename. Renamed to " + underscore("model_" + name)); + LOGGER.warn("{} (reserved word) cannot be used as model filename. Renamed to {}", name, underscore("model_" + name)); name = "model_" + name; // e.g. return => ModelReturn (after camelize) } 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 2aa6d625e03..2d9e445838b 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 @@ -406,13 +406,14 @@ public class RustClientCodegen extends DefaultCodegen implements CodegenConfig { // model name cannot use reserved keyword, e.g. return if (isReservedWord(name)) { - LOGGER.warn(name + " (reserved word) cannot be used as model name. Renamed to " + ("model_" + name)); + LOGGER.warn("{} (reserved word) cannot be used as model name. Renamed to {}", name, "model_" + name); name = "model_" + name; // e.g. return => ModelReturn (after camelize) } // model name starts with number if (name.matches("^\\d.*")) { - LOGGER.warn(name + " (model name starts with number) cannot be used as model name. Renamed to " + ("model_" + name)); + LOGGER.warn("{} (model name starts with number) cannot be used as model name. Renamed to {}", name, + "model_" + name); name = "model_" + name; // e.g. 200Response => Model200Response (after camelize) } @@ -454,14 +455,15 @@ public class RustClientCodegen extends DefaultCodegen implements CodegenConfig { ArraySchema ap = (ArraySchema) p; Schema inner = ap.getItems(); if (inner == null) { - LOGGER.warn(ap.getName() + "(array property) does not have a proper inner type defined.Default to string"); + LOGGER.warn("{}(array property) does not have a proper inner type defined.Default to string", + ap.getName()); inner = new StringSchema().description("TODO default missing array inner type to string"); } return "Vec<" + getTypeDeclaration(inner) + ">"; } else if (ModelUtils.isMapSchema(p)) { Schema inner = getAdditionalProperties(p); if (inner == null) { - LOGGER.warn(p.getName() + "(map property) does not have a proper inner type defined. Default to string"); + LOGGER.warn("{}(map property) does not have a proper inner type defined. Default to string", p.getName()); inner = new StringSchema().description("TODO default missing map inner type to string"); } return "::std::collections::HashMap"; @@ -502,7 +504,7 @@ public class RustClientCodegen extends DefaultCodegen implements CodegenConfig { // method name cannot use reserved keyword, e.g. return if (isReservedWord(sanitizedOperationId)) { - LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + StringUtils.underscore("call_" + operationId)); + LOGGER.warn("{} (reserved word) cannot be used as method name. Renamed to {}", operationId, StringUtils.underscore("call_" + operationId)); sanitizedOperationId = "call_" + sanitizedOperationId; } @@ -520,7 +522,7 @@ public class RustClientCodegen extends DefaultCodegen implements CodegenConfig { if (HYPER_LIBRARY.equals(getLibrary())) { operation.httpMethod = StringUtils.camelize(operation.httpMethod.toLowerCase(Locale.ROOT)); } else if (REQWEST_LIBRARY.equals(getLibrary())) { - operation.httpMethod = operation.httpMethod.toLowerCase(Locale.ROOT); + operation.httpMethod = operation.httpMethod.toUpperCase(Locale.ROOT); } // add support for single request parameter using x-group-parameters 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 a47e86573fb..e73361311a1 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 @@ -396,14 +396,15 @@ public class RustServerCodegen extends DefaultCodegen implements CodegenConfig { // model name cannot use reserved keyword, e.g. return if (isReservedWord(camelizedName)) { camelizedName = "Model" + camelizedName; - LOGGER.warn(camelizedName + " (reserved word) cannot be used as model name. Renamed to " + camelizedName); + LOGGER.warn("{} (reserved word) cannot be used as model name. Renamed to {}", camelizedName, camelizedName); } // model name starts with number else if (camelizedName.matches("^\\d.*")) { // e.g. 200Response => Model200Response (after camelize) camelizedName = "Model" + camelizedName; - LOGGER.warn(name + " (model name starts with number) cannot be used as model name. Renamed to " + camelizedName); + LOGGER.warn("{} (model name starts with number) cannot be used as model name. Renamed to {}", name, + camelizedName); } return camelizedName; @@ -435,10 +436,11 @@ public class RustServerCodegen extends DefaultCodegen implements CodegenConfig { public String toOperationId(String operationId) { // method name cannot use reserved keyword, e.g. return if (isReservedWord(operationId)) { - LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + camelize("call_" + operationId)); + LOGGER.warn("{} (reserved word) cannot be used as method name. Renamed to {}", operationId, camelize("call_" + operationId)); operationId = "call_" + operationId; } else if (operationId.matches("\\d.*")) { - LOGGER.warn(operationId + " cannot be used as method name because it starts with a digit. Renamed to " + camelize("call_" + operationId)); + LOGGER.warn("{} cannot be used as method name because it starts with a digit. Renamed to {}", operationId, + camelize("call_" + operationId)); operationId = "call_" + operationId; } @@ -459,7 +461,7 @@ public class RustServerCodegen extends DefaultCodegen implements CodegenConfig { // model name cannot use reserved keyword, e.g. return if (isReservedWord(name)) { - LOGGER.warn(name + " (reserved word) cannot be used as model name. Renamed to " + camelize("model_" + name)); + LOGGER.warn("{} (reserved word) cannot be used as model name. Renamed to {}", name, camelize("model_" + name)); name = "model_" + name; // e.g. return => ModelReturn (after camelize) } @@ -1098,7 +1100,7 @@ public class RustServerCodegen extends DefaultCodegen implements CodegenConfig { co, Map> operations) { // only generate operation for the first tag of the tags if (tag != null && co.tags.size() > 1 && !tag.equals(co.tags.get(0).getName())) { - LOGGER.info("generated skip additional tag `" + tag + "` with operationId=" + co.operationId); + LOGGER.info("generated skip additional tag `{}` with operationId={}", tag, co.operationId); return; } super.addOperationToGroup(tag, resourcePath, operation, co, operations); @@ -1163,7 +1165,7 @@ public class RustServerCodegen extends DefaultCodegen implements CodegenConfig { datatype = "models::" + datatype; } } catch (Exception e) { - LOGGER.warn("Error obtaining the datatype from schema (model):" + p + ". Datatype default to Object"); + LOGGER.warn("Error obtaining the datatype from schema (model):{}. Datatype default to Object", p); datatype = "Object"; LOGGER.error(e.getMessage(), e); } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ScalaAkkaHttpServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ScalaAkkaHttpServerCodegen.java index f2d63fbf140..35a308f639a 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ScalaAkkaHttpServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ScalaAkkaHttpServerCodegen.java @@ -245,7 +245,7 @@ public class ScalaAkkaHttpServerCodegen extends AbstractScalaCodegen implements } } catch (NumberFormatException e) { - LOGGER.warn("Unable to parse " + AKKA_HTTP_VERSION + ": " + akkaHttpVersion + ", fallback to " + DEFAULT_AKKA_HTTP_VERSION); + LOGGER.warn("Unable to parse {}: {}, fallback to {}", AKKA_HTTP_VERSION, akkaHttpVersion, DEFAULT_AKKA_HTTP_VERSION); akkaHttpVersion = DEFAULT_AKKA_HTTP_VERSION; is10_1_10AndAbove = true; } @@ -318,10 +318,9 @@ public class ScalaAkkaHttpServerCodegen extends AbstractScalaCodegen implements if (pathParam.baseName.equals(parameterName)) { String matcher = pathTypeToMatcher.get(pathParam.dataType); if (matcher == null) { - LOGGER.warn("The path parameter " + pathParam.baseName + - " with the datatype " + pathParam.dataType + - " could not be translated to a corresponding path matcher of akka http" + - " and therefore has been translated to string."); + LOGGER.warn( + "The path parameter {} with the datatype {} could not be translated to a corresponding path matcher of akka http and therefore has been translated to string.", + pathParam.baseName, pathParam.dataType); matcher = pathTypeToMatcher.get("String"); } if (pathParam.pattern != null && !pathParam.pattern.isEmpty()) { diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ScalaHttpClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ScalaHttpClientCodegen.java index 517d0e8c58a..de887007308 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ScalaHttpClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ScalaHttpClientCodegen.java @@ -105,27 +105,6 @@ public class ScalaHttpClientCodegen extends AbstractScalaCodegen implements Code additionalProperties.put("authPreemptive", authPreemptive); additionalProperties.put("clientName", clientName); - supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml")); - supportingFiles.add(new SupportingFile("apiInvoker.mustache", - (sourceFolder + File.separator + invokerPackage).replace(".", java.io.File.separator), "ApiInvoker.scala")); - supportingFiles.add(new SupportingFile("client.mustache", - (sourceFolder + File.separator + invokerPackage).replace(".", java.io.File.separator), clientName + ".scala")); - supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh")); - supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore")); - // gradle settings - supportingFiles.add(new SupportingFile("build.gradle.mustache", "", "build.gradle")); - supportingFiles.add(new SupportingFile("settings.gradle.mustache", "", "settings.gradle")); - supportingFiles.add(new SupportingFile("gradle.properties.mustache", "", "gradle.properties")); - // gradleWrapper files - supportingFiles.add(new SupportingFile("gradlew.mustache", "", "gradlew")); - supportingFiles.add(new SupportingFile("gradlew.bat.mustache", "", "gradlew.bat")); - supportingFiles.add(new SupportingFile("gradle-wrapper.properties.mustache", - gradleWrapperPackage.replace(".", File.separator), "gradle-wrapper.properties")); - supportingFiles.add(new SupportingFile("gradle-wrapper.jar", - gradleWrapperPackage.replace(".", File.separator), "gradle-wrapper.jar")); - - supportingFiles.add(new SupportingFile("build.sbt.mustache", "", "build.sbt")); - importMapping.remove("List"); importMapping.remove("Set"); importMapping.remove("Map"); @@ -163,6 +142,27 @@ public class ScalaHttpClientCodegen extends AbstractScalaCodegen implements Code LOGGER.warn("IMPORTANT: This generator (scala-http-client-deprecated) is no longer actively maintained and will be deprecated. " + "PLease use 'scala-akka' generator instead."); super.processOpts(); + + supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml")); + supportingFiles.add(new SupportingFile("apiInvoker.mustache", + (sourceFolder + File.separator + invokerPackage).replace(".", java.io.File.separator), "ApiInvoker.scala")); + supportingFiles.add(new SupportingFile("client.mustache", + (sourceFolder + File.separator + invokerPackage).replace(".", java.io.File.separator), clientName + ".scala")); + supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh")); + supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore")); + // gradle settings + supportingFiles.add(new SupportingFile("build.gradle.mustache", "", "build.gradle")); + supportingFiles.add(new SupportingFile("settings.gradle.mustache", "", "settings.gradle")); + supportingFiles.add(new SupportingFile("gradle.properties.mustache", "", "gradle.properties")); + // gradleWrapper files + supportingFiles.add(new SupportingFile("gradlew.mustache", "", "gradlew")); + supportingFiles.add(new SupportingFile("gradlew.bat.mustache", "", "gradlew.bat")); + supportingFiles.add(new SupportingFile("gradle-wrapper.properties.mustache", + gradleWrapperPackage.replace(".", File.separator), "gradle-wrapper.properties")); + supportingFiles.add(new SupportingFile("gradle-wrapper.jar", + gradleWrapperPackage.replace(".", File.separator), "gradle-wrapper.jar")); + + supportingFiles.add(new SupportingFile("build.sbt.mustache", "", "build.sbt")); } @Override diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ScalaPlayFrameworkServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ScalaPlayFrameworkServerCodegen.java index 3181dde93e6..f38d42d1020 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ScalaPlayFrameworkServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ScalaPlayFrameworkServerCodegen.java @@ -317,7 +317,7 @@ public class ScalaPlayFrameworkServerCodegen extends AbstractScalaCodegen implem } if (null == openAPIType) { - LOGGER.error("No Type defined for Schema " + p); + LOGGER.error("No Type defined for Schema {}", p); } return toModelName(openAPIType); } 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 4c4f0e19496..0dd93bfc594 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 @@ -229,7 +229,7 @@ public class SpringCodegen extends AbstractJavaCodegen // set invokerPackage as basePackage: this.setBasePackage((String) additionalProperties.get(CodegenConstants.INVOKER_PACKAGE)); additionalProperties.put(BASE_PACKAGE, basePackage); - LOGGER.info("Set base package to invoker package (" + basePackage + ")"); + LOGGER.info("Set base package to invoker package ({})", basePackage); } super.processOpts(); @@ -336,8 +336,8 @@ public class SpringCodegen extends AbstractJavaCodegen } additionalProperties.put(UNHANDLED_EXCEPTION_HANDLING, this.isUnhandledException()); - typeMapping.put("file", "org.springframework.web.multipart.MultipartFile"); - importMapping.put("org.springframework.web.multipart.MultipartFile", "org.springframework.web.multipart.MultipartFile"); + typeMapping.put("file", "org.springframework.core.io.Resource"); + importMapping.put("org.springframework.core.io.Resource", "org.springframework.core.io.Resource"); if (useOptional) { writePropertyBack(USE_OPTIONAL, useOptional); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/StaticHtml2Generator.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/StaticHtml2Generator.java index 18f774e3710..fa94bcfa29b 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/StaticHtml2Generator.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/StaticHtml2Generator.java @@ -229,7 +229,7 @@ public class StaticHtml2Generator extends DefaultCodegen implements CodegenConfi Markdown markInstance = new Markdown(); openAPI.getInfo().setDescription(markInstance.toHtml(currentDescription)); } else { - LOGGER.error("OpenAPI object description is empty [" + openAPI.getInfo().getTitle() + "]"); + LOGGER.error("OpenAPI object description is empty [{}]", openAPI.getInfo().getTitle()); } } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/Swift4Codegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/Swift4Codegen.java index 0133cfb3c17..5992ab51560 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/Swift4Codegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/Swift4Codegen.java @@ -568,8 +568,7 @@ public class Swift4Codegen extends DefaultCodegen implements CodegenConfig { // model name cannot use reserved keyword, e.g. return if (isReservedWord(name)) { String modelName = "Model" + name; - LOGGER.warn(name + " (reserved word) cannot be used as model name. Renamed to " - + modelName); + LOGGER.warn("{} (reserved word) cannot be used as model name. Renamed to {}", name, modelName); return modelName; } @@ -577,9 +576,8 @@ public class Swift4Codegen extends DefaultCodegen implements CodegenConfig { if (name.matches("^\\d.*")) { // e.g. 200Response => Model200Response (after camelize) String modelName = "Model" + name; - LOGGER.warn(name - + " (model name starts with number) cannot be used as model name." - + " Renamed to " + modelName); + LOGGER.warn("{} (model name starts with number) cannot be used as model name. Renamed to {}", name, + modelName); return modelName; } @@ -674,14 +672,13 @@ public class Swift4Codegen extends DefaultCodegen implements CodegenConfig { // method name cannot use reserved keyword, e.g. return if (isReservedWord(operationId)) { String newOperationId = camelize(("call_" + operationId), true); - LOGGER.warn(operationId + " (reserved word) cannot be used as method name." - + " Renamed to " + newOperationId); + LOGGER.warn("{} (reserved word) cannot be used as method name. Renamed to {}", operationId, newOperationId); return newOperationId; } // operationId starts with a number if (operationId.matches("^\\d.*")) { - LOGGER.warn(operationId + " (starting with a number) cannot be used as method name. Renamed to " + camelize(sanitizeName("call_" + operationId), true)); + LOGGER.warn("{} (starting with a number) cannot be used as method name. Renamed to {}", operationId, camelize(sanitizeName("call_" + operationId), true)); operationId = camelize(sanitizeName("call_" + operationId), true); } @@ -973,7 +970,7 @@ public class Swift4Codegen extends DefaultCodegen implements CodegenConfig { if (exitValue != 0) { LOGGER.error("Error running the command ({}). Exit value: {}", command, exitValue); } else { - LOGGER.info("Successfully executed: " + command); + LOGGER.info("Successfully executed: {}", command); } } catch (InterruptedException | IOException e) { LOGGER.error("Error running the command ({}). Exception: {}", command, e.getMessage()); 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 5d7f86a40d3..4b109700254 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 @@ -63,9 +63,14 @@ public class Swift5ClientCodegen extends DefaultCodegen implements CodegenConfig public static final String LENIENT_TYPE_CAST = "lenientTypeCast"; public static final String USE_SPM_FILE_STRUCTURE = "useSPMFileStructure"; public static final String SWIFT_PACKAGE_PATH = "swiftPackagePath"; + public static final String USE_CLASSES = "useClasses"; public static final String USE_BACKTICK_ESCAPES = "useBacktickEscapes"; + public static final String GENERATE_MODEL_ADDITIONAL_PROPERTIES = "generateModelAdditionalProperties"; + public static final String HASHABLE_MODELS = "hashableModels"; + public static final String MAP_FILE_BINARY_TO_DATA = "mapFileBinaryToData"; protected static final String LIBRARY_ALAMOFIRE = "alamofire"; protected static final String LIBRARY_URLSESSION = "urlsession"; + protected static final String LIBRARY_VAPOR = "vapor"; protected static final String RESPONSE_LIBRARY_PROMISE_KIT = "PromiseKit"; protected static final String RESPONSE_LIBRARY_RX_SWIFT = "RxSwift"; protected static final String RESPONSE_LIBRARY_RESULT = "Result"; @@ -79,7 +84,11 @@ public class Swift5ClientCodegen extends DefaultCodegen implements CodegenConfig protected boolean swiftUseApiNamespace = false; protected boolean useSPMFileStructure = false; protected String swiftPackagePath = "Classes" + File.separator + "OpenAPIs"; + protected boolean useClasses = false; protected boolean useBacktickEscapes = false; + protected boolean generateModelAdditionalProperties = true; + protected boolean hashableModels = true; + protected boolean mapFileBinaryToData = false; protected String[] responseAs = new String[0]; protected String sourceFolder = swiftPackagePath; protected HashSet objcReservedWords; @@ -91,9 +100,10 @@ public class Swift5ClientCodegen extends DefaultCodegen implements CodegenConfig */ public Swift5ClientCodegen() { super(); + this.useOneOfInterfaces = true; generatorMetadata = GeneratorMetadata.newBuilder(generatorMetadata) - .stability(Stability.BETA) + .stability(Stability.STABLE) .build(); outputFolder = "generated-code" + File.separator + "swift"; @@ -115,7 +125,6 @@ public class Swift5ClientCodegen extends DefaultCodegen implements CodegenConfig "Bool", "Void", "String", - "URL", "Data", "Date", "Character", @@ -267,15 +276,29 @@ public class Swift5ClientCodegen extends DefaultCodegen implements CodegenConfig cliOptions.add(new CliOption(USE_BACKTICK_ESCAPES, "Escape reserved words using backticks (default: false)") .defaultValue(Boolean.FALSE.toString())); + cliOptions.add(new CliOption(GENERATE_MODEL_ADDITIONAL_PROPERTIES, + "Generate model additional properties (default: true)") + .defaultValue(Boolean.TRUE.toString())); cliOptions.add(new CliOption(CodegenConstants.API_NAME_PREFIX, CodegenConstants.API_NAME_PREFIX_DESC)); cliOptions.add(new CliOption(USE_SPM_FILE_STRUCTURE, "Use SPM file structure" + " and set the source path to Sources" + File.separator + "{{projectName}} (default: false).")); cliOptions.add(new CliOption(SWIFT_PACKAGE_PATH, "Set a custom source path instead of " + projectName + File.separator + "Classes" + File.separator + "OpenAPIs" + ".")); + cliOptions.add(new CliOption(USE_CLASSES, "Use final classes for models instead of structs (default: false)") + .defaultValue(Boolean.FALSE.toString())); + + cliOptions.add(new CliOption(HASHABLE_MODELS, + "Make hashable models (default: true)") + .defaultValue(Boolean.TRUE.toString())); + + cliOptions.add(new CliOption(MAP_FILE_BINARY_TO_DATA, + "[WARNING] This option will be removed and enabled by default in the future once we've enhanced the code to work with `Data` in all the different situations. Map File and Binary to Data (default: false)") + .defaultValue(Boolean.FALSE.toString())); supportedLibraries.put(LIBRARY_URLSESSION, "[DEFAULT] HTTP client: URLSession"); supportedLibraries.put(LIBRARY_ALAMOFIRE, "HTTP client: Alamofire"); + supportedLibraries.put(LIBRARY_VAPOR, "HTTP client: Vapor"); CliOption libraryOption = new CliOption(CodegenConstants.LIBRARY, "Library template (sub-template) to use"); libraryOption.setEnum(supportedLibraries); @@ -425,7 +448,7 @@ public class Swift5ClientCodegen extends DefaultCodegen implements CodegenConfig additionalProperties.put(READONLY_PROPERTIES, readonlyProperties); // Setup swiftUseApiNamespace option, which makes all the API - // classes inner-class of {{projectName}}API + // classes inner-class of {{projectName}} if (additionalProperties.containsKey(SWIFT_USE_API_NAMESPACE)) { setSwiftUseApiNamespace(convertPropertyToBooleanAndWriteBack(SWIFT_USE_API_NAMESPACE)); } @@ -448,63 +471,89 @@ public class Swift5ClientCodegen extends DefaultCodegen implements CodegenConfig setUseBacktickEscapes(convertPropertyToBooleanAndWriteBack(USE_BACKTICK_ESCAPES)); } + if (additionalProperties.containsKey(GENERATE_MODEL_ADDITIONAL_PROPERTIES)) { + setGenerateModelAdditionalProperties(convertPropertyToBooleanAndWriteBack(GENERATE_MODEL_ADDITIONAL_PROPERTIES)); + } + additionalProperties.put(GENERATE_MODEL_ADDITIONAL_PROPERTIES, generateModelAdditionalProperties); + + if (additionalProperties.containsKey(HASHABLE_MODELS)) { + setHashableModels(convertPropertyToBooleanAndWriteBack(HASHABLE_MODELS)); + } + additionalProperties.put(HASHABLE_MODELS, hashableModels); + + if (additionalProperties.containsKey(MAP_FILE_BINARY_TO_DATA)) { + setMapFileBinaryToData(convertPropertyToBooleanAndWriteBack(MAP_FILE_BINARY_TO_DATA)); + } + additionalProperties.put(MAP_FILE_BINARY_TO_DATA, mapFileBinaryToData); + if (mapFileBinaryToData) { + typeMapping.put("file", "Data"); + typeMapping.put("binary", "Data"); + } + + if (additionalProperties.containsKey(USE_CLASSES)) { + setUseClasses(convertPropertyToBooleanAndWriteBack(USE_CLASSES)); + } + additionalProperties.put(USE_CLASSES, useClasses); + setLenientTypeCast(convertPropertyToBooleanAndWriteBack(LENIENT_TYPE_CAST)); // make api and model doc path available in mustache template additionalProperties.put("apiDocPath", apiDocPath); additionalProperties.put("modelDocPath", modelDocPath); - supportingFiles.add(new SupportingFile("Podspec.mustache", - "", - projectName + ".podspec")); - supportingFiles.add(new SupportingFile("Cartfile.mustache", - "", - "Cartfile")); + if (!getLibrary().equals(LIBRARY_VAPOR)) { + supportingFiles.add(new SupportingFile("Podspec.mustache", + "", + projectName + ".podspec")); + supportingFiles.add(new SupportingFile("Cartfile.mustache", + "", + "Cartfile")); + supportingFiles.add(new SupportingFile("CodableHelper.mustache", + sourceFolder, + "CodableHelper.swift")); + supportingFiles.add(new SupportingFile("OpenISO8601DateFormatter.mustache", + sourceFolder, + "OpenISO8601DateFormatter.swift")); + supportingFiles.add(new SupportingFile("JSONDataEncoding.mustache", + sourceFolder, + "JSONDataEncoding.swift")); + supportingFiles.add(new SupportingFile("JSONEncodingHelper.mustache", + sourceFolder, + "JSONEncodingHelper.swift")); + supportingFiles.add(new SupportingFile("git_push.sh.mustache", + "", + "git_push.sh")); + supportingFiles.add(new SupportingFile("SynchronizedDictionary.mustache", + sourceFolder, + "SynchronizedDictionary.swift")); + supportingFiles.add(new SupportingFile("XcodeGen.mustache", + "", + "project.yml")); + supportingFiles.add(new SupportingFile("APIHelper.mustache", + sourceFolder, + "APIHelper.swift")); + supportingFiles.add(new SupportingFile("Models.mustache", + sourceFolder, + "Models.swift")); + } supportingFiles.add(new SupportingFile("Package.swift.mustache", "", "Package.swift")); - supportingFiles.add(new SupportingFile("APIHelper.mustache", - sourceFolder, - "APIHelper.swift")); supportingFiles.add(new SupportingFile("Configuration.mustache", sourceFolder, "Configuration.swift")); supportingFiles.add(new SupportingFile("Extensions.mustache", sourceFolder, "Extensions.swift")); - supportingFiles.add(new SupportingFile("Models.mustache", - sourceFolder, - "Models.swift")); supportingFiles.add(new SupportingFile("APIs.mustache", sourceFolder, "APIs.swift")); - supportingFiles.add(new SupportingFile("CodableHelper.mustache", - sourceFolder, - "CodableHelper.swift")); - supportingFiles.add(new SupportingFile("OpenISO8601DateFormatter.mustache", - sourceFolder, - "OpenISO8601DateFormatter.swift")); - supportingFiles.add(new SupportingFile("JSONDataEncoding.mustache", - sourceFolder, - "JSONDataEncoding.swift")); - supportingFiles.add(new SupportingFile("JSONEncodingHelper.mustache", - sourceFolder, - "JSONEncodingHelper.swift")); - supportingFiles.add(new SupportingFile("git_push.sh.mustache", - "", - "git_push.sh")); - supportingFiles.add(new SupportingFile("SynchronizedDictionary.mustache", - sourceFolder, - "SynchronizedDictionary.swift")); supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore")); supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); - supportingFiles.add(new SupportingFile("XcodeGen.mustache", - "", - "project.yml")); switch (getLibrary()) { case LIBRARY_ALAMOFIRE: @@ -519,12 +568,23 @@ public class Swift5ClientCodegen extends DefaultCodegen implements CodegenConfig sourceFolder, "URLSessionImplementations.swift")); break; + case LIBRARY_VAPOR: + additionalProperties.put("useVapor", true); + break; default: break; } } + public boolean isMapFileBinaryToData() { + return mapFileBinaryToData; + } + + public void setMapFileBinaryToData(boolean mapFileBinaryToData) { + this.mapFileBinaryToData = mapFileBinaryToData; + } + @Override protected boolean isReservedWord(String word) { return word != null && reservedWords.contains(word); //don't lowercase as super does @@ -614,8 +674,7 @@ public class Swift5ClientCodegen extends DefaultCodegen implements CodegenConfig // model name cannot use reserved keyword, e.g. return if (isReservedWord(name)) { String modelName = "Model" + name; - LOGGER.warn(name + " (reserved word) cannot be used as model name. Renamed to " - + modelName); + LOGGER.warn("{} (reserved word) cannot be used as model name. Renamed to {}", name, modelName); return modelName; } @@ -623,9 +682,8 @@ public class Swift5ClientCodegen extends DefaultCodegen implements CodegenConfig if (name.matches("^\\d.*")) { // e.g. 200Response => Model200Response (after camelize) String modelName = "Model" + name; - LOGGER.warn(name - + " (model name starts with number) cannot be used as model name." - + " Renamed to " + modelName); + LOGGER.warn("{} (model name starts with number) cannot be used as model name. Renamed to {}", name, + modelName); return modelName; } @@ -725,14 +783,13 @@ public class Swift5ClientCodegen extends DefaultCodegen implements CodegenConfig // method name cannot use reserved keyword, e.g. return if (isReservedWord(operationId)) { String newOperationId = camelize(("call_" + operationId), true); - LOGGER.warn(operationId + " (reserved word) cannot be used as method name." - + " Renamed to " + newOperationId); + LOGGER.warn("{} (reserved word) cannot be used as method name. Renamed to {}", operationId, newOperationId); return newOperationId; } // operationId starts with a number if (operationId.matches("^\\d.*")) { - LOGGER.warn(operationId + " (starting with a number) cannot be used as method name. Renamed to " + camelize(sanitizeName("call_" + operationId), true)); + LOGGER.warn("{} (starting with a number) cannot be used as method name. Renamed to {}", operationId, camelize(sanitizeName("call_" + operationId), true)); operationId = camelize(sanitizeName("call_" + operationId), true); } @@ -818,7 +875,9 @@ public class Swift5ClientCodegen extends DefaultCodegen implements CodegenConfig parentSchema = parentCodegenModel.parentSchema; } } - + if (hashableModels) { + codegenModel.vendorExtensions.put("x-swift-hashable", true); + } return codegenModel; } @@ -858,10 +917,22 @@ public class Swift5ClientCodegen extends DefaultCodegen implements CodegenConfig this.swiftPackagePath = swiftPackagePath; } + public void setUseClasses(boolean useClasses) { + this.useClasses = useClasses; + } + public void setUseBacktickEscapes(boolean useBacktickEscapes) { this.useBacktickEscapes = useBacktickEscapes; } + public void setGenerateModelAdditionalProperties(boolean generateModelAdditionalProperties) { + this.generateModelAdditionalProperties = generateModelAdditionalProperties; + } + + public void setHashableModels(boolean hashableModels) { + this.hashableModels = hashableModels; + } + @Override public String toEnumValue(String value, String datatype) { // for string, array of string @@ -1033,7 +1104,7 @@ public class Swift5ClientCodegen extends DefaultCodegen implements CodegenConfig if (exitValue != 0) { LOGGER.error("Error running the command ({}). Exit value: {}", command, exitValue); } else { - LOGGER.info("Successfully executed: " + command); + LOGGER.info("Successfully executed: {}", command); } } catch (InterruptedException | IOException e) { LOGGER.error("Error running the command ({}). Exception: {}", command, e.getMessage()); @@ -1083,6 +1154,8 @@ public class Swift5ClientCodegen extends DefaultCodegen implements CodegenConfig } } else if ("URL".equals(codegenParameter.dataType)) { // URL return "URL(string: \"https://example.com\")!"; + } else if ("Data".equals(codegenParameter.dataType)) { // URL + return "Data([9, 8, 7])"; } else if ("Date".equals(codegenParameter.dataType)) { // date return "Date()"; } else { // numeric diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptAngularClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptAngularClientCodegen.java index e91ddecda38..8773634e93b 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptAngularClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptAngularClientCodegen.java @@ -517,6 +517,7 @@ public class TypeScriptAngularClientCodegen extends AbstractTypeScriptClientCode if (cm.discriminator != null && cm.children != null) { for (CodegenModel child : cm.children) { cm.imports.add(child.classname); + setChildDiscriminatorValue(cm, child); } } if (cm.parent != null) { @@ -531,6 +532,25 @@ public class TypeScriptAngularClientCodegen extends AbstractTypeScriptClientCode return result; } + private void setChildDiscriminatorValue(CodegenModel parent, CodegenModel child) { + if ( + child.vendorExtensions.isEmpty() || + !child.vendorExtensions.containsKey("x-discriminator-value") + ) { + + for (CodegenProperty prop : child.allVars) { + if (prop.baseName.equals(parent.discriminator.getPropertyName())) { + + for (CodegenDiscriminator.MappedModel mappedModel : parent.discriminator.getMappedModels()) { + if (mappedModel.getModelName().equals(child.classname)) { + prop.discriminatorValue = mappedModel.getMappingName(); + } + } + } + } + } + } + /** * Parse imports */ diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptClientCodegen.java index c8fe4b4e042..821d190f5eb 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptClientCodegen.java @@ -19,6 +19,7 @@ package org.openapitools.codegen.languages; import io.swagger.v3.oas.models.OpenAPI; import io.swagger.v3.oas.models.media.ArraySchema; +import io.swagger.v3.oas.models.media.ComposedSchema; import io.swagger.v3.oas.models.media.Schema; import io.swagger.v3.oas.models.parameters.Parameter; import org.apache.commons.lang3.StringUtils; @@ -32,6 +33,8 @@ import org.slf4j.LoggerFactory; import java.io.File; import java.text.SimpleDateFormat; import java.util.*; +import java.util.stream.Collectors; + import static org.openapitools.codegen.utils.StringUtils.camelize; import static org.openapitools.codegen.utils.StringUtils.underscore; @@ -144,10 +147,12 @@ public class TypeScriptClientCodegen extends DefaultCodegen implements CodegenCo typeMapping.put("object", "any"); typeMapping.put("integer", "number"); typeMapping.put("Map", "any"); + typeMapping.put("map", "any"); typeMapping.put("date", "string"); typeMapping.put("DateTime", "Date"); typeMapping.put("binary", "any"); typeMapping.put("File", "any"); + typeMapping.put("file", "any"); typeMapping.put("ByteArray", "string"); typeMapping.put("UUID", "string"); typeMapping.put("Error", "Error"); @@ -373,40 +378,58 @@ public class TypeScriptClientCodegen extends DefaultCodegen implements CodegenCo } @Override - public String toModelName(String name) { - name = sanitizeName(name); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. + public String toModelName(final String name) { + String fullModelName = name; + fullModelName = addPrefix(fullModelName, modelNamePrefix); + fullModelName = addSuffix(fullModelName, modelNameSuffix); + return toTypescriptTypeName(fullModelName, "Model"); + } - if (!StringUtils.isEmpty(modelNamePrefix)) { - name = modelNamePrefix + "_" + name; + protected String addPrefix(String name, String prefix) { + if (!StringUtils.isEmpty(prefix)) { + name = prefix + "_" + name; + } + return name; + } + + protected String addSuffix(String name, String suffix) { + if (!StringUtils.isEmpty(suffix)) { + name = name + "_" + suffix; } - if (!StringUtils.isEmpty(modelNameSuffix)) { - name = name + "_" + modelNameSuffix; - } + return name; + } + + protected String toTypescriptTypeName(final String name, String safePrefix) { + ArrayList exceptions = new ArrayList(Arrays.asList("\\|", " ")); + String sanName = sanitizeName(name, "(?![| ])\\W", exceptions); + + sanName = camelize(sanName); // model name cannot use reserved keyword, e.g. return - if (isReservedWord(name)) { - String modelName = camelize("model_" + name); - LOGGER.warn(name + " (reserved word) cannot be used as model name. Renamed to " + modelName); + // this is unlikely to happen, because we have just camelized the name, while reserved words are usually all lowcase + if (isReservedWord(sanName)) { + String modelName = safePrefix + sanName; + LOGGER.warn("{} (reserved word) cannot be used as model name. Renamed to {}", sanName, modelName); return modelName; } // model name starts with number - if (name.matches("^\\d.*")) { - String modelName = camelize("model_" + name); // e.g. 200Response => Model200Response (after camelize) - LOGGER.warn(name + " (model name starts with number) cannot be used as model name. Renamed to " + modelName); + if (sanName.matches("^\\d.*")) { + String modelName = safePrefix + sanName; // e.g. 200Response => Model200Response + LOGGER.warn("{} (model name starts with number) cannot be used as model name. Renamed to {}", sanName, + modelName); return modelName; } - if (languageSpecificPrimitives.contains(name)) { - String modelName = camelize("model_" + name); - LOGGER.warn(name + " (model name matches existing language type) cannot be used as a model name. Renamed to " + modelName); + if (languageSpecificPrimitives.contains(sanName)) { + String modelName = safePrefix + sanName; + LOGGER.warn("{} (model name matches existing language type) cannot be used as a model name. Renamed to {}", + sanName, modelName); return modelName; } - // camelize the model name - // phone_number => PhoneNumber - return camelize(name); + return sanName; } @Override @@ -521,7 +544,9 @@ public class TypeScriptClientCodegen extends DefaultCodegen implements CodegenCo public String getSchemaType(Schema p) { String openAPIType = super.getSchemaType(p); String type = null; - if (typeMapping.containsKey(openAPIType)) { + if (ModelUtils.isComposedSchema(p)) { + return openAPIType; + } else if (typeMapping.containsKey(openAPIType)) { type = typeMapping.get(openAPIType); if (languageSpecificPrimitives.contains(type)) return type; @@ -853,4 +878,55 @@ public class TypeScriptClientCodegen extends DefaultCodegen implements CodegenCo codegenModel.additionalPropertiesType = getTypeDeclaration((Schema) schema.getAdditionalProperties()); addImport(codegenModel, codegenModel.additionalPropertiesType); } + + @Override + public String toAnyOfName(List names, ComposedSchema composedSchema) { + List types = getTypesFromSchemas(composedSchema.getAnyOf()); + + return String.join(" | ", types); + } + + @Override + public String toOneOfName(List names, ComposedSchema composedSchema) { + List types = getTypesFromSchemas(composedSchema.getOneOf()); + + return String.join(" | ", types); + } + + /** + * Extracts the list of type names from a list of schemas. + * Excludes `AnyType` if there are other valid types extracted. + * + * @param schemas list of schemas + * @return list of types + */ + protected List getTypesFromSchemas(List schemas) { + List filteredSchemas = schemas.size() > 1 + ? schemas.stream().filter(schema -> !"AnyType".equals(super.getSchemaType(schema))).collect(Collectors.toList()) + : schemas; + + return filteredSchemas.stream().map(schema -> { + String schemaType = getSchemaType(schema); + if (ModelUtils.isArraySchema(schema)) { + ArraySchema ap = (ArraySchema) schema; + Schema inner = ap.getItems(); + schemaType = schemaType + "<" + getSchemaType(inner) + ">"; + } + return schemaType; + }).distinct().collect(Collectors.toList()); + } + + @Override + protected void addImport(CodegenModel m, String type) { + if (type == null) { + return; + } + + String[] parts = type.split("( [|&] )|[<>]"); + for (String s : parts) { + if (needToImport(s)) { + m.imports.add(s); + } + } + } } 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 d182ffb6e0e..c32bdcbb6cc 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 @@ -19,7 +19,12 @@ package org.openapitools.codegen.languages; import com.google.common.collect.ImmutableMap; import com.samskivert.mustache.Mustache; +import io.swagger.v3.oas.models.Operation; 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 io.swagger.v3.parser.util.SchemaTypeUtil; import org.openapitools.codegen.*; import org.openapitools.codegen.meta.features.DocumentationFeature; @@ -27,12 +32,9 @@ import org.openapitools.codegen.templating.mustache.IndentedLambda; import org.openapitools.codegen.utils.ModelUtils; import java.io.File; -import java.util.TreeSet; -import java.util.List; -import java.util.Map; +import java.util.*; public class TypeScriptFetchClientCodegen extends AbstractTypeScriptClientCodegen { - public static final String NPM_REPOSITORY = "npmRepository"; public static final String WITH_INTERFACES = "withInterfaces"; public static final String USE_SINGLE_REQUEST_PARAMETER = "useSingleRequestParameter"; @@ -48,6 +50,24 @@ public class TypeScriptFetchClientCodegen extends AbstractTypeScriptClientCodege protected boolean typescriptThreePlus = false; protected boolean withoutRuntimeChecks = false; + // "Saga and Record" mode. + public static final String SAGAS_AND_RECORDS = "sagasAndRecords"; + public static final String DETECT_PASSTHROUGH_MODELS_WITH_SUFFIX_AND_FIELD = "detectPassthroughModelsWithSuffixAndField"; + public static final String INFER_UNIQUE_ID_FROM_NAME_SUFFIX = "inferUniqueIdFromNameSuffix"; + public static final String INFER_ENTITY_FROM_UNIQUE_ID_WITH_NAME = "inferEntityFromUniqueIdWithName"; + public static final String PACKAGE_AS_SOURCE_ONLY_LIBRARY = "packageAsSourceOnlyLibrary"; + + private static final String X_IS_UNIQUE_ID = "x-isUniqueId"; + private static final String X_ENTITY_ID = "x-entityId"; + private static final String X_OPERATION_RETURN_PASSTHROUGH = "x-operationReturnPassthrough"; + private static final String X_KEEP_AS_JS_OBJECT = "x-keepAsJSObject"; + + protected boolean sagasAndRecords = false; + protected String detectPassthroughModelsWithSuffixAndField = null; // Ex: "Response;data" + protected boolean inferUniqueIdFromNameSuffix = false; + protected String inferEntityFromUniqueIdWithName = null; + protected boolean packageAsSourceOnlyLibrary = false; + public TypeScriptFetchClientCodegen() { super(); @@ -75,6 +95,7 @@ public class TypeScriptFetchClientCodegen extends AbstractTypeScriptClientCodege this.cliOptions.add(new CliOption(PREFIX_PARAMETER_INTERFACES, "Setting this property to true will generate parameter interface declarations prefixed with API class name to avoid name conflicts.", SchemaTypeUtil.BOOLEAN_TYPE).defaultValue(Boolean.FALSE.toString())); this.cliOptions.add(new CliOption(TYPESCRIPT_THREE_PLUS, "Setting this property to true will generate TypeScript 3.6+ compatible code.", SchemaTypeUtil.BOOLEAN_TYPE).defaultValue(Boolean.FALSE.toString())); this.cliOptions.add(new CliOption(WITHOUT_RUNTIME_CHECKS, "Setting this property to true will remove any runtime checks on the request and response payloads. Payloads will be casted to their expected types.", SchemaTypeUtil.BOOLEAN_TYPE).defaultValue(Boolean.FALSE.toString())); + this.cliOptions.add(new CliOption(SAGAS_AND_RECORDS, "Setting this property to true will generate additional files for use with redux-saga and immutablejs.", SchemaTypeUtil.BOOLEAN_TYPE).defaultValue(Boolean.FALSE.toString())); } @Override @@ -103,14 +124,72 @@ public class TypeScriptFetchClientCodegen extends AbstractTypeScriptClientCodege this.typescriptThreePlus = typescriptThreePlus; } - public Boolean getWithoutRuntimeChecks(){ + public Boolean getWithoutRuntimeChecks() { return withoutRuntimeChecks; } - public void setWithoutRuntimeChecks(Boolean withoutRuntimeChecks){ + public void setWithoutRuntimeChecks(Boolean withoutRuntimeChecks) { this.withoutRuntimeChecks = withoutRuntimeChecks; } + public Boolean getSagasAndRecords() { + return sagasAndRecords; + } + + public void setSagasAndRecords(Boolean sagasAndRecords) { + this.sagasAndRecords = sagasAndRecords; + } + + public String getPassthroughSuffix() { + return detectPassthroughModelsWithSuffixAndField != null ? detectPassthroughModelsWithSuffixAndField.split("\\.")[0] : null; + } + + public String getPassthroughField() { + return detectPassthroughModelsWithSuffixAndField != null ? detectPassthroughModelsWithSuffixAndField.split("\\.")[1] : null; + } + + public String getDetectPassthroughModelsWithSuffixAndField() { + return detectPassthroughModelsWithSuffixAndField; + } + + public void setDetectPassthroughModelsWithSuffixAndField(String detectPassthroughModelsWithSuffixAndField) { + this.detectPassthroughModelsWithSuffixAndField = detectPassthroughModelsWithSuffixAndField; + } + + public boolean getInferUniqueIdFromNameSuffix() { + return inferUniqueIdFromNameSuffix; + } + + public void setInferUniqueIdFromNameSuffix(boolean inferUniqueIdFromNameSuffix) { + this.inferUniqueIdFromNameSuffix = inferUniqueIdFromNameSuffix; + } + + public String getInferEntityFromUniqueIdWithName() { + return inferEntityFromUniqueIdWithName; + } + + public void setInferEntityFromUniqueIdWithName(String inferEntityFromUniqueIdWithName) { + this.inferEntityFromUniqueIdWithName = inferEntityFromUniqueIdWithName; + } + + public boolean getPackageAsSourceOnlyLibrary() { + return packageAsSourceOnlyLibrary; + } + + public void setPackageAsSourceOnlyLibrary(boolean packageAsSourceOnlyLibrary) { + this.packageAsSourceOnlyLibrary = packageAsSourceOnlyLibrary; + } + + public boolean isUniqueIdAccordingToNameSuffix(String name) { + if (name == null) { + return false; + } + return "id".equals(name) || + "ids".equals(name) || + (name.length() >= 3 && name.substring(name.length() - 2).equals("Id")) || + (name.length() >= 4 && name.substring(name.length() - 3).equals("Ids")); + } + @Override public void processOpts() { super.processOpts(); @@ -150,11 +229,59 @@ public class TypeScriptFetchClientCodegen extends AbstractTypeScriptClientCodege this.setWithoutRuntimeChecks(convertPropertyToBoolean(WITHOUT_RUNTIME_CHECKS)); } - if(!withoutRuntimeChecks){ + if (!withoutRuntimeChecks) { this.modelTemplateFiles.put("models.mustache", ".ts"); } + + if (additionalProperties.containsKey(SAGAS_AND_RECORDS)) { + this.setSagasAndRecords(convertPropertyToBoolean(SAGAS_AND_RECORDS)); + if (this.getSagasAndRecords()) { + apiTemplateFiles.put("sagas.mustache", "Sagas.ts"); + modelTemplateFiles.put("records.mustache", "Record.ts"); + supportingFiles.add(new SupportingFile("runtimeSagasAndRecords.mustache", sourceDir, "runtimeSagasAndRecords.ts")); + supportingFiles.add(new SupportingFile("ApiEntitiesRecord.mustache", sourceDir, "ApiEntitiesRecord.ts")); + supportingFiles.add(new SupportingFile("ApiEntitiesReducer.mustache", sourceDir, "ApiEntitiesReducer.ts")); + supportingFiles.add(new SupportingFile("ApiEntitiesSelectors.mustache", sourceDir, "ApiEntitiesSelectors.ts")); + + if (additionalProperties.containsKey(DETECT_PASSTHROUGH_MODELS_WITH_SUFFIX_AND_FIELD)) { + this.setDetectPassthroughModelsWithSuffixAndField((String) additionalProperties.get(DETECT_PASSTHROUGH_MODELS_WITH_SUFFIX_AND_FIELD)); + } + if (additionalProperties.containsKey(INFER_UNIQUE_ID_FROM_NAME_SUFFIX)) { + this.setInferUniqueIdFromNameSuffix(convertPropertyToBoolean(INFER_UNIQUE_ID_FROM_NAME_SUFFIX)); + } + if (additionalProperties.containsKey(INFER_ENTITY_FROM_UNIQUE_ID_WITH_NAME)) { + this.setInferEntityFromUniqueIdWithName((String) additionalProperties.get(INFER_ENTITY_FROM_UNIQUE_ID_WITH_NAME)); + } + if (additionalProperties.containsKey(PACKAGE_AS_SOURCE_ONLY_LIBRARY)) { + this.setPackageAsSourceOnlyLibrary(convertPropertyToBoolean(PACKAGE_AS_SOURCE_ONLY_LIBRARY)); + } + + this.addExtraReservedWordsForSagasAndRecords(); + + if (this.getPackageAsSourceOnlyLibrary()) { + supportingFiles.add(new SupportingFile("sourceLibraryIndex.mustache", "", "index.ts")); + } + } + } } + @Override + public String toEnumDefaultValue(String value, String datatype) { + if (this.getSagasAndRecords()) { + return datatype + "." + value; + } + return super.toEnumDefaultValue(value, datatype); + } + + @Override + protected String getEnumDefaultValue(String defaultValue, String dataType) { + if (this.getSagasAndRecords()) { + return defaultValue; + } + return super.getEnumDefaultValue(defaultValue, dataType); + } + + @Override protected ImmutableMap.Builder addMustacheLambdas() { ImmutableMap.Builder lambdas = super.addMustacheLambdas(); @@ -183,36 +310,12 @@ public class TypeScriptFetchClientCodegen extends AbstractTypeScriptClientCodege public Map postProcessModels(Map objs) { List models = (List) postProcessModelsEnum(objs).get("models"); - // process enum in models + // process enum and custom properties in models for (Object _mo : models) { Map mo = (Map) _mo; - CodegenModel cm = (CodegenModel) mo.get("model"); + ExtendedCodegenModel cm = (ExtendedCodegenModel) mo.get("model"); cm.imports = new TreeSet(cm.imports); - // name enum with model name, e.g. StatusEnum => Pet.StatusEnum - for (CodegenProperty var : cm.vars) { - if (Boolean.TRUE.equals(var.isEnum)) { - // behaviour for enum names is specific for Typescript Fetch, not using namespaces - var.datatypeWithEnum = var.datatypeWithEnum.replace(var.enumName, cm.classname + var.enumName); - } - } - if (cm.parent != null) { - for (CodegenProperty var : cm.allVars) { - if (Boolean.TRUE.equals(var.isEnum)) { - var.datatypeWithEnum = var.datatypeWithEnum - .replace(var.enumName, cm.classname + var.enumName); - } - } - } - if (!cm.oneOf.isEmpty()) { - // For oneOfs only import $refs within the oneOf - TreeSet oneOfRefs = new TreeSet<>(); - for (String im : cm.imports) { - if (cm.oneOf.contains(im)) { - oneOfRefs.add(im); - } - } - cm.imports = oneOfRefs; - } + this.processCodeGenModel(cm); } return objs; @@ -228,18 +331,71 @@ public class TypeScriptFetchClientCodegen extends AbstractTypeScriptClientCodege @Override public Map postProcessAllModels(Map objs) { + List allModels = new ArrayList(); + List entityModelClassnames = new ArrayList(); + Map result = super.postProcessAllModels(objs); for (Map.Entry entry : result.entrySet()) { Map inner = (Map) entry.getValue(); List> models = (List>) inner.get("models"); for (Map model : models) { - CodegenModel codegenModel = (CodegenModel) model.get("model"); + ExtendedCodegenModel codegenModel = (ExtendedCodegenModel) model.get("model"); model.put("hasImports", codegenModel.imports.size() > 0); + + allModels.add(codegenModel); + if (codegenModel.isEntity) { + entityModelClassnames.add(codegenModel.classname); + } + } + } + + for (ExtendedCodegenModel rootModel : allModels) { + for (String curImport : rootModel.imports) { + boolean isModelImport = false; + for (ExtendedCodegenModel model : allModels) { + if (model.classname.equals(curImport) && !model.isEnum) { + isModelImport = true; + break; + } + } + if (isModelImport) { + rootModel.modelImports.add(curImport); + } + } + + for (CodegenProperty cpVar : rootModel.vars) { + ExtendedCodegenProperty var = (ExtendedCodegenProperty) cpVar; + if (var.isModel && entityModelClassnames.indexOf(var.dataType) != -1) { + var.isEntity = true; + } else if (var.isArray && var.items.isModel && entityModelClassnames.indexOf(var.items.dataType) != -1) { + ((ExtendedCodegenProperty) var.items).isEntity = true; + } } } return result; } + private void autoSetDefaultValueForProperty(ExtendedCodegenProperty var) { + if (var.isArray || var.isModel) { + var.defaultValue = var.dataTypeAlternate + "()"; + } else if (var.isUniqueId) { + var.defaultValue = "\"-1\""; + } else if (var.isEnum) { + var.defaultValue = "'" + var._enum.get(0) + "'"; + updateCodegenPropertyEnum(var); + } else if (var.dataType.equalsIgnoreCase("string")) { + var.defaultValue = "\"\""; + } else if (var.dataType.equalsIgnoreCase("number")) { + var.defaultValue = "0"; + } else if (var.dataType.equalsIgnoreCase("boolean")) { + var.defaultValue = "false"; + } else { + if (var.allowableValues != null && var.allowableValues.get("enumVars") instanceof ArrayList && ((ArrayList) var.allowableValues.get("enumVars")).get(0) instanceof HashMap) { + var.defaultValue = var.dataTypeAlternate + "." + ((HashMap) ((ArrayList) var.allowableValues.get("enumVars")).get(0)).get("name"); + } + } + } + private void addNpmPackageGeneration() { if (additionalProperties.containsKey(NPM_REPOSITORY)) { @@ -254,12 +410,160 @@ public class TypeScriptFetchClientCodegen extends AbstractTypeScriptClientCodege supportingFiles.add(new SupportingFile("gitignore", "", ".gitignore")); } + @Override + public List fromRequestBodyToFormParameters(RequestBody body, Set imports) { + List superParams = super.fromRequestBodyToFormParameters(body, imports); + List extendedParams = new ArrayList(); + for (CodegenParameter cp : superParams) { + extendedParams.add(new ExtendedCodegenParameter(cp)); + } + return extendedParams; + } + + @Override + public ExtendedCodegenParameter fromParameter(Parameter parameter, Set imports) { + CodegenParameter cp = super.fromParameter(parameter, imports); + return new ExtendedCodegenParameter(cp); + } + + @Override + public CodegenParameter fromFormProperty(String name, Schema propertySchema, Set imports) { + CodegenParameter cp = super.fromFormProperty(name, propertySchema, imports); + return new ExtendedCodegenParameter(cp); + } + + @Override + public CodegenParameter fromRequestBody(RequestBody body, Set imports, String bodyParameterName) { + CodegenParameter cp = super.fromRequestBody(body, imports, bodyParameterName); + return new ExtendedCodegenParameter(cp); + } + + @Override + public ExtendedCodegenProperty fromProperty(String name, Schema p) { + CodegenProperty cp = super.fromProperty(name, p); + return new ExtendedCodegenProperty(cp); + } + + @Override + public ExtendedCodegenModel fromModel(String name, Schema model) { + CodegenModel cm = super.fromModel(name, model); + return new ExtendedCodegenModel(cm); + } + + @Override + public ExtendedCodegenOperation fromOperation(String path, String httpMethod, Operation operation, List servers) { + CodegenOperation superOp = super.fromOperation(path, httpMethod, operation, servers); + ExtendedCodegenOperation op = new ExtendedCodegenOperation(superOp); + + if (this.getSagasAndRecords()) { + ApiResponse methodResponse = findMethodResponse(operation.getResponses()); + if (methodResponse != null) { + Map schemas = ModelUtils.getSchemas(this.openAPI); + Schema schema = null; + if (schemas != null) { + schema = schemas.get(op.returnBaseType); + } + + ExtendedCodegenModel cm = null; + if (schema != null) { + cm = fromModel(op.returnBaseType, schema); + + Object returnPassthrough = cm.vendorExtensions.get(X_OPERATION_RETURN_PASSTHROUGH); + if (returnPassthrough instanceof String) { + if (((String) returnPassthrough).isEmpty()) { + op.hasReturnPassthroughVoid = true; + op.returnPassthrough = null; + } else { + boolean foundMatch = false; + for (CodegenProperty var : cm.vars) { + if (var.name.equals(returnPassthrough)) { + foundMatch = true; + break; + } + } + if (foundMatch) { + op.returnPassthrough = (String) returnPassthrough; + } else { // no match, treat as if empty. + op.hasReturnPassthroughVoid = true; + op.returnPassthrough = null; + } + } + } else if (this.getDetectPassthroughModelsWithSuffixAndField() != null && op.returnBaseType.length() > this.getPassthroughSuffix().length() && op.returnBaseType.substring(op.returnBaseType.length() - this.getPassthroughSuffix().length()).equals(this.getPassthroughSuffix())) { + boolean foundMatch = false; + for (CodegenProperty var : cm.vars) { + if (var.name.equals(this.getPassthroughField())) { + foundMatch = true; + break; + } + } + if (foundMatch) { + op.returnPassthrough = this.getPassthroughField(); + } else { // no match, treat as if empty. + op.hasReturnPassthroughVoid = true; + op.returnPassthrough = null; + } + } + } + + if (!op.hasReturnPassthroughVoid) { + Schema responseSchema = unaliasSchema(ModelUtils.getSchemaFromResponse(methodResponse), importMapping); + ExtendedCodegenProperty cp = null; + if (op.returnPassthrough instanceof String && cm != null) { + cp = (ExtendedCodegenProperty) this.processCodeGenModel(cm).vars.get(1); + } else if (responseSchema != null) { + cp = fromProperty("response", responseSchema); + this.processCodegenProperty(cp, "", null); + } + + op.returnBaseTypeAlternate = null; + if (cp != null) { + op.returnTypeAlternate = cp.dataTypeAlternate; + op.returnTypeIsModel = cp.isModel; + op.returnTypeIsArray = cp.isArray; + if (cp.isArray) { + if (cp.items.isModel) { + op.returnTypeSupportsEntities = true; + op.returnBaseTypeAlternate = cp.items.dataType + "Record"; + } else if (cp.items.allowableValues != null) { + op.returnBaseTypeAlternate = cp.items.dataType; + } + } else if (cp.isModel) { + op.returnTypeSupportsEntities = true; + op.returnBaseTypeAlternate = cp.dataTypeAlternate; + } else if (cp.allowableValues != null) { + op.returnBaseTypeAlternate = cp.dataTypeAlternate; + } + + } + } + } + } + + return op; + } + + @Override + public String escapeReservedWord(String name) { + if (this.getSagasAndRecords()) { + if (this.reservedWordsMappings().containsKey(name)) { + return this.reservedWordsMappings().get(name); + } + return "_" + name; + } else { + return super.escapeReservedWord(name); + } + } + @Override public Map postProcessOperationsWithModels(Map operations, List allModels) { // Add supporting file only if we plan to generate files in /apis if (operations.size() > 0 && !addedApiIndex) { addedApiIndex = true; supportingFiles.add(new SupportingFile("apis.index.mustache", apiPackage().replace('.', File.separatorChar), "index.ts")); + if (this.getSagasAndRecords()) { + supportingFiles.add(new SupportingFile("sagaApiManager.mustache", apiPackage().replace('.', File.separatorChar), "SagaApiManager.ts")); + supportingFiles.add(new SupportingFile("allSagas.mustache", apiPackage().replace('.', File.separatorChar), "allSagas.ts")); + } } // Add supporting file only if we plan to generate files in /models @@ -269,17 +573,169 @@ public class TypeScriptFetchClientCodegen extends AbstractTypeScriptClientCodege } this.addOperationModelImportInfomation(operations); - this.updateOperationParameterEnumInformation(operations); + this.updateOperationParameterForEnum(operations); + if (this.getSagasAndRecords()) { + this.updateOperationParameterForSagaAndRecords(operations); + } this.addOperationObjectResponseInformation(operations); this.addOperationPrefixParameterInterfacesInformation(operations); this.escapeOperationIds(operations); return operations; } + @Override + public Map postProcessSupportingFileData(Map objs) { + Map parentObjs = super.postProcessSupportingFileData(objs); + + parentObjs.put("useSagaAndRecords", this.getSagasAndRecords()); + + return parentObjs; + } + + private ExtendedCodegenModel processCodeGenModel(ExtendedCodegenModel cm) { + if (this.getSagasAndRecords()) { + Object xEntityId = cm.vendorExtensions.get(X_ENTITY_ID); + if (xEntityId == null && this.getInferEntityFromUniqueIdWithName() != null) { + xEntityId = this.getInferEntityFromUniqueIdWithName(); + } + Object vendorKeepAsJSObject = cm.vendorExtensions.get(X_KEEP_AS_JS_OBJECT); + String[] propertiesToKeepAsJSObject = null; + if (vendorKeepAsJSObject instanceof String) { + propertiesToKeepAsJSObject = ((String) vendorKeepAsJSObject).split(","); + } + + for (CodegenProperty cpVar : cm.vars) { + ExtendedCodegenProperty var = (ExtendedCodegenProperty) cpVar; + if (propertiesToKeepAsJSObject != null && Arrays.asList(propertiesToKeepAsJSObject).contains(var.name)) { + var.keepAsJSObject = true; + } + boolean parentIsEntity = this.processCodegenProperty(var, cm.classname, xEntityId); + if (parentIsEntity) { + cm.isEntity = true; + } + } + + Object returnPassthrough = cm.vendorExtensions.get(X_OPERATION_RETURN_PASSTHROUGH); + if (returnPassthrough instanceof String) { + if (((String) returnPassthrough).isEmpty()) { + cm.hasReturnPassthroughVoid = true; + cm.returnPassthrough = null; + } else { + boolean foundMatch = false; + for (CodegenProperty var : cm.vars) { + if (var.name.equals(returnPassthrough)) { + foundMatch = true; + break; + } + } + if (foundMatch) { + cm.returnPassthrough = (String) returnPassthrough; + } else { // no match, treat as if empty. + cm.hasReturnPassthroughVoid = true; + cm.returnPassthrough = null; + } + } + } else if (this.getDetectPassthroughModelsWithSuffixAndField() != null && cm.name.length() > this.getPassthroughSuffix().length() && cm.name.substring(cm.name.length() - this.getPassthroughSuffix().length()).equals(this.getPassthroughSuffix())) { + boolean foundMatch = false; + for (CodegenProperty var : cm.vars) { + if (var.name.equals(this.getPassthroughField())) { + foundMatch = true; + break; + } + } + if (foundMatch) { + cm.returnPassthrough = this.getPassthroughField(); + } else { // no match, treat as if empty. + cm.hasReturnPassthroughVoid = true; + cm.returnPassthrough = null; + } + } + } else { + for (CodegenProperty cpVar : cm.vars) { + ExtendedCodegenProperty var = (ExtendedCodegenProperty) cpVar; + this.processCodegenProperty(var, cm.classname, null); + } + } + + if (cm.parent != null) { + for (CodegenProperty cpVar : cm.allVars) { + ExtendedCodegenProperty var = (ExtendedCodegenProperty) cpVar; + + if (Boolean.TRUE.equals(var.isEnum)) { + var.datatypeWithEnum = var.datatypeWithEnum + .replace(var.enumName, cm.classname + var.enumName); + } + } + } + if (!cm.oneOf.isEmpty()) { + // For oneOfs only import $refs within the oneOf + TreeSet oneOfRefs = new TreeSet<>(); + for (String im : cm.imports) { + if (cm.oneOf.contains(im)) { + oneOfRefs.add(im); + } + } + cm.imports = oneOfRefs; + } + return cm; + } + + private boolean processCodegenProperty(ExtendedCodegenProperty var, String parentClassName, Object xEntityId) { + // name enum with model name, e.g. StatusEnum => PetStatusEnum + if (Boolean.TRUE.equals(var.isEnum)) { + // behaviour for enum names is specific for Typescript Fetch, not using namespaces + var.datatypeWithEnum = var.datatypeWithEnum.replace(var.enumName, parentClassName + var.enumName); + + // need to post-process defaultValue, was computed with previous var.datatypeWithEnum + if (var.defaultValue != null && !var.defaultValue.equals("undefined")) { + int dotPos = var.defaultValue.indexOf("."); + if (dotPos != -1) { + var.defaultValue = var.datatypeWithEnum + var.defaultValue.substring(dotPos); + } + } + } + + boolean parentIsEntity = false; + if (this.getSagasAndRecords()) { + if (var.vendorExtensions.get(X_IS_UNIQUE_ID) instanceof Boolean) { + var.isUniqueId = Boolean.TRUE.equals(var.vendorExtensions.get(X_IS_UNIQUE_ID)); + } else if (this.getInferUniqueIdFromNameSuffix() && (var.isArray && "number".equals(var.items.dataType)) || ("number".equals(var.dataType))) { + var.isUniqueId = this.isUniqueIdAccordingToNameSuffix(var.name); + } + if (var.isUniqueId && xEntityId != null && xEntityId.equals(var.name)) { + parentIsEntity = true; + } + + var.dataTypeAlternate = var.dataType; + if (var.isArray) { + var.dataTypeAlternate = var.dataType.replace("Array<", "List<"); + if (var.items.isModel) { + String itemsDataType = var.items.dataType + "Record"; + var.dataTypeAlternate = var.dataTypeAlternate.replace(var.items.dataType, itemsDataType); + } else if (var.items.isEnum) { + var.dataTypeAlternate = var.dataTypeAlternate.replace(var.items.dataType, var.items.datatypeWithEnum); + } + if (var.isUniqueId) { + var.dataTypeAlternate = var.dataTypeAlternate.replace("number", "string"); + } + } else if (var.isEnum) { + var.dataTypeAlternate = var.datatypeWithEnum; + } else if (var.isModel) { + var.dataTypeAlternate = var.dataType + "Record"; + } else if (var.isUniqueId) { + var.dataTypeAlternate = "string"; + } + if (var.defaultValue == null || var.defaultValue.equals("undefined")) { + this.autoSetDefaultValueForProperty(var); + } + } + return parentIsEntity; + } + private void escapeOperationIds(Map operations) { Map _operations = (Map) operations.get("operations"); - List operationList = (List) _operations.get("operation"); - for (CodegenOperation op : operationList) { + List operationList = (List) _operations.get("operation"); + for (ExtendedCodegenOperation op : operationList) { String param = op.operationIdCamelCase + "Request"; if (op.imports.contains(param)) { // we import a model with the same name as the generated operation, escape it @@ -295,19 +751,44 @@ public class TypeScriptFetchClientCodegen extends AbstractTypeScriptClientCodege // The api template uses this infomation to import all the required // models for a given operation. List> imports = (List>) operations.get("imports"); + List existingRecordClassNames = new ArrayList(); + List existingClassNames = new ArrayList(); for (Map im : imports) { - im.put("className", im.get("import").toString().replace(modelPackage() + ".", "")); + String className = im.get("import").toString().replace(modelPackage() + ".", ""); + existingClassNames.add(className); + existingRecordClassNames.add(className + "Record"); + im.put("className", className); + } + + if (this.getSagasAndRecords()) { + Map _operations = (Map) operations.get("operations"); + List operationList = (List) _operations.get("operation"); + Set additionalPassthroughImports = new TreeSet(); + for (ExtendedCodegenOperation op : operationList) { + if (op.returnPassthrough != null && op.returnBaseTypeAlternate instanceof String) { + if (op.returnTypeSupportsEntities && !existingRecordClassNames.contains(op.returnBaseTypeAlternate)) { + additionalPassthroughImports.add(op.returnBaseTypeAlternate); + } else if (!op.returnTypeSupportsEntities && !existingClassNames.contains(op.returnBaseTypeAlternate)) { + additionalPassthroughImports.add(op.returnBaseTypeAlternate); + } + } + } + operations.put("passthroughImports", additionalPassthroughImports); + operations.put("hasPassthroughImports", additionalPassthroughImports.size() > 0); } } - private void updateOperationParameterEnumInformation(Map operations) { + private void updateOperationParameterForEnum(Map operations) { // This method will add extra infomation as to whether or not we have enums and // update their names with the operation.id prefixed. + // It will also set the uniqueId status if provided. Map _operations = (Map) operations.get("operations"); - List operationList = (List) _operations.get("operation"); + List operationList = (List) _operations.get("operation"); boolean hasEnum = false; - for (CodegenOperation op : operationList) { - for (CodegenParameter param : op.allParams) { + for (ExtendedCodegenOperation op : operationList) { + for (CodegenParameter cpParam : op.allParams) { + ExtendedCodegenParameter param = (ExtendedCodegenParameter) cpParam; + if (Boolean.TRUE.equals(param.isEnum)) { hasEnum = true; param.datatypeWithEnum = param.datatypeWithEnum @@ -319,14 +800,55 @@ public class TypeScriptFetchClientCodegen extends AbstractTypeScriptClientCodege operations.put("hasEnums", hasEnum); } + private void updateOperationParameterForSagaAndRecords(Map operations) { + // This method will add extra infomation as to whether or not we have enums and + // update their names with the operation.id prefixed. + // It will also set the uniqueId status if provided. + Map _operations = (Map) operations.get("operations"); + List operationList = (List) _operations.get("operation"); + for (ExtendedCodegenOperation op : operationList) { + for (CodegenParameter cpParam : op.allParams) { + ExtendedCodegenParameter param = (ExtendedCodegenParameter) cpParam; + + if (param.vendorExtensions.get(X_IS_UNIQUE_ID) instanceof Boolean) { + param.isUniqueId = Boolean.TRUE.equals(param.vendorExtensions.get(X_IS_UNIQUE_ID)); + } else if (this.getInferUniqueIdFromNameSuffix() && (param.isArray && "number".equals(param.items.dataType)) || ("number".equals(param.dataType))) { + param.isUniqueId = this.isUniqueIdAccordingToNameSuffix(param.paramName); + } + + param.dataTypeAlternate = param.dataType; + if (param.isArray) { + if (param.items.isModel) { + String itemsDataType = param.items.dataType + "Record"; + param.dataTypeAlternate = param.dataType.replace("Array<", "List<"); + param.dataTypeAlternate = param.dataTypeAlternate.replace(param.items.dataType, itemsDataType); + } else if (param.items.isEnum) { + param.dataTypeAlternate = param.datatypeWithEnum.replace("Array<", "List<"); + } else { + param.dataTypeAlternate = param.dataType.replace("Array<", "List<"); + } + if (param.isUniqueId) { + param.dataTypeAlternate = param.dataTypeAlternate.replace("number", "string"); + } + } else if (param.isEnum) { + param.dataTypeAlternate = param.datatypeWithEnum; + } else if (param.isModel) { + param.dataTypeAlternate = param.dataType + "Record"; + } else if (param.isUniqueId) { + param.dataTypeAlternate = "string"; + } + } + } + } + private void addOperationObjectResponseInformation(Map operations) { // This method will modify the infomation on the operations' return type. // The api template uses this infomation to know when to return a text // response for a given simple response operation. Map _operations = (Map) operations.get("operations"); - List operationList = (List) _operations.get("operation"); - for (CodegenOperation op : operationList) { - if("object".equals(op.returnType)) { + List operationList = (List) _operations.get("operation"); + for (ExtendedCodegenOperation op : operationList) { + if ("object".equals(op.returnType)) { op.isMap = true; op.returnSimpleType = false; } @@ -369,6 +891,11 @@ public class TypeScriptFetchClientCodegen extends AbstractTypeScriptClientCodege this.reservedWords.add("Index"); } + private void addExtraReservedWordsForSagasAndRecords() { + // immutablejs Records have potentially many reserved words. Adding only strict minimum for now. + this.reservedWords.add("entries"); + } + private boolean getUseSingleRequestParameter() { return useSingleRequestParameter; } @@ -384,4 +911,491 @@ public class TypeScriptFetchClientCodegen extends AbstractTypeScriptClientCodege private void setPrefixParameterInterfaces(boolean prefixParameterInterfaces) { this.prefixParameterInterfaces = prefixParameterInterfaces; } + + class ExtendedCodegenParameter extends CodegenParameter { + public String dataTypeAlternate; + public boolean isUniqueId; // this parameter represents a unique id (x-isUniqueId: true) + + public ExtendedCodegenParameter(CodegenParameter cp) { + super(); + + this.isFormParam = cp.isFormParam; + this.isQueryParam = cp.isQueryParam; + this.isPathParam = cp.isPathParam; + this.isHeaderParam = cp.isHeaderParam; + this.isCookieParam = cp.isCookieParam; + this.isBodyParam = cp.isBodyParam; + this.isContainer = cp.isContainer; + this.isCollectionFormatMulti = cp.isCollectionFormatMulti; + this.isPrimitiveType = cp.isPrimitiveType; + this.isModel = cp.isModel; + this.isExplode = cp.isExplode; + this.baseName = cp.baseName; + this.paramName = cp.paramName; + this.dataType = cp.dataType; + this.datatypeWithEnum = cp.datatypeWithEnum; + this.dataFormat = cp.dataFormat; + this.contentType = cp.contentType; + this.collectionFormat = cp.collectionFormat; + this.description = cp.description; + this.unescapedDescription = cp.unescapedDescription; + this.baseType = cp.baseType; + this.defaultValue = cp.defaultValue; + this.enumName = cp.enumName; + this.style = cp.style; + this.nameInLowerCase = cp.nameInLowerCase; + this.example = cp.example; + this.jsonSchema = cp.jsonSchema; + this.isString = cp.isString; + this.isNumeric = cp.isNumeric; + this.isInteger = cp.isInteger; + this.isLong = cp.isLong; + this.isNumber = cp.isNumber; + this.isFloat = cp.isFloat; + this.isDouble = cp.isDouble; + this.isDecimal = cp.isDecimal; + this.isByteArray = cp.isByteArray; + this.isBinary = cp.isBinary; + this.isBoolean = cp.isBoolean; + this.isDate = cp.isDate; + this.isDateTime = cp.isDateTime; + this.isUuid = cp.isUuid; + this.isUri = cp.isUri; + this.isEmail = cp.isEmail; + this.isFreeFormObject = cp.isFreeFormObject; + this.isAnyType = cp.isAnyType; + this.isArray = cp.isArray; + this.isMap = cp.isMap; + this.isFile = cp.isFile; + this.isEnum = cp.isEnum; + this._enum = cp._enum; + this.allowableValues = cp.allowableValues; + this.items = cp.items; + this.additionalProperties = cp.additionalProperties; + this.vars = cp.vars; + this.requiredVars = cp.requiredVars; + this.mostInnerItems = cp.mostInnerItems; + this.vendorExtensions = cp.vendorExtensions; + this.hasValidation = cp.hasValidation; + this.isNullable = cp.isNullable; + this.required = cp.required; + this.maximum = cp.maximum; + this.exclusiveMaximum = cp.exclusiveMaximum; + this.minimum = cp.minimum; + this.exclusiveMinimum = cp.exclusiveMinimum; + this.maxLength = cp.maxLength; + this.minLength = cp.minLength; + this.pattern = cp.pattern; + this.maxItems = cp.maxItems; + this.minItems = cp.minItems; + this.uniqueItems = cp.uniqueItems; + this.multipleOf = cp.multipleOf; + this.setMaxProperties(cp.getMaxProperties()); + this.setMinProperties(cp.getMinProperties()); + } + + @Override + public ExtendedCodegenParameter copy() { + CodegenParameter superCopy = super.copy(); + ExtendedCodegenParameter output = new ExtendedCodegenParameter(superCopy); + output.dataTypeAlternate = this.dataTypeAlternate; + output.isUniqueId = this.isUniqueId; + return output; + } + + @Override + public boolean equals(Object o) { + boolean result = super.equals(o); + ExtendedCodegenParameter that = (ExtendedCodegenParameter) o; + return result && + isUniqueId == that.isUniqueId && + Objects.equals(dataTypeAlternate, that.dataTypeAlternate); + } + + @Override + public int hashCode() { + int superHash = super.hashCode(); + return Objects.hash(superHash, dataTypeAlternate, isUniqueId); + } + + @Override + public String toString() { + String superString = super.toString(); + final StringBuilder sb = new StringBuilder(superString); + sb.append(", isUniqueId=").append(isUniqueId); + sb.append(", dataTypeAlternate='").append(dataTypeAlternate).append('\''); + return sb.toString(); + } + } + + class ExtendedCodegenProperty extends CodegenProperty { + public String dataTypeAlternate; + public boolean isEntity; //Is a model containing an "id" property marked as isUniqueId and which matches the 'x-entityId' value. + public boolean isUniqueId; // The property represents a unique id (x-isUniqueId: true) + public boolean keepAsJSObject; + public boolean isReservedRecordField; + + public ExtendedCodegenProperty(CodegenProperty cp) { + super(); + + this.openApiType = openApiType; + this.baseName = cp.baseName; + this.complexType = cp.complexType; + this.getter = cp.getter; + this.setter = cp.setter; + this.description = cp.description; + this.dataType = cp.dataType; + this.datatypeWithEnum = cp.datatypeWithEnum; + this.dataFormat = cp.dataFormat; + this.name = cp.name; + this.min = cp.min; + this.max = cp.max; + this.defaultValue = cp.defaultValue; + this.defaultValueWithParam = cp.defaultValueWithParam; + this.baseType = cp.baseType; + this.containerType = cp.containerType; + this.title = cp.title; + this.unescapedDescription = cp.unescapedDescription; + this.maxLength = cp.maxLength; + this.minLength = cp.minLength; + this.pattern = cp.pattern; + this.example = cp.example; + this.jsonSchema = cp.jsonSchema; + this.minimum = cp.minimum; + this.maximum = cp.maximum; + this.multipleOf = cp.multipleOf; + this.exclusiveMinimum = cp.exclusiveMinimum; + this.exclusiveMaximum = cp.exclusiveMaximum; + this.required = cp.required; + this.deprecated = cp.deprecated; + this.hasMoreNonReadOnly = cp.hasMoreNonReadOnly; + this.isPrimitiveType = cp.isPrimitiveType; + this.isModel = cp.isModel; + this.isContainer = cp.isContainer; + this.isString = cp.isString; + this.isNumeric = cp.isNumeric; + this.isInteger = cp.isInteger; + this.isLong = cp.isLong; + this.isNumber = cp.isNumber; + this.isFloat = cp.isFloat; + this.isDouble = cp.isDouble; + this.isDecimal = cp.isDecimal; + this.isByteArray = cp.isByteArray; + this.isBinary = cp.isBinary; + this.isFile = cp.isFile; + this.isBoolean = cp.isBoolean; + this.isDate = cp.isDate; // full-date notation as defined by RFC 3339, section 5.6, for example, 2017-07-21 + this.isDateTime = cp.isDateTime; // the date-time notation as defined by RFC 3339, section 5.6, for example, 2017-07-21T17:32:28Z + this.isUuid = cp.isUuid; + this.isUri = cp.isUri; + this.isEmail = cp.isEmail; + this.isFreeFormObject = cp.isFreeFormObject; + this.isAnyType = cp.isAnyType; + this.isArray = cp.isArray; + this.isMap = cp.isMap; + this.isEnum = cp.isEnum; + this.isReadOnly = cp.isReadOnly; + this.isWriteOnly = cp.isWriteOnly; + this.isNullable = cp.isNullable; + this.isSelfReference = cp.isSelfReference; + this.isCircularReference = cp.isCircularReference; + this.isDiscriminator = cp.isDiscriminator; + this._enum = cp._enum; + this.allowableValues = cp.allowableValues; + this.items = cp.items; + this.additionalProperties = cp.additionalProperties; + this.vars = cp.vars; + this.requiredVars = cp.requiredVars; + this.mostInnerItems = cp.mostInnerItems; + this.vendorExtensions = cp.vendorExtensions; + this.hasValidation = cp.hasValidation; + this.isInherited = cp.isInherited; + this.discriminatorValue = cp.discriminatorValue; + this.nameInLowerCase = cp.nameInLowerCase; + this.nameInCamelCase = cp.nameInCamelCase; + this.nameInSnakeCase = cp.nameInSnakeCase; + this.enumName = cp.enumName; + this.maxItems = cp.maxItems; + this.minItems = cp.minItems; + this.setMaxProperties(cp.getMaxProperties()); + this.setMinProperties(cp.getMinProperties()); + this.setUniqueItems(cp.getUniqueItems()); + this.isXmlAttribute = cp.isXmlAttribute; + this.xmlPrefix = cp.xmlPrefix; + this.xmlName = cp.xmlName; + this.xmlNamespace = cp.xmlNamespace; + this.isXmlWrapped = cp.isXmlWrapped; + } + + @Override + public boolean equals(Object o) { + boolean result = super.equals(o); + ExtendedCodegenProperty that = (ExtendedCodegenProperty) o; + return result && + isEntity == that.isEntity && + isUniqueId == that.isUniqueId && + keepAsJSObject == that.keepAsJSObject && + isReservedRecordField == that.isReservedRecordField && + Objects.equals(dataTypeAlternate, that.dataTypeAlternate); + } + + @Override + public int hashCode() { + int superHash = super.hashCode(); + return Objects.hash(superHash, dataTypeAlternate, isEntity, isUniqueId, keepAsJSObject, isReservedRecordField); + } + + @Override + public String toString() { + String superString = super.toString(); + final StringBuilder sb = new StringBuilder(superString); + sb.append(", dataTypeAlternate='").append(dataTypeAlternate).append('\''); + sb.append(", isEntity=").append(isEntity); + sb.append(", isUniqueId=").append(isUniqueId); + sb.append(", keepAsJSObject=").append(keepAsJSObject); + sb.append(", isReservedRecordField=").append(isReservedRecordField); + return sb.toString(); + } + } + + class ExtendedCodegenOperation extends CodegenOperation { + boolean hasReturnPassthroughVoid, returnTypeSupportsEntities, returnTypeIsModel, returnTypeIsArray; + String returnTypeAlternate, returnBaseTypeAlternate, returnPassthrough; + + public ExtendedCodegenOperation(CodegenOperation o) { + super(); + + this.responseHeaders.addAll(o.responseHeaders); + this.hasAuthMethods = o.hasAuthMethods; + this.hasConsumes = o.hasConsumes; + this.hasProduces = o.hasProduces; + this.hasParams = o.hasParams; + this.hasOptionalParams = o.hasOptionalParams; + this.hasRequiredParams = o.hasRequiredParams; + this.returnTypeIsPrimitive = o.returnTypeIsPrimitive; + this.returnSimpleType = o.returnSimpleType; + this.subresourceOperation = o.subresourceOperation; + this.isMap = o.isMap; + this.isArray = o.isArray; + this.isMultipart = o.isMultipart; + this.isResponseBinary = o.isResponseBinary; + this.isResponseFile = o.isResponseFile; + this.hasReference = o.hasReference; + this.isRestfulIndex = o.isRestfulIndex; + this.isRestfulShow = o.isRestfulShow; + this.isRestfulCreate = o.isRestfulCreate; + this.isRestfulUpdate = o.isRestfulUpdate; + this.isRestfulDestroy = o.isRestfulDestroy; + this.isRestful = o.isRestful; + this.isDeprecated = o.isDeprecated; + this.isCallbackRequest = o.isCallbackRequest; + this.uniqueItems = o.uniqueItems; + this.path = o.path; + this.operationId = o.operationId; + this.returnType = o.returnType; + this.returnFormat = o.returnFormat; + this.httpMethod = o.httpMethod; + this.returnBaseType = o.returnBaseType; + this.returnContainer = o.returnContainer; + this.summary = o.summary; + this.unescapedNotes = o.unescapedNotes; + this.notes = o.notes; + this.baseName = o.baseName; + this.defaultResponse = o.defaultResponse; + this.discriminator = o.discriminator; + this.consumes = o.consumes; + this.produces = o.produces; + this.prioritizedContentTypes = o.prioritizedContentTypes; + this.servers = o.servers; + this.bodyParam = o.bodyParam; + this.allParams = o.allParams; + this.bodyParams = o.bodyParams; + this.pathParams = o.pathParams; + this.queryParams = o.queryParams; + this.headerParams = o.headerParams; + this.formParams = o.formParams; + this.cookieParams = o.cookieParams; + this.requiredParams = o.requiredParams; + this.optionalParams = o.optionalParams; + this.authMethods = o.authMethods; + this.tags = o.tags; + this.responses = o.responses; + this.callbacks = o.callbacks; + this.imports = o.imports; + this.examples = o.examples; + this.requestBodyExamples = o.requestBodyExamples; + this.externalDocs = o.externalDocs; + this.vendorExtensions = o.vendorExtensions; + this.nickname = o.nickname; + this.operationIdOriginal = o.operationIdOriginal; + this.operationIdLowerCase = o.operationIdLowerCase; + this.operationIdCamelCase = o.operationIdCamelCase; + this.operationIdSnakeCase = o.operationIdSnakeCase; + } + + @Override + public boolean equals(Object o) { + boolean result = super.equals(o); + ExtendedCodegenOperation that = (ExtendedCodegenOperation) o; + return result && + hasReturnPassthroughVoid == that.hasReturnPassthroughVoid && + returnTypeSupportsEntities == that.returnTypeSupportsEntities && + returnTypeIsArray == that.returnTypeIsArray && + returnTypeIsModel == that.returnTypeIsModel && + Objects.equals(returnTypeAlternate, that.returnTypeAlternate) && + Objects.equals(returnBaseTypeAlternate, that.returnBaseTypeAlternate) && + Objects.equals(returnPassthrough, that.returnPassthrough); + } + + @Override + public int hashCode() { + int superHash = super.hashCode(); + return Objects.hash(superHash, returnPassthrough, hasReturnPassthroughVoid, returnTypeSupportsEntities, returnTypeIsArray, returnTypeIsModel, returnTypeAlternate, returnBaseTypeAlternate); + } + + @Override + public String toString() { + String superString = super.toString(); + final StringBuilder sb = new StringBuilder(superString); + sb.append(", hasReturnPassthroughVoid=").append(hasReturnPassthroughVoid); + sb.append(", returnTypeSupportsEntities=").append(returnTypeSupportsEntities); + sb.append(", returnTypeIsArray=").append(returnTypeIsArray); + sb.append(", returnTypeIsModel=").append(returnTypeIsModel); + sb.append(", returnTypeAlternate='").append(returnTypeAlternate).append('\''); + sb.append(", returnBaseTypeAlternate='").append(returnBaseTypeAlternate).append('\''); + sb.append(", returnPassthrough='").append(returnPassthrough).append('\''); + return sb.toString(); + } + } + + class ExtendedCodegenModel extends CodegenModel { + public Set modelImports = new TreeSet(); + public boolean isEntity; // Is a model containing an "id" property marked as isUniqueId + public String returnPassthrough; + public boolean hasReturnPassthroughVoid; + + public ExtendedCodegenModel(CodegenModel cm) { + super(); + + this.parent = cm.parent; + this.parentSchema = cm.parentSchema; + this.interfaces = cm.interfaces; + this.allParents = cm.allParents; + this.parentModel = cm.parentModel; + this.interfaceModels = cm.interfaceModels; + this.children = cm.children; + this.anyOf = cm.anyOf; + this.oneOf = cm.oneOf; + this.allOf = cm.allOf; + this.name = cm.name; + this.classname = cm.classname; + this.title = cm.title; + this.description = cm.description; + this.classVarName = cm.classVarName; + this.modelJson = cm.modelJson; + this.dataType = cm.dataType; + this.xmlPrefix = cm.xmlPrefix; + this.xmlNamespace = cm.xmlNamespace; + this.xmlName = cm.xmlName; + this.classFilename = cm.classFilename; + this.unescapedDescription = cm.unescapedDescription; + this.discriminator = cm.discriminator; + this.defaultValue = cm.defaultValue; + this.arrayModelType = cm.arrayModelType; + this.isAlias = cm.isAlias; + this.isString = cm.isString; + this.isInteger = cm.isInteger; + this.isLong = cm.isLong; + this.isNumber = cm.isNumber; + this.isNumeric = cm.isNumeric; + this.isFloat = cm.isFloat; + this.isDouble = cm.isDouble; + this.isDate = cm.isDate; + this.isDateTime = cm.isDateTime; + this.vars = cm.vars; + this.allVars = cm.allVars; + this.requiredVars = cm.requiredVars; + this.optionalVars = cm.optionalVars; + this.readOnlyVars = cm.readOnlyVars; + this.readWriteVars = cm.readWriteVars; + this.parentVars = cm.parentVars; + this.allowableValues = cm.allowableValues; + this.mandatory = cm.mandatory; + this.allMandatory = cm.allMandatory; + this.imports = cm.imports; + this.hasVars = cm.hasVars; + this.emptyVars = cm.emptyVars; + this.hasMoreModels = cm.hasMoreModels; + this.hasEnums = cm.hasEnums; + this.isEnum = cm.isEnum; + this.isNullable = cm.isNullable; + this.hasRequired = cm.hasRequired; + this.hasOptional = cm.hasOptional; + this.isArray = cm.isArray; + this.hasChildren = cm.hasChildren; + this.isMap = cm.isMap; + this.isDeprecated = cm.isDeprecated; + this.hasOnlyReadOnly = cm.hasOnlyReadOnly; + this.externalDocumentation = cm.externalDocumentation; + + this.vendorExtensions = cm.vendorExtensions; + this.additionalPropertiesType = cm.additionalPropertiesType; + this.isAdditionalPropertiesTrue = cm.isAdditionalPropertiesTrue; + this.setMaxProperties(cm.getMaxProperties()); + this.setMinProperties(cm.getMinProperties()); + this.setUniqueItems(cm.getUniqueItems()); + this.setMaxItems(cm.getMaxItems()); + this.setMinItems(cm.getMinItems()); + this.setMaxLength(cm.getMaxLength()); + this.setMinLength(cm.getMinLength()); + this.setExclusiveMinimum(cm.getExclusiveMinimum()); + this.setExclusiveMaximum(cm.getExclusiveMaximum()); + this.setMinimum(cm.getMinimum()); + this.setMaximum(cm.getMaximum()); + this.setPattern(cm.getPattern()); + this.setMultipleOf(cm.getMultipleOf()); + this.setItems(cm.getItems()); + this.setAdditionalProperties(cm.getAdditionalProperties()); + this.setIsModel(cm.getIsModel()); + } + + public Set getModelImports() { + return modelImports; + } + + public void setModelImports(Set modelImports) { + this.modelImports = modelImports; + } + + @Override + public boolean equals(Object o) { + boolean result = super.equals(o); + ExtendedCodegenModel that = (ExtendedCodegenModel) o; + return result && + isEntity == that.isEntity && + hasReturnPassthroughVoid == that.hasReturnPassthroughVoid && + Objects.equals(returnPassthrough, that.returnPassthrough) && + Objects.equals(modelImports, that.modelImports); + + } + + @Override + public int hashCode() { + int superHash = super.hashCode(); + return Objects.hash(superHash, isEntity, returnPassthrough, hasReturnPassthroughVoid, getModelImports()); + } + + @Override + public String toString() { + String superString = super.toString(); + final StringBuilder sb = new StringBuilder(superString); + sb.append(", modelImports=").append(modelImports); + sb.append(", isEntity=").append(isEntity); + sb.append(", returnPassthrough='").append(returnPassthrough).append('\''); + sb.append(", hasReturnPassthroughVoid=").append(hasReturnPassthroughVoid); + return sb.toString(); + } + + } + } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptRxjsClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptRxjsClientCodegen.java index bdecf7febe1..9a15de44bd7 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptRxjsClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptRxjsClientCodegen.java @@ -271,7 +271,7 @@ public class TypeScriptRxjsClientCodegen extends AbstractTypeScriptClientCodegen if(this.reservedParamNames.contains(p.paramName)){ paramNameAlternative = p.paramName + "Alias"; - LOGGER.info("param: "+p.paramName+" isReserved ––> "+paramNameAlternative); + LOGGER.info("param: {} isReserved ––> {}", p.paramName, paramNameAlternative); } setParamNameAlternative(p, p.paramName, paramNameAlternative); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/WsdlSchemaCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/WsdlSchemaCodegen.java new file mode 100644 index 00000000000..7bee8aee42a --- /dev/null +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/WsdlSchemaCodegen.java @@ -0,0 +1,287 @@ +/* + * 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.languages; + +import io.swagger.v3.oas.models.OpenAPI; +import io.swagger.v3.oas.models.info.Info; + +import java.io.File; +import java.text.Normalizer; +import java.util.List; +import java.util.ArrayList; +import java.util.Locale; +import java.util.Map; + +import org.openapitools.codegen.CliOption; +import org.openapitools.codegen.CodegenConfig; +import org.openapitools.codegen.CodegenModel; +import org.openapitools.codegen.CodegenOperation; +import org.openapitools.codegen.CodegenParameter; +import org.openapitools.codegen.CodegenProperty; +import org.openapitools.codegen.CodegenType; +import org.openapitools.codegen.DefaultCodegen; +import org.openapitools.codegen.meta.GeneratorMetadata; +import org.openapitools.codegen.meta.Stability; +import org.openapitools.codegen.meta.features.*; +import org.openapitools.codegen.SupportingFile; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class WsdlSchemaCodegen extends DefaultCodegen implements CodegenConfig { + public static final String PROJECT_NAME = "projectName"; + + static final Logger LOGGER = LoggerFactory.getLogger(WsdlSchemaCodegen.class); + + public CodegenType getTag() { + return CodegenType.SCHEMA; + } + + public String getName() { + return "wsdl-schema"; + } + + public String getHelp() { + return "Generates WSDL files."; + } + + public WsdlSchemaCodegen() { + super(); + + generatorMetadata = GeneratorMetadata.newBuilder(generatorMetadata) + .stability(Stability.BETA) + .build(); + + outputFolder = "generated-code" + File.separator + "wsdl-schema"; + embeddedTemplateDir = templateDir = "wsdl-schema"; + apiPackage = "Apis"; + modelPackage = "Models"; + + cliOptions.add(new CliOption("hostname", "the hostname of the service")); + cliOptions.add(new CliOption("soapPath", "basepath of the soap services")); + cliOptions.add(new CliOption("serviceName", "service name for the wsdl")); + + additionalProperties.put("hostname", "localhost"); + additionalProperties.put("soapPath", "soap"); + additionalProperties.put("serviceName", "ServiceV1"); + + supportingFiles.add(new SupportingFile("wsdl-converter.mustache", "", "service.wsdl")); + supportingFiles.add(new SupportingFile("jaxb-customization.mustache", "", + "jaxb-customization.xml")); + } + + public void preprocessOpenAPI(OpenAPI openAPI) { + Info info = openAPI.getInfo(); + + String title = info.getTitle(); + String description = info.getDescription(); + + info.setDescription(this.processOpenapiSpecDescription(description)); + info.setTitle(this.escapeTitle(title)); + } + + private String escapeTitle(String title) { + // strip umlauts etc. + final String normalizedTitle = Normalizer.normalize(title, Normalizer.Form.NFD) + .replaceAll("[^\\p{ASCII}]", ""); + return super.escapeUnsafeCharacters(normalizedTitle); + } + + public String processOpenapiSpecDescription(String description) { + if (description != null) { + return description.replaceAll("\\s+", " "); + } else { + return "No description provided"; + } + } + + @Override + public Map postProcessOperationsWithModels(Map objs, + List allModels) { + + Map operations = (Map) objs.get("operations"); + List operationList = (List) operations.get("operation"); + for (CodegenOperation op : operationList) { + op.operationId = this.generateOperationId(op); + + // for xml compliant primitives, lowercase dataType of openapi + for (CodegenParameter param : op.allParams) { + Map paramVendorExtensions = param.vendorExtensions; + + normalizeDataType(param); + + // prevent default="null" in wsdl-tag if no default was specified for a param + if ("null".equals(param.defaultValue) || param.defaultValue == null) { + paramVendorExtensions.put("x-param-has-defaultvalue", false); + } else { + paramVendorExtensions.put("x-param-has-defaultvalue", true); + } + + // check if param has a minimum or maximum number or lenght + if (param.minimum != null + || param.maximum != null + || param.minLength != null + || param.maxLength != null) { + paramVendorExtensions.put("x-param-has-minormax", true); + } else { + paramVendorExtensions.put("x-param-has-minormax", false); + } + + // if param is enum, uppercase 'baseName' to have a reference to wsdl simpletype + if (param.isEnum) { + char[] c = param.baseName.toCharArray(); + c[0] = Character.toUpperCase(c[0]); + param.baseName = new String(c); + } + } + + for (CodegenParameter param : op.bodyParams) { + normalizeDataType(param); + } + for (CodegenParameter param : op.pathParams) { + normalizeDataType(param); + } + for (CodegenParameter param : op.queryParams) { + normalizeDataType(param); + } + for (CodegenParameter param : op.formParams) { + normalizeDataType(param); + } + } + + return objs; + } + + private void normalizeDataType(CodegenParameter param) { + if (param.isPrimitiveType) { + param.dataType = param.dataType.toLowerCase(Locale.getDefault()); + } + if (param.dataFormat != null && param.dataFormat.equalsIgnoreCase("date")) { + param.dataType = "date"; + } + if (param.dataFormat != null && param.dataFormat.equalsIgnoreCase("date-time")) { + param.dataType = "dateTime"; + } + if (param.dataFormat != null && param.dataFormat.equalsIgnoreCase("uuid")) { + param.dataType = "string"; + } + } + + @Override + public Map postProcessModels(Map objs) { + List models = (List) objs.get("models"); + + for (Object mo : models) { + Map mod = (Map) mo; + CodegenModel model = (CodegenModel) mod.get("model"); + Map modelVendorExtensions = model.getVendorExtensions(); + + /* check if model is a model with no properties + * Used in the mustache template to ensure that no complextype is created + * if model is just a schema with an enum defined in the openapi specification + */ + if (model.allowableValues != null) { + modelVendorExtensions.put("x-is-openapimodel-enum", true); + } else { + modelVendorExtensions.put("x-is-openapimodel-enum", false); + } + + for (CodegenProperty var : model.vars) { + Map propertyVendorExtensions = var.getVendorExtensions(); + + // lowercase basetypes if openapitype is string + if ("string".equals(var.openApiType)) { + char[] c = var.baseType.toCharArray(); + c[0] = Character.toLowerCase(c[0]); + var.baseType = new String(c); + } + // if string enum, uppercase 'name' to have a reference to wsdl simpletype + if (var.isEnum) { + char[] c = var.name.toCharArray(); + c[0] = Character.toUpperCase(c[0]); + var.name = new String(c); + } + + // prevent default="null" in wsdl-tag if no default was specified for a property + if ("null".equals(var.defaultValue) || var.defaultValue == null) { + propertyVendorExtensions.put("x-prop-has-defaultvalue", false); + } else { + propertyVendorExtensions.put("x-prop-has-defaultvalue", true); + } + + // check if model property has a minimum or maximum number or lenght + if (var.minimum != null + || var.maximum != null + || var.minLength != null + || var.maxLength != null) { + propertyVendorExtensions.put("x-prop-has-minormax", true); + } else { + propertyVendorExtensions.put("x-prop-has-minormax", false); + } + } + } + return super.postProcessModelsEnum(objs); + } + + public String generateOperationId(CodegenOperation op) { + String newOperationid = this.lowerCaseStringExceptFirstLetter(op.httpMethod); + String[] pathElements = op.path.split("/"); + List pathParameters = new ArrayList(); + + for (int i = 0; i < pathElements.length; i++) { + if (pathElements[i].contains("{")) { + pathParameters.add(pathElements[i]); + pathElements[i] = ""; + } + if (pathElements[i].length() > 0) { + newOperationid = newOperationid + this.lowerCaseStringExceptFirstLetter(pathElements[i]); + } + } + + if (pathParameters.size() > 0) { + for (int i = 0; i < pathParameters.size(); i++) { + String pathParameter = pathParameters.get(i); + pathParameter = this.lowerCaseStringExceptFirstLetter(pathParameter + .substring(1, pathParameter.length() - 1)); + if (i == 0) { + newOperationid = newOperationid + "By" + pathParameter; + } else { + newOperationid = newOperationid + "And" + pathParameter; + } + } + } + return newOperationid; + } + + public String lowerCaseStringExceptFirstLetter(String value) { + String newOperationid = value.toLowerCase(Locale.getDefault()); + return newOperationid.substring(0, 1).toUpperCase(Locale.getDefault()) + + newOperationid.substring(1); + } + + @Override + public String escapeQuotationMark(String input) { + // just return the original string + return input; + } + + @Override + public String escapeUnsafeCharacters(String input) { + // just return the original string + return input; + } +} diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/utils/JsonCacheImpl.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/utils/JsonCacheImpl.java index a08173dedb1..cb02519d507 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/utils/JsonCacheImpl.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/utils/JsonCacheImpl.java @@ -1602,23 +1602,23 @@ class JsonCacheImpl implements JsonCache.Root { destObject.set(fieldName, srcChild); // Mark the cache as dirty as we've added items from another file. isDirty = true; - LOGGER.info("Existing root property '" + fieldName - + "' has been overwritten by incoming data"); + LOGGER.info("Existing root property '{}' has been overwritten by incoming data", + fieldName); break; case MERGE_RECURSIVE: if (destChild.isContainerNode() && srcChild.isContainerNode()) merge((ContainerNode) destChild, (ContainerNode) srcChild); break; case KEEP_EXISTING: - LOGGER.info("Existing root property '" + fieldName - + "' will not be overwritten by incoming data"); + LOGGER.info("Existing root property '{}' will not be overwritten by incoming data", + fieldName); default: // Nothing to do. break; } } else { destObject.set(fieldName, srcChild); - LOGGER.info("New property '" + fieldName + "' has been added from incoming data"); + LOGGER.info("New property '{}' has been added from incoming data", fieldName); // Mark the cache as dirty as we've added items from another file. isDirty = true; } 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 0c85a67a2b3..81c1fbdba39 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 @@ -18,13 +18,13 @@ // Functions for enum {{enumName}} for {{{classname}}}_{{{operationId}}} static char* {{{operationId}}}_{{enumName}}_ToString({{projectName}}_{{operationId}}_{{baseName}}_e {{enumName}}){ - char *{{enumName}}Array[] = { "NULL"{{#allowableValues}}{{#enumVars}}, "{{{value}}}"{{/enumVars}}{{/allowableValues}} }; + char *{{enumName}}Array[] = { "NULL"{{#allowableValues}}{{#values}}, "{{.}}"{{/values}}{{/allowableValues}} }; return {{enumName}}Array[{{enumName}}]; } static {{projectName}}_{{operationId}}_{{baseName}}_e {{{operationId}}}_{{enumName}}_FromString(char* {{enumName}}){ int stringToReturn = 0; - char *{{enumName}}Array[] = { "NULL"{{#allowableValues}}{{#enumVars}}, "{{{value}}}"{{/enumVars}}{{/allowableValues}} }; + char *{{enumName}}Array[] = { "NULL"{{#allowableValues}}{{#values}}, "{{.}}"{{/values}}{{/allowableValues}} }; size_t sizeofArray = sizeof({{enumName}}Array) / sizeof({{enumName}}Array[0]); while(stringToReturn < sizeofArray) { if(strcmp({{enumName}}, {{enumName}}Array[stringToReturn]) == 0) { 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 e487cb0f474..6f4259a6f18 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 @@ -8,13 +8,13 @@ {{#isEnum}} char* {{classFilename}}_{{classname}}_ToString({{projectName}}_{{classVarName}}_{{enumName}}_e {{classname}}) { - char *{{classname}}Array[] = { "NULL"{{#allowableValues}}{{#enumVars}}, "{{{value}}}"{{/enumVars}}{{/allowableValues}} }; + char *{{classname}}Array[] = { "NULL"{{#allowableValues}}{{#values}}, "{{.}}"{{/values}}{{/allowableValues}} }; return {{classname}}Array[{{classname}}]; } {{projectName}}_{{classVarName}}_{{enumName}}_e {{classFilename}}_{{classname}}_FromString(char* {{classname}}) { int stringToReturn = 0; - char *{{classname}}Array[] = { "NULL"{{#allowableValues}}{{#enumVars}}, "{{{value}}}"{{/enumVars}}{{/allowableValues}} }; + char *{{classname}}Array[] = { "NULL"{{#allowableValues}}{{#values}}, "{{.}}"{{/values}}{{/allowableValues}} }; size_t sizeofArray = sizeof({{classname}}Array) / sizeof({{classname}}Array[0]); while(stringToReturn < sizeofArray) { if(strcmp({{classname}}, {{classname}}Array[stringToReturn]) == 0) { @@ -78,13 +78,13 @@ end: {{^isModel}} {{#isEnum}} char* {{name}}{{classname}}_ToString({{projectName}}_{{classVarName}}_{{enumName}}_e {{name}}) { - char* {{name}}Array[] = { "NULL"{{#allowableValues}}{{#enumVars}}, "{{{value}}}"{{/enumVars}}{{/allowableValues}} }; + char* {{name}}Array[] = { "NULL"{{#allowableValues}}{{#values}}, "{{.}}"{{/values}}{{/allowableValues}} }; return {{name}}Array[{{name}}]; } {{projectName}}_{{classVarName}}_{{enumName}}_e {{name}}{{classname}}_FromString(char* {{name}}){ int stringToReturn = 0; - char *{{name}}Array[] = { "NULL"{{#allowableValues}}{{#enumVars}}, "{{{value}}}"{{/enumVars}}{{/allowableValues}} }; + char *{{name}}Array[] = { "NULL"{{#allowableValues}}{{#values}}, "{{.}}"{{/values}}{{/allowableValues}} }; size_t sizeofArray = sizeof({{name}}Array) / sizeof({{name}}Array[0]); while(stringToReturn < sizeofArray) { if(strcmp({{name}}, {{name}}Array[stringToReturn]) == 0) { @@ -102,13 +102,13 @@ char* {{name}}{{classname}}_ToString({{projectName}}_{{classVarName}}_{{enumName {{^isModel}} {{#isEnum}} char* {{name}}{{classname}}_ToString({{projectName}}_{{classVarName}}_{{enumName}}_e {{name}}) { - char *{{name}}Array[] = { "NULL"{{#allowableValues}}{{#enumVars}}, "{{{value}}}"{{/enumVars}}{{/allowableValues}} }; + char *{{name}}Array[] = { "NULL"{{#allowableValues}}{{#values}}, "{{.}}"{{/values}}{{/allowableValues}} }; return {{name}}Array[{{name}} - 1]; } {{projectName}}_{{classVarName}}_{{enumName}}_e {{name}}{{classname}}_FromString(char* {{name}}) { int stringToReturn = 0; - char *{{name}}Array[] = { "NULL"{{#allowableValues}}{{#enumVars}}, "{{{value}}}"{{/enumVars}}{{/allowableValues}} }; + char *{{name}}Array[] = { "NULL"{{#allowableValues}}{{#values}}, "{{.}}"{{/values}}{{/allowableValues}} }; size_t sizeofArray = sizeof({{name}}Array) / sizeof({{name}}Array[0]); while(stringToReturn < sizeofArray) { if(strcmp({{name}}, {{name}}Array[stringToReturn]) == 0) { 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 4e094dfccbe..e0d3e01c386 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 @@ -162,6 +162,7 @@ public class ApiClient { return objectMapper; } + {{#hasOAuthMethods}} private RequestInterceptor buildOauthRequestInterceptor(OAuthFlow flow, String authorizationUrl, String tokenUrl, String scopes) { switch (flow) { case password: @@ -173,6 +174,7 @@ public class ApiClient { } } + {{/hasOAuthMethods}} public ObjectMapper getObjectMapper(){ return objectMapper; } 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 63321ae28bb..b43a110aed7 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 @@ -170,7 +170,7 @@ 1.5.18 9.2.9.v20150224 4.13.1 - 1.1.7 + 1.2.0 2.5 {{#useBeanValidation}} 1.1.0.Final diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/native/AbstractOpenApiSchema.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/native/AbstractOpenApiSchema.mustache index d7d9ee9e740..11429c69b46 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/native/AbstractOpenApiSchema.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/native/AbstractOpenApiSchema.mustache @@ -6,7 +6,6 @@ import {{invokerPackage}}.ApiException; import java.util.Objects; import java.lang.reflect.Type; import java.util.Map; -import javax.ws.rs.core.GenericType; import com.fasterxml.jackson.annotation.JsonValue; @@ -35,7 +34,7 @@ public abstract class AbstractOpenApiSchema { * * @return an instance of the actual schema/object */ - public abstract Map getSchemas(); + public abstract Map> getSchemas(); /** * Get the actual instance 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 16aa21e1403..961f23b4870 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 @@ -26,11 +26,9 @@ import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; -import javax.ws.rs.core.GenericType; -import javax.ws.rs.ext.ContextResolver; {{>generatedAnnotation}} -public class JSON implements ContextResolver { +public class JSON { private ObjectMapper mapper; public JSON() { @@ -70,11 +68,6 @@ public class JSON implements ContextResolver { mapper.setDateFormat(dateFormat); } - @Override - public ObjectMapper getContext(Class type) { - return mapper; - } - /** * Get the object mapper * @@ -207,10 +200,10 @@ public class JSON implements ContextResolver { visitedClasses.add(modelClass); // Traverse the oneOf/anyOf composed schemas. - Map descendants = modelDescendants.get(modelClass); + Map> descendants = modelDescendants.get(modelClass); if (descendants != null) { - for (GenericType childType : descendants.values()) { - if (isInstanceOf(childType.getRawType(), inst, visitedClasses)) { + for (Class childType : descendants.values()) { + if (isInstanceOf(childType, inst, visitedClasses)) { return true; } } @@ -221,12 +214,12 @@ public class JSON implements ContextResolver { /** * A map of discriminators for all model classes. */ - private static Map, ClassDiscriminatorMapping> modelDiscriminators = new HashMap, ClassDiscriminatorMapping>(); + private static Map, ClassDiscriminatorMapping> modelDiscriminators = new HashMap<>(); /** * A map of oneOf/anyOf descendants for each model class. */ - private static Map, Map> modelDescendants = new HashMap, Map>(); + private static Map, Map>> modelDescendants = new HashMap<>(); /** * Register a model class discriminator. @@ -246,7 +239,7 @@ public class JSON implements ContextResolver { * @param modelClass the model class * @param descendants a map of oneOf/anyOf descendants. */ - public static void registerDescendants(Class modelClass, Map descendants) { + public static void registerDescendants(Class modelClass, Map> descendants) { modelDescendants.put(modelClass, descendants); } 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 456f8309c09..17568b34dc0 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 @@ -1,5 +1,3 @@ -import javax.ws.rs.core.GenericType; -import javax.ws.rs.core.Response; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; @@ -10,7 +8,6 @@ import java.util.HashSet; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.JsonNode; @@ -99,7 +96,7 @@ public class {{classname}} extends AbstractOpenApiSchema{{#vendorExtensions.x-im } // store a list of schema names defined in anyOf - public static final Map schemas = new HashMap(); + public static final Map> schemas = new HashMap>(); public {{classname}}() { super("anyOf", {{#isNullable}}Boolean.TRUE{{/isNullable}}{{^isNullable}}Boolean.FALSE{{/isNullable}}); @@ -128,8 +125,7 @@ public class {{classname}} extends AbstractOpenApiSchema{{#vendorExtensions.x-im {{/anyOf}} static { {{#anyOf}} - schemas.put("{{{.}}}", new GenericType<{{{.}}}>() { - }); + schemas.put("{{{.}}}", {{{.}}}.class); {{/anyOf}} JSON.registerDescendants({{classname}}.class, Collections.unmodifiableMap(schemas)); {{#discriminator}} @@ -144,7 +140,7 @@ public class {{classname}} extends AbstractOpenApiSchema{{#vendorExtensions.x-im } @Override - public Map getSchemas() { + public Map> getSchemas() { return {{classname}}.schemas; } diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/native/api.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/native/api.mustache index e91e72f97b9..35922945360 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/native/api.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/native/api.mustache @@ -57,20 +57,25 @@ public class {{classname}} { } {{#asyncNative}} - private ApiException getApiException(String operationId, HttpResponselocalVarResponse) { - return new ApiException(localVarResponse.statusCode(), - operationId + " call received non-success response", - localVarResponse.headers(), - localVarResponse.body()); + private ApiException getApiException(String operationId, HttpResponse response) { + String message = formatExceptionMessage(operationId, response.statusCode(), response.body()); + return new ApiException(response.statusCode(), message, response.headers(), response.body()); + } + {{/asyncNative}} + {{^asyncNative}} + + protected ApiException getApiException(String operationId, HttpResponse response) throws IOException { + String body = response.body() == null ? null : new String(response.body().readAllBytes()); + String message = formatExceptionMessage(operationId, response.statusCode(), body); + return new ApiException(response.statusCode(), message, response.headers(), body); } {{/asyncNative}} - protected ApiException createApiException(HttpResponse response, String msgPrefix) throws IOException { - String body = response.body() == null ? null : new String(response.body().readAllBytes()); - if (body != null) { - msgPrefix += ": " + body; + private String formatExceptionMessage(String operationId, int statusCode, String body) { + if (body == null || body.isEmpty()) { + body = "[no body]"; } - return new ApiException(response.statusCode(), msgPrefix, response.headers(), body); + return operationId + " call failed with: " + statusCode + " - " + body; } {{#operation}} @@ -215,7 +220,7 @@ public class {{classname}} { memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw createApiException(localVarResponse, "{{operationId}} call received non-success response"); + throw getApiException("{{operationId}}", localVarResponse); } return new ApiResponse<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}>( localVarResponse.statusCode(), diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/native/build.gradle.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/native/build.gradle.mustache index e1967261a11..36504882370 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/native/build.gradle.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/native/build.gradle.mustache @@ -22,6 +22,17 @@ apply plugin: 'maven' sourceCompatibility = JavaVersion.VERSION_11 targetCompatibility = JavaVersion.VERSION_11 +// Some text from the schema is copy pasted into the source files as UTF-8 +// but the default still seems to be to use platform encoding +tasks.withType(JavaCompile) { + configure(options) { + options.encoding = 'UTF-8' + } +} +javadoc { + options.encoding = 'UTF-8' +} + install { repositories.mavenInstaller { pom.artifactId = '{{artifactId}}' @@ -53,7 +64,6 @@ ext { swagger_annotations_version = "1.5.22" jackson_version = "2.10.4" junit_version = "4.13.1" - ws_rs_version = "2.1.1" {{#threetenbp}} threetenbp_version = "2.9.10" {{/threetenbp}} @@ -68,7 +78,6 @@ dependencies { implementation "com.fasterxml.jackson.datatype:jackson-datatype-jsr310:$jackson_version" implementation "org.openapitools:jackson-databind-nullable:0.2.1" implementation 'javax.annotation:javax.annotation-api:1.3.2' - implementation "javax.ws.rs:javax.ws.rs-api:$ws_rs_version" {{#threetenbp}} implementation "com.github.joschi.jackson:jackson-datatype-threetenbp:$threetenbp_version" {{/threetenbp}} 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 f2345ab33be..ff1118ebdba 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 @@ -1,5 +1,3 @@ -import javax.ws.rs.core.GenericType; -import javax.ws.rs.core.Response; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; @@ -11,7 +9,6 @@ import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.JsonToken; -import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.JsonNode; @@ -132,7 +129,7 @@ public class {{classname}} extends AbstractOpenApiSchema{{#vendorExtensions.x-im } // store a list of schema names defined in oneOf - public static final Map schemas = new HashMap(); + public static final Map> schemas = new HashMap<>(); public {{classname}}() { super("oneOf", {{#isNullable}}Boolean.TRUE{{/isNullable}}{{^isNullable}}Boolean.FALSE{{/isNullable}}); @@ -161,8 +158,7 @@ public class {{classname}} extends AbstractOpenApiSchema{{#vendorExtensions.x-im {{/oneOf}} static { {{#oneOf}} - schemas.put("{{{.}}}", new GenericType<{{{.}}}>() { - }); + schemas.put("{{{.}}}", {{{.}}}.class); {{/oneOf}} JSON.registerDescendants({{classname}}.class, Collections.unmodifiableMap(schemas)); {{#discriminator}} @@ -177,7 +173,7 @@ public class {{classname}} extends AbstractOpenApiSchema{{#vendorExtensions.x-im } @Override - public Map getSchemas() { + public Map> getSchemas() { return {{classname}}.schemas; } diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/native/pom.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/native/pom.mustache index a6445406227..4a90d80c3dc 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/native/pom.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/native/pom.mustache @@ -214,13 +214,6 @@ provided - - - javax.ws.rs - javax.ws.rs-api - ${javax-ws-rs-api-version} - - junit @@ -238,7 +231,6 @@ 2.10.4 0.2.1 1.3.2 - 2.1.1 {{#threetenbp}} 2.9.10 {{/threetenbp}} diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/resteasy/JSON.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/resteasy/JSON.mustache index 338d0455d14..71bd624f7ed 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/resteasy/JSON.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/resteasy/JSON.mustache @@ -5,12 +5,7 @@ import com.fasterxml.jackson.databind.*; {{#openApiNullable}} import org.openapitools.jackson.nullable.JsonNullableModule; {{/openApiNullable}} -{{#java8}} import com.fasterxml.jackson.datatype.jsr310.*; -{{/java8}} -{{^java8}} -import com.fasterxml.jackson.datatype.joda.*; -{{/java8}} import java.text.DateFormat; @@ -33,12 +28,7 @@ public class JSON implements ContextResolver { JsonNullableModule jnm = new JsonNullableModule(); mapper.registerModule(jnm); {{/openApiNullable}} - {{#java8}} mapper.registerModule(new JavaTimeModule()); - {{/java8}} - {{^java8}} - mapper.registerModule(new JodaModule()); - {{/java8}} } /** diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/resteasy/build.gradle.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/resteasy/build.gradle.mustache index fe6c7b1f8d0..852a2f638a5 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/resteasy/build.gradle.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/resteasy/build.gradle.mustache @@ -33,14 +33,8 @@ if(hasProperty('target') && target == 'android') { targetSdkVersion 23 } compileOptions { - {{#java8}} sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 - {{/java8}} - {{^java8}} - sourceCompatibility JavaVersion.VERSION_1_7 - targetCompatibility JavaVersion.VERSION_1_7 - {{/java8}} } // Rename the aar correctly @@ -84,14 +78,8 @@ if(hasProperty('target') && target == 'android') { apply plugin: 'java' apply plugin: 'maven' - {{#java8}} sourceCompatibility = JavaVersion.VERSION_1_8 targetCompatibility = JavaVersion.VERSION_1_8 - {{/java8}} - {{^java8}} - sourceCompatibility = JavaVersion.VERSION_1_7 - targetCompatibility = JavaVersion.VERSION_1_7 - {{/java8}} install { repositories.mavenInstaller { @@ -113,10 +101,7 @@ ext { jackson_databind_nullable_version = "0.2.1" {{/openApiNullable}} threetenbp_version = "2.9.10" - resteasy_version = "3.1.3.Final" - {{^java8}} - jodatime_version = "2.9.9" - {{/java8}} + resteasy_version = "4.5.11.Final" junit_version = "4.13" } @@ -133,14 +118,7 @@ dependencies { {{#openApiNullable}} implementation "org.openapitools:jackson-databind-nullable:$jackson_databind_nullable_version" {{/openApiNullable}} - {{#java8}} implementation "com.fasterxml.jackson.datatype:jackson-datatype-jsr310:$jackson_version" - {{/java8}} - {{^java8}} - implementation "com.fasterxml.jackson.datatype:jackson-datatype-joda:$jackson_version" - implementation "joda-time:joda-time:$jodatime_version" - implementation "com.brsanthu:migbase64:2.2" - {{/java8}} implementation 'javax.annotation:javax.annotation-api:1.3.2' testImplementation "junit:junit:$junit_version" } diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/resteasy/build.sbt.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/resteasy/build.sbt.mustache index c2dfff284b0..785100fb678 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/resteasy/build.sbt.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/resteasy/build.sbt.mustache @@ -11,20 +11,13 @@ lazy val root = (project in file(".")). 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" % "3.1.3.Final" % "compile", - "org.jboss.resteasy" % "resteasy-jackson2-provider" % "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.10.5" % "compile", "com.fasterxml.jackson.core" % "jackson-annotations" % "2.10.5" % "compile", "com.fasterxml.jackson.core" % "jackson-databind" % "2.10.5.1" % "compile", "com.github.joschi.jackson" % "jackson-datatype-threetenbp" % "2.9.10" % "compile", - {{#java8}} "com.fasterxml.jackson.datatype" % "jackson-datatype-jsr310" % "2.9.10" % "compile", - {{/java8}} - {{^java8}} - "com.fasterxml.jackson.datatype" % "jackson-datatype-joda" % "2.9.10" % "compile", - "joda-time" % "joda-time" % "2.9.9" % "compile", - "com.brsanthu" % "migbase64" % "2.2" % "compile", - {{/java8}} "javax.annotation" % "javax.annotation-api" % "1.3.2" % "compile", "junit" % "junit" % "4.13" % "test", "com.novocode" % "junit-interface" % "0.10" % "test" diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/resteasy/pom.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/resteasy/pom.mustache index 084f42df9bd..edeb08f18c1 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/resteasy/pom.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/resteasy/pom.mustache @@ -142,14 +142,8 @@ maven-compiler-plugin 2.5.1 - {{#java8}} - 1.8 - 1.8 - {{/java8}} - {{^java8}} - 1.7 - 1.7 - {{/java8}} + 1.8 + 1.8 @@ -158,12 +152,7 @@ 3.1.1 none - {{#java8}} - 1.8 - {{/java8}} - {{^java8}} - 1.7 - {{/java8}} + 1.8 @@ -193,11 +182,43 @@ org.jboss.resteasy resteasy-client ${resteasy-version} + + + org.jboss.resteasy + resteasy-jaxrs-services + + + net.jcip + jcip-annotations + + + org.jboss.spec.javax.annotation + jboss-annotations-api_1.2_spec + + + javax.activation + activation + + org.jboss.resteasy resteasy-multipart-provider ${resteasy-version} + + + com.sun.xml.bind + jaxb-impl + + + com.sun.mail + javax.mail + + + javax.activation + activation + + @@ -232,30 +253,10 @@ {{/withXml}} - {{^java8}} - - com.fasterxml.jackson.datatype - jackson-datatype-joda - ${jackson-version} - - - joda-time - joda-time - ${jodatime-version} - - - - - com.brsanthu - migbase64 - 2.2 - - {{/java8}} - org.jboss.resteasy resteasy-jackson2-provider - 3.1.3.Final + ${resteasy-version} com.fasterxml.jackson.datatype @@ -284,15 +285,12 @@ UTF-8 1.5.22 - 3.1.3.Final + 4.5.11.Final 2.10.5 2.10.5.1 0.2.1 1.3.2 2.9.10 - {{^java8}} - 2.9.9 - {{/java8}} 1.0.0 4.13 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 150f3d3ebbb..032d398f6cd 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 @@ -39,10 +39,11 @@ import com.fasterxml.jackson.datatype.threetenbp.ThreeTenModule; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter; import com.fasterxml.jackson.databind.ObjectMapper; +{{/threetenbp}} {{#openApiNullable}} import org.openapitools.jackson.nullable.JsonNullableModule; {{/openApiNullable}} -{{/threetenbp}} + import java.io.BufferedReader; import java.io.IOException; 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 dce5d647267..e0c75bdc0da 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 @@ -71,7 +71,7 @@ public class {{classname}} { {{#isDeprecated}} @Deprecated {{/isDeprecated}} - public {{#returnType}}{{{returnType}}} {{/returnType}}{{^returnType}}void {{/returnType}}{{operationId}}({{#allParams}}{{#isFile}}{{#useAbstractionForFiles}}{{#collectionFormat}}java.util.Collection{{/collectionFormat}}{{^collectionFormat}}org.springframework.web.multipart.MultipartFile{{/collectionFormat}}{{/useAbstractionForFiles}}{{^useAbstractionForFiles}}{{{dataType}}}{{/useAbstractionForFiles}}{{/isFile}}{{^isFile}}{{{dataType}}}{{/isFile}} {{paramName}}{{^-last}}, {{/-last}}{{/allParams}}) throws RestClientException { + public {{#returnType}}{{{returnType}}} {{/returnType}}{{^returnType}}void {{/returnType}}{{operationId}}({{#allParams}}{{#isFile}}{{#useAbstractionForFiles}}{{#collectionFormat}}java.util.Collection{{/collectionFormat}}{{^collectionFormat}}org.springframework.core.io.Resource{{/collectionFormat}}{{/useAbstractionForFiles}}{{^useAbstractionForFiles}}{{{dataType}}}{{/useAbstractionForFiles}}{{/isFile}}{{^isFile}}{{{dataType}}}{{/isFile}} {{paramName}}{{^-last}}, {{/-last}}{{/allParams}}) throws RestClientException { {{#returnType}} return {{operationId}}WithHttpInfo({{#allParams}}{{paramName}}{{^-last}}, {{/-last}}{{/allParams}}).getBody(); {{/returnType}} @@ -99,7 +99,7 @@ public class {{classname}} { {{#isDeprecated}} @Deprecated {{/isDeprecated}} - public ResponseEntity<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}> {{operationId}}WithHttpInfo({{#allParams}}{{#isFile}}{{#useAbstractionForFiles}}{{#collectionFormat}}java.util.Collection{{/collectionFormat}}{{^collectionFormat}}org.springframework.web.multipart.MultipartFile{{/collectionFormat}}{{/useAbstractionForFiles}}{{^useAbstractionForFiles}}{{{dataType}}}{{/useAbstractionForFiles}}{{/isFile}}{{^isFile}}{{{dataType}}}{{/isFile}} {{paramName}}{{^-last}}, {{/-last}}{{/allParams}}) throws RestClientException { + public ResponseEntity<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}> {{operationId}}WithHttpInfo({{#allParams}}{{#isFile}}{{#useAbstractionForFiles}}{{#collectionFormat}}java.util.Collection{{/collectionFormat}}{{^collectionFormat}}org.springframework.core.io.Resource{{/collectionFormat}}{{/useAbstractionForFiles}}{{^useAbstractionForFiles}}{{{dataType}}}{{/useAbstractionForFiles}}{{/isFile}}{{^isFile}}{{{dataType}}}{{/isFile}} {{paramName}}{{^-last}}, {{/-last}}{{/allParams}}) throws RestClientException { Object postBody = {{#bodyParam}}{{paramName}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}}; {{#allParams}}{{#required}} // verify the required parameter '{{paramName}}' is set @@ -139,12 +139,12 @@ public class {{classname}} { final String[] contentTypes = { {{#hasConsumes}} {{#consumes}}"{{{mediaType}}}"{{^-last}}, {{/-last}}{{/consumes}} {{/hasConsumes}} }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { {{#authMethods}}"{{name}}"{{^-last}}, {{/-last}}{{/authMethods}} }; {{#returnType}}ParameterizedTypeReference<{{{returnType}}}> returnType = new ParameterizedTypeReference<{{{returnType}}}>() {};{{/returnType}}{{^returnType}}ParameterizedTypeReference returnType = new ParameterizedTypeReference() {};{{/returnType}} - return apiClient.invokeAPI(path, HttpMethod.{{httpMethod}}, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.{{httpMethod}}, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } {{/operation}} } diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/resttemplate/api_test.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/resttemplate/api_test.mustache index 56d89a842d4..119194543c3 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/resttemplate/api_test.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/resttemplate/api_test.mustache @@ -34,7 +34,7 @@ public class {{classname}}Test { @Test public void {{operationId}}Test() { {{#allParams}} - {{#isFile}}{{#useAbstractionForFiles}}{{#collectionFormat}}java.util.Collection{{/collectionFormat}}{{^collectionFormat}}org.springframework.web.multipart.MultipartFile{{/collectionFormat}}{{/useAbstractionForFiles}}{{^useAbstractionForFiles}}{{{dataType}}}{{/useAbstractionForFiles}}{{/isFile}}{{^isFile}}{{{dataType}}}{{/isFile}} {{paramName}} = null; + {{#isFile}}{{#useAbstractionForFiles}}{{#collectionFormat}}java.util.Collection{{/collectionFormat}}{{^collectionFormat}}org.springframework.core.io.Resource{{/collectionFormat}}{{/useAbstractionForFiles}}{{^useAbstractionForFiles}}{{{dataType}}}{{/useAbstractionForFiles}}{{/isFile}}{{^isFile}}{{{dataType}}}{{/isFile}} {{paramName}} = null; {{/allParams}} {{#returnType}}{{{returnType}}} response = {{/returnType}}api.{{operationId}}({{#allParams}}{{paramName}}{{^-last}}, {{/-last}}{{/allParams}}); 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 6491013f5a8..677b8304f80 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 @@ -31,6 +31,7 @@ import org.springframework.http.client.reactive.ClientHttpRequest; import org.springframework.web.client.RestClientException; import org.springframework.web.util.UriComponentsBuilder; import org.springframework.web.reactive.function.client.WebClient; +import org.springframework.web.reactive.function.client.WebClient.ResponseSpec; import org.springframework.web.reactive.function.client.ClientResponse; import org.springframework.web.reactive.function.BodyInserter; import org.springframework.web.reactive.function.BodyInserters; @@ -512,6 +513,15 @@ public class ApiClient{{#jsr310}} extends JavaTimeFormatter{{/jsr310}} { 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; @@ -526,7 +536,7 @@ public class ApiClient{{#jsr310}} extends JavaTimeFormatter{{/jsr310}} { } for (String accept : accepts) { MediaType mediaType = MediaType.parseMediaType(accept); - if (isJsonMime(mediaType)) { + if (isJsonMime(mediaType) && !isProblemJsonMime(accept)) { return Collections.singletonList(mediaType); } } @@ -595,31 +605,9 @@ public class ApiClient{{#jsr310}} extends JavaTimeFormatter{{/jsr310}} { * @param returnType The return type into which to deserialize the response * @return The response body in chosen type */ - public Mono 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 { + public ResponseSpec 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 { final WebClient.RequestBodySpec requestBuilder = prepareRequest(path, method, pathParams, queryParams, body, headerParams, cookieParams, formParams, accept, contentType, authNames); - return requestBuilder.retrieve().bodyToMono(returnType); - } - - /** - * 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 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 chosen type - */ - public Flux invokeFluxAPI(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 { - final WebClient.RequestBodySpec requestBuilder = prepareRequest(path, method, pathParams, queryParams, body, headerParams, cookieParams, formParams, accept, contentType, authNames); - return requestBuilder.retrieve().bodyToFlux(returnType); + return requestBuilder.retrieve(); } private WebClient.RequestBodySpec prepareRequest(String path, HttpMethod method, Map pathParams, MultiValueMap queryParams, Object body, HttpHeaders headerParams, MultiValueMap cookieParams, MultiValueMap formParams, List accept, MediaType contentType, String[] authNames) { 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 5fbef45db81..dcd86e45fc9 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 @@ -18,12 +18,14 @@ import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import org.springframework.web.util.UriComponentsBuilder; import org.springframework.core.ParameterizedTypeReference; +import org.springframework.web.reactive.function.client.WebClient.ResponseSpec; import org.springframework.web.reactive.function.client.WebClientResponseException; 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; import reactor.core.publisher.Mono; import reactor.core.publisher.Flux; @@ -62,7 +64,7 @@ public class {{classname}} { * @see {{summary}} Documentation {{/externalDocs}} */ - public {{#returnType}}{{#isArray}}Flux<{{{returnBaseType}}}>{{/isArray}}{{^isArray}}Mono<{{{returnType}}}>{{/isArray}} {{/returnType}}{{^returnType}}Mono {{/returnType}}{{operationId}}({{#allParams}}{{#isFile}}{{#useAbstractionForFiles}}{{#collectionFormat}}java.util.Collection{{/collectionFormat}}{{^collectionFormat}}org.springframework.core.io.AbstractResource{{/collectionFormat}}{{/useAbstractionForFiles}}{{^useAbstractionForFiles}}{{{dataType}}}{{/useAbstractionForFiles}}{{/isFile}}{{^isFile}}{{{dataType}}}{{/isFile}} {{paramName}}{{^-last}}, {{/-last}}{{/allParams}}) throws WebClientResponseException { + private ResponseSpec {{operationId}}RequestCreation({{#allParams}}{{#isFile}}{{#useAbstractionForFiles}}{{#collectionFormat}}java.util.Collection{{/collectionFormat}}{{^collectionFormat}}org.springframework.core.io.AbstractResource{{/collectionFormat}}{{/useAbstractionForFiles}}{{^useAbstractionForFiles}}{{{dataType}}}{{/useAbstractionForFiles}}{{/isFile}}{{^isFile}}{{{dataType}}}{{/isFile}} {{paramName}}{{^-last}}, {{/-last}}{{/allParams}}) throws WebClientResponseException { Object postBody = {{#bodyParam}}{{paramName}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}}; {{#allParams}} {{#required}} @@ -125,7 +127,29 @@ public class {{classname}} { String[] localVarAuthNames = new String[] { {{#authMethods}}"{{name}}"{{^-last}}, {{/-last}}{{/authMethods}} }; {{#returnType}}ParameterizedTypeReference<{{#isArray}}{{{returnBaseType}}}{{/isArray}}{{^isArray}}{{{returnType}}}{{/isArray}}> localVarReturnType = new ParameterizedTypeReference<{{#isArray}}{{{returnBaseType}}}{{/isArray}}{{^isArray}}{{{returnType}}}{{/isArray}}>() {};{{/returnType}}{{^returnType}}ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {};{{/returnType}} - return apiClient.{{#isArray}}invokeFluxAPI{{/isArray}}{{^isArray}}invokeAPI{{/isArray}}("{{{path}}}", HttpMethod.{{httpMethod}}, pathParams, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + return apiClient.invokeAPI("{{{path}}}", HttpMethod.{{httpMethod}}, pathParams, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + + /** + * {{summary}} + * {{notes}} +{{#responses}} *

    {{code}}{{#message}} - {{message}}{{/message}} +{{/responses}}{{#allParams}} * @param {{paramName}} {{description}}{{^description}}The {{paramName}} parameter{{/description}} +{{/allParams}}{{#returnType}} * @return {{returnType}} +{{/returnType}} * @throws WebClientResponseException if an error occurs while attempting to invoke the API +{{#externalDocs}} + * {{description}} + * @see {{summary}} Documentation +{{/externalDocs}} + */ + public {{#returnType}}{{#isArray}}Flux<{{{returnBaseType}}}>{{/isArray}}{{^isArray}}Mono<{{{returnType}}}>{{/isArray}} {{/returnType}}{{^returnType}}Mono {{/returnType}}{{operationId}}({{#allParams}}{{#isFile}}{{#useAbstractionForFiles}}{{#collectionFormat}}java.util.Collection{{/collectionFormat}}{{^collectionFormat}}org.springframework.core.io.AbstractResource{{/collectionFormat}}{{/useAbstractionForFiles}}{{^useAbstractionForFiles}}{{{dataType}}}{{/useAbstractionForFiles}}{{/isFile}}{{^isFile}}{{{dataType}}}{{/isFile}} {{paramName}}{{^-last}}, {{/-last}}{{/allParams}}) throws WebClientResponseException { + {{#returnType}}ParameterizedTypeReference<{{#isArray}}{{{returnBaseType}}}{{/isArray}}{{^isArray}}{{{returnType}}}{{/isArray}}> localVarReturnType = new ParameterizedTypeReference<{{#isArray}}{{{returnBaseType}}}{{/isArray}}{{^isArray}}{{{returnType}}}{{/isArray}}>() {};{{/returnType}}{{^returnType}}ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {};{{/returnType}} + return {{operationId}}RequestCreation({{#allParams}}{{paramName}}{{^-last}}, {{/-last}}{{/allParams}}).{{#isArray}}bodyToFlux{{/isArray}}{{^isArray}}bodyToMono{{/isArray}}(localVarReturnType); + } + + public {{#returnType}}{{#isArray}}Mono>>{{/isArray}}{{^isArray}}Mono>{{/isArray}} {{/returnType}}{{^returnType}}Mono> {{/returnType}}{{operationId}}WithHttpInfo({{#allParams}}{{#isFile}}{{#useAbstractionForFiles}}{{#collectionFormat}}java.util.Collection{{/collectionFormat}}{{^collectionFormat}}org.springframework.core.io.AbstractResource{{/collectionFormat}}{{/useAbstractionForFiles}}{{^useAbstractionForFiles}}{{{dataType}}}{{/useAbstractionForFiles}}{{/isFile}}{{^isFile}}{{{dataType}}}{{/isFile}} {{paramName}}{{^-last}}, {{/-last}}{{/allParams}}) throws WebClientResponseException { + {{#returnType}}ParameterizedTypeReference<{{#isArray}}{{{returnBaseType}}}{{/isArray}}{{^isArray}}{{{returnType}}}{{/isArray}}> localVarReturnType = new ParameterizedTypeReference<{{#isArray}}{{{returnBaseType}}}{{/isArray}}{{^isArray}}{{{returnType}}}{{/isArray}}>() {};{{/returnType}}{{^returnType}}ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {};{{/returnType}} + return {{operationId}}RequestCreation({{#allParams}}{{paramName}}{{^-last}}, {{/-last}}{{/allParams}}).{{#isArray}}toEntityList{{/isArray}}{{^isArray}}toEntity{{/isArray}}(localVarReturnType); } {{/operation}} } 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 a0e068f8ce5..e9df52a01a6 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 @@ -207,7 +207,7 @@ 1.5.22 9.2.9.v20150224 4.13.1 - 1.1.7 + 1.2.0 2.5 {{#useBeanValidation}} 1.1.0.Final 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 eabc448d6b2..8cb82501d51 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 @@ -338,7 +338,7 @@ {{/generateSpringApplication}} {{^generateSpringBootApplication}} 4.13 - 1.1.7 + 1.2.0 {{/generateSpringBootApplication}} 3.3.0 2.9.9 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 d1596f47265..493fd683cf9 100644 --- a/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf/pom.mustache +++ b/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf/pom.mustache @@ -207,7 +207,7 @@ 1.5.18 9.2.9.v20150224 4.13.1 - 1.1.7 + 1.2.0 2.5 {{#useBeanValidation}} 1.1.0.Final 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 9d8c6df2b59..28a678bb612 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 @@ -258,7 +258,7 @@ 1.5.22 9.2.9.v20150224 4.13 - 1.1.7 + 1.2.0 2.5 {{#useBeanValidation}} 1.1.0.Final diff --git a/modules/openapi-generator/src/main/resources/JavaJaxRS/pom.mustache b/modules/openapi-generator/src/main/resources/JavaJaxRS/pom.mustache index 8951701707d..dc2a043addb 100644 --- a/modules/openapi-generator/src/main/resources/JavaJaxRS/pom.mustache +++ b/modules/openapi-generator/src/main/resources/JavaJaxRS/pom.mustache @@ -218,7 +218,7 @@ 3.5 {{/supportJava6}} 4.13.1 - 1.1.7 + 1.2.0 2.5 UTF-8 diff --git a/modules/openapi-generator/src/main/resources/JavaSpring/beanValidationQueryParams.mustache b/modules/openapi-generator/src/main/resources/JavaSpring/beanValidationQueryParams.mustache index 9cca8cb8874..a2f19f77468 100644 --- a/modules/openapi-generator/src/main/resources/JavaSpring/beanValidationQueryParams.mustache +++ b/modules/openapi-generator/src/main/resources/JavaSpring/beanValidationQueryParams.mustache @@ -1 +1 @@ -{{#required}}@NotNull {{/required}}{{>beanValidationCore}} \ No newline at end of file +{{#required}}@NotNull {{/required}}{{^useOptional}}{{>beanValidationCore}}{{/useOptional}}{{#useOptional}}{{#required}}{{>beanValidationCore}}{{/required}}{{/useOptional}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/JavaSpring/homeController.mustache b/modules/openapi-generator/src/main/resources/JavaSpring/homeController.mustache index 2b244c540bc..f909a15b37d 100644 --- a/modules/openapi-generator/src/main/resources/JavaSpring/homeController.mustache +++ b/modules/openapi-generator/src/main/resources/JavaSpring/homeController.mustache @@ -4,7 +4,7 @@ package {{configPackage}}; import com.fasterxml.jackson.dataformat.yaml.YAMLMapper; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; -import org.springframework.web.multipart.MultipartFile; +import org.springframework.core.io.Resource; {{/useSpringfox}} import org.springframework.stereotype.Controller; {{^useSpringfox}} diff --git a/modules/openapi-generator/src/main/resources/JavaSpring/libraries/spring-boot/application.mustache b/modules/openapi-generator/src/main/resources/JavaSpring/libraries/spring-boot/application.mustache index b7fea3f6262..6eb4ae24298 100644 --- a/modules/openapi-generator/src/main/resources/JavaSpring/libraries/spring-boot/application.mustache +++ b/modules/openapi-generator/src/main/resources/JavaSpring/libraries/spring-boot/application.mustache @@ -5,8 +5,8 @@ server.port={{serverPort}} spring.jackson.date-format={{basePackage}}.RFC3339DateFormat spring.jackson.serialization.WRITE_DATES_AS_TIMESTAMPS=false {{#virtualService}} -virtual.datasource.driver-class-name=org.hsqldb.jdbcDriver -virtual.datasource.jdbcurl=jdbc:hsqldb:mem:dataSource -virtual.datasource.username=sa -virtual.datasource.password= -{{/virtualService}} \ No newline at end of file +virtualan.datasource.driver-class-name=org.hsqldb.jdbcDriver +virtualan.datasource.jdbcurl=jdbc:hsqldb:mem:dataSource +virtualan.datasource.username=sa +virtualan.datasource.password= +{{/virtualService}} diff --git a/modules/openapi-generator/src/main/resources/JavaSpring/libraries/spring-boot/pom.mustache b/modules/openapi-generator/src/main/resources/JavaSpring/libraries/spring-boot/pom.mustache index e2733633e35..d5ae34ff8a5 100644 --- a/modules/openapi-generator/src/main/resources/JavaSpring/libraries/spring-boot/pom.mustache +++ b/modules/openapi-generator/src/main/resources/JavaSpring/libraries/spring-boot/pom.mustache @@ -176,18 +176,13 @@ io.virtualan virtualan-plugin - 2.1.7 + 2.2.1 org.hsqldb hsqldb - 2.3.2 - - - org.springframework.boot - spring-boot-starter-data-jpa - 1.5.9.RELEASE + 2.5.0 {{/virtualService}} diff --git a/modules/openapi-generator/src/main/resources/JavaSpring/optionalDataType.mustache b/modules/openapi-generator/src/main/resources/JavaSpring/optionalDataType.mustache index 976950e27e8..84505f8fc29 100644 --- a/modules/openapi-generator/src/main/resources/JavaSpring/optionalDataType.mustache +++ b/modules/openapi-generator/src/main/resources/JavaSpring/optionalDataType.mustache @@ -1 +1 @@ -{{#useOptional}}{{#required}}{{{dataType}}}{{/required}}{{^required}}Optional<{{{dataType}}}>{{/required}}{{/useOptional}}{{^useOptional}}{{{dataType}}}{{/useOptional}} \ No newline at end of file +{{#useOptional}}{{#required}}{{{dataType}}}{{/required}}{{^required}}Optional<{{#useBeanValidation}}{{>beanValidationCore}}{{/useBeanValidation}}{{{dataType}}}>{{/required}}{{/useOptional}}{{^useOptional}}{{{dataType}}}{{/useOptional}} \ No newline at end of file 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 4226cade162..a213327b3f7 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 @@ -11,11 +11,12 @@ org.openapitools.codegen.languages.CrystalClientCodegen org.openapitools.codegen.languages.CLibcurlClientCodegen org.openapitools.codegen.languages.ClojureClientCodegen org.openapitools.codegen.languages.ConfluenceWikiCodegen -org.openapitools.codegen.languages.CppQt5ClientCodegen -org.openapitools.codegen.languages.CppQt5QHttpEngineServerCodegen +org.openapitools.codegen.languages.CppQtClientCodegen +org.openapitools.codegen.languages.CppQtQHttpEngineServerCodegen org.openapitools.codegen.languages.CppPistacheServerCodegen org.openapitools.codegen.languages.CppRestbedServerCodegen org.openapitools.codegen.languages.CppRestSdkClientCodegen +org.openapitools.codegen.languages.CppTinyClientCodegen org.openapitools.codegen.languages.CppTizenClientCodegen org.openapitools.codegen.languages.CppUE4ClientCodegen org.openapitools.codegen.languages.CSharpClientCodegen @@ -37,6 +38,7 @@ org.openapitools.codegen.languages.FsharpFunctionsServerCodegen org.openapitools.codegen.languages.FsharpGiraffeServerCodegen org.openapitools.codegen.languages.GoClientCodegen org.openapitools.codegen.languages.GoDeprecatedClientCodegen +org.openapitools.codegen.languages.GoEchoServerCodegen org.openapitools.codegen.languages.GoServerCodegen org.openapitools.codegen.languages.GoGinServerCodegen org.openapitools.codegen.languages.GraphQLSchemaCodegen @@ -95,6 +97,7 @@ org.openapitools.codegen.languages.PowerShellClientCodegen org.openapitools.codegen.languages.ProtobufSchemaCodegen org.openapitools.codegen.languages.PythonLegacyClientCodegen org.openapitools.codegen.languages.PythonClientCodegen +org.openapitools.codegen.languages.PythonFastAPIServerCodegen org.openapitools.codegen.languages.PythonFlaskConnexionServerCodegen org.openapitools.codegen.languages.PythonAiohttpConnexionServerCodegen org.openapitools.codegen.languages.PythonBluePlanetServerCodegen @@ -132,4 +135,4 @@ org.openapitools.codegen.languages.TypeScriptNestjsClientCodegen org.openapitools.codegen.languages.TypeScriptNodeClientCodegen org.openapitools.codegen.languages.TypeScriptReduxQueryClientCodegen org.openapitools.codegen.languages.TypeScriptRxjsClientCodegen -org.openapitools.codegen.languages.GoEchoServerCodegen +org.openapitools.codegen.languages.WsdlSchemaCodegen diff --git a/modules/openapi-generator/src/main/resources/android/build.mustache b/modules/openapi-generator/src/main/resources/android/build.mustache index c26f9b8967d..4d465c7b9a8 100644 --- a/modules/openapi-generator/src/main/resources/android/build.mustache +++ b/modules/openapi-generator/src/main/resources/android/build.mustache @@ -89,7 +89,7 @@ android { ext { swagger_annotations_version = "1.5.0" gson_version = "2.3.1" - httpclient_version = "4.5.2" + httpclient_version = "4.5.13" httpcore_version = "4.4.4" junit_version = "4.13" } diff --git a/modules/openapi-generator/src/main/resources/android/jsonUtil.mustache b/modules/openapi-generator/src/main/resources/android/jsonUtil.mustache index 5995c0150f0..ae8d18d3731 100644 --- a/modules/openapi-generator/src/main/resources/android/jsonUtil.mustache +++ b/modules/openapi-generator/src/main/resources/android/jsonUtil.mustache @@ -5,9 +5,7 @@ import com.google.gson.GsonBuilder; import com.google.gson.reflect.TypeToken; import java.lang.reflect.Type; import java.util.List; -{{#hasModel}} import {{modelPackage}}.*; -{{/hasModel}} public class JsonUtil { public static GsonBuilder gsonBuilder; diff --git a/modules/openapi-generator/src/main/resources/android/pom.mustache b/modules/openapi-generator/src/main/resources/android/pom.mustache index ff001f6c572..fea7ca217b0 100644 --- a/modules/openapi-generator/src/main/resources/android/pom.mustache +++ b/modules/openapi-generator/src/main/resources/android/pom.mustache @@ -176,6 +176,6 @@ 4.13.1 1.0.0 4.8.1 - 4.3.6 + 4.5.13 diff --git a/modules/openapi-generator/src/main/resources/aspnetcore/3.0/Project.csproj.mustache b/modules/openapi-generator/src/main/resources/aspnetcore/3.0/Project.csproj.mustache index 70f7388a988..ee3ced7ba19 100644 --- a/modules/openapi-generator/src/main/resources/aspnetcore/3.0/Project.csproj.mustache +++ b/modules/openapi-generator/src/main/resources/aspnetcore/3.0/Project.csproj.mustache @@ -7,6 +7,9 @@ true true {{packageVersion}} +{{#nullableReferenceTypes}} + annotations +{{/nullableReferenceTypes}} {{#isLibrary}} Library {{/isLibrary}} diff --git a/modules/openapi-generator/src/main/resources/cpp-pistache-server/api-header.mustache b/modules/openapi-generator/src/main/resources/cpp-pistache-server/api-header.mustache index f614d478e96..c79979173f4 100644 --- a/modules/openapi-generator/src/main/resources/cpp-pistache-server/api-header.mustache +++ b/modules/openapi-generator/src/main/resources/cpp-pistache-server/api-header.mustache @@ -42,13 +42,15 @@ private: ///

    /// Helper function to handle unexpected Exceptions during Parameter parsing and validation. - /// May be overriden to return custom error formats. + /// May be overriden to return custom error formats. This is called inside a catch block. + /// Important: When overriding, do not call `throw ex;`, but instead use `throw;`. /// virtual std::pair handleParsingException(const std::exception& ex) const noexcept; /// /// Helper function to handle unexpected Exceptions during processing of the request in handler functions. - /// May be overriden to return custom error formats. + /// May be overriden to return custom error formats. This is called inside a catch block. + /// Important: When overriding, do not call `throw ex;`, but instead use `throw;`. /// virtual std::pair handleOperationException(const std::exception& ex) const noexcept; diff --git a/modules/openapi-generator/src/main/resources/cpp-pistache-server/api-source.mustache b/modules/openapi-generator/src/main/resources/cpp-pistache-server/api-source.mustache index 9814ba0cd62..dad2eb75c6c 100644 --- a/modules/openapi-generator/src/main/resources/cpp-pistache-server/api-source.mustache +++ b/modules/openapi-generator/src/main/resources/cpp-pistache-server/api-source.mustache @@ -36,11 +36,13 @@ void {{classname}}::setupRoutes() { std::pair {{classname}}::handleParsingException(const std::exception& ex) const noexcept { try { - throw ex; + throw; } catch (nlohmann::detail::exception &e) { return std::make_pair(Pistache::Http::Code::Bad_Request, e.what()); } catch ({{helpersNamespace}}::ValidationException &e) { return std::make_pair(Pistache::Http::Code::Bad_Request, e.what()); + } catch (std::exception &e) { + return std::make_pair(Pistache::Http::Code::Internal_Server_Error, e.what()) } } diff --git a/modules/openapi-generator/src/main/resources/cpp-pistache-server/model-header.mustache b/modules/openapi-generator/src/main/resources/cpp-pistache-server/model-header.mustache index cb6d8d98ee0..ccd8e876af3 100644 --- a/modules/openapi-generator/src/main/resources/cpp-pistache-server/model-header.mustache +++ b/modules/openapi-generator/src/main/resources/cpp-pistache-server/model-header.mustache @@ -46,6 +46,12 @@ public: /// bool validate(std::stringstream& msg) const; + /// + /// Helper overload for validate. Used when one model stores another model and calls it's validate. + /// Not meant to be called outside that case. + /// + bool validate(std::stringstream& msg, const std::string& pathPrefix) const; + bool operator==(const {{classname}}& rhs) const; bool operator!=(const {{classname}}& rhs) const; @@ -64,22 +70,22 @@ public: {{#isEnum}} {{classname}}::e{{classname}} getValue() const; void setValue({{classname}}::e{{classname}} value); - {{/isEnum}} - + {{/isEnum}}{{#vendorExtensions.x-is-string-enum-container}}{{#anyOf}}{{#-first}} + {{{this}}} getValue() const; + void setValue({{{this}}} value); + {{{this}}}::e{{{this}}} getEnumValue() const; + void setEnumValue({{{this}}}::e{{{this}}} value);{{/-first}}{{/anyOf}}{{/vendorExtensions.x-is-string-enum-container}} friend void to_json(nlohmann::json& j, const {{classname}}& o); - friend void from_json(const nlohmann::json& j, {{classname}}& o); + friend void from_json(const nlohmann::json& j, {{classname}}& o);{{#vendorExtensions.x-is-string-enum-container}}{{#anyOf}}{{#-first}} + friend void to_json(nlohmann::json& j, const {{{this}}}& o); + friend void from_json(const nlohmann::json& j, {{{this}}}& o);{{/-first}}{{/anyOf}}{{/vendorExtensions.x-is-string-enum-container}} protected: {{#vars}} {{{dataType}}} m_{{name}}; {{^required}} bool m_{{name}}IsSet;{{/required}} {{/vars}} - {{#isEnum}} - {{classname}}::e{{classname}} m_value = {{classname}}::e{{classname}}::INVALID_VALUE_OPENAPI_GENERATED; - {{/isEnum}} - - // Helper overload for validate. Used when one model stores another model and calls it's validate. - bool validate(std::stringstream& msg, const std::string& pathPrefix) const; + {{#isEnum}}{{classname}}::e{{classname}} m_value = {{classname}}::e{{classname}}::INVALID_VALUE_OPENAPI_GENERATED;{{/isEnum}}{{#vendorExtensions.x-is-string-enum-container}}{{#anyOf}}{{#-first}}{{{this}}} m_value;{{/-first}}{{/anyOf}}{{/vendorExtensions.x-is-string-enum-container}} }; } // namespace {{modelNamespace}} diff --git a/modules/openapi-generator/src/main/resources/cpp-pistache-server/model-source.mustache b/modules/openapi-generator/src/main/resources/cpp-pistache-server/model-source.mustache index 8ef6abf0e4c..9ce767ed01b 100644 --- a/modules/openapi-generator/src/main/resources/cpp-pistache-server/model-source.mustache +++ b/modules/openapi-generator/src/main/resources/cpp-pistache-server/model-source.mustache @@ -60,10 +60,11 @@ bool {{classname}}::validate(std::stringstream& msg, const std::string& pathPref const std::string currentValuePath = _pathPrefix + ".{{nameInCamelCase}}"; {{> model-validation-body }} } - {{/hasValidation}}{{/isArray}} - {{/vars}} - {{/isEnum}} - + {{/hasValidation}}{{/isArray}}{{/vars}}{{/isEnum}}{{#vendorExtensions.x-is-string-enum-container}}{{#anyOf}}{{#-first}} + if (!m_value.validate(msg)) + { + success = false; + }{{/-first}}{{/anyOf}}{{/vendorExtensions.x-is-string-enum-container}} return success; } @@ -71,10 +72,10 @@ bool {{classname}}::operator==(const {{classname}}& rhs) const { return {{#isEnum}}getValue() == rhs.getValue(){{/isEnum}} - {{^isEnum}}{{#vars}} + {{^isEnum}}{{#hasVars}}{{#vars}} {{#required}}({{getter}}() == rhs.{{getter}}()){{/required}} {{^required}}((!{{nameInCamelCase}}IsSet() && !rhs.{{nameInCamelCase}}IsSet()) || ({{nameInCamelCase}}IsSet() && rhs.{{nameInCamelCase}}IsSet() && {{getter}}() == rhs.{{getter}}())){{/required}}{{^-last}} &&{{/-last}} - {{/vars}}{{/isEnum}} + {{/vars}}{{/hasVars}}{{^hasVars}}{{#vendorExtensions.x-is-string-enum-container}}{{#anyOf}}{{#-first}}getValue() == rhs.getValue(){{/-first}}{{/anyOf}}{{^anyOf}}true{{/anyOf}}{{/vendorExtensions.x-is-string-enum-container}}{{/hasVars}}{{/isEnum}} ; } @@ -103,7 +104,7 @@ void to_json(nlohmann::json& j, const {{classname}}& o) j = "{{value}}"; break; {{/enumVars}} - }{{/allowableValues}}{{/isEnum}} + }{{/allowableValues}}{{/isEnum}}{{#vendorExtensions.x-is-string-enum-container}}{{#anyOf}}{{#-first}}to_json(j, o.m_value);{{/-first}}{{/anyOf}}{{/vendorExtensions.x-is-string-enum-container}} } void from_json(const nlohmann::json& j, {{classname}}& o) @@ -127,7 +128,7 @@ void from_json(const nlohmann::json& j, {{classname}}& o) << " {{classname}}::e{{classname}}"; throw std::invalid_argument(ss.str()); } {{/-last}} -{{/enumVars}}{{/allowableValues}}{{/isEnum}} +{{/enumVars}}{{/allowableValues}}{{/isEnum}}{{#vendorExtensions.x-is-string-enum-container}}{{#anyOf}}{{#-first}}from_json(j, o.m_value);{{/-first}}{{/anyOf}}{{/vendorExtensions.x-is-string-enum-container}} } {{#vars}}{{{dataType}}} {{classname}}::{{getter}}() const @@ -156,7 +157,25 @@ void {{classname}}::unset{{name}}() void {{classname}}::setValue({{classname}}::e{{classname}} value) { m_value = value; -}{{/isEnum}} +}{{/isEnum}}{{#vendorExtensions.x-is-string-enum-container}}{{#anyOf}}{{#-first}}{{{this}}} {{classname}}::getValue() const +{ + return m_value; +} + +void {{classname}}::setValue({{{this}}} value) +{ + m_value = value; +} + +{{{this}}}::e{{{this}}} {{classname}}::getEnumValue() const +{ + return m_value.getValue(); +} + +void {{classname}}::setEnumValue({{{this}}}::e{{{this}}} value) +{ + m_value.setValue(value); +}{{/-first}}{{/anyOf}}{{/vendorExtensions.x-is-string-enum-container}} } // namespace {{modelNamespace}} diff --git a/modules/openapi-generator/src/main/resources/cpp-qt5-client/CMakeLists.txt.mustache b/modules/openapi-generator/src/main/resources/cpp-qt-client/CMakeLists.txt.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/cpp-qt5-client/CMakeLists.txt.mustache rename to modules/openapi-generator/src/main/resources/cpp-qt-client/CMakeLists.txt.mustache diff --git a/modules/openapi-generator/src/main/resources/cpp-qt5-client/HttpFileElement.cpp.mustache b/modules/openapi-generator/src/main/resources/cpp-qt-client/HttpFileElement.cpp.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/cpp-qt5-client/HttpFileElement.cpp.mustache rename to modules/openapi-generator/src/main/resources/cpp-qt-client/HttpFileElement.cpp.mustache diff --git a/modules/openapi-generator/src/main/resources/cpp-qt5-client/HttpFileElement.h.mustache b/modules/openapi-generator/src/main/resources/cpp-qt-client/HttpFileElement.h.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/cpp-qt5-client/HttpFileElement.h.mustache rename to modules/openapi-generator/src/main/resources/cpp-qt-client/HttpFileElement.h.mustache diff --git a/modules/openapi-generator/src/main/resources/cpp-qt5-client/HttpRequest.cpp.mustache b/modules/openapi-generator/src/main/resources/cpp-qt-client/HttpRequest.cpp.mustache similarity index 99% rename from modules/openapi-generator/src/main/resources/cpp-qt5-client/HttpRequest.cpp.mustache rename to modules/openapi-generator/src/main/resources/cpp-qt-client/HttpRequest.cpp.mustache index 5eca0f0f0a4..bf88363b51c 100644 --- a/modules/openapi-generator/src/main/resources/cpp-qt5-client/HttpRequest.cpp.mustache +++ b/modules/openapi-generator/src/main/resources/cpp-qt-client/HttpRequest.cpp.mustache @@ -328,7 +328,7 @@ void {{prefix}}HttpRequestWorker::execute({{prefix}}HttpRequestInput *input) { if ({{prefix}}HttpRequestWorker::sslDefaultConfiguration != nullptr) { request.setSslConfiguration(*{{prefix}}HttpRequestWorker::sslDefaultConfiguration); } - request.setRawHeader("User-Agent", "{{#httpUserAgent}}{{.}}{{/httpUserAgent}}{{^httpUserAgent}}OpenAPI-Generator/{{apiVersion}}/cpp-qt5{{/httpUserAgent}}"); + request.setRawHeader("User-Agent", "{{#httpUserAgent}}{{.}}{{/httpUserAgent}}{{^httpUserAgent}}OpenAPI-Generator/{{apiVersion}}/cpp-qt{{/httpUserAgent}}"); foreach (QString key, input->headers.keys()) { request.setRawHeader(key.toStdString().c_str(), input->headers.value(key).toStdString().c_str()); } if (request_content.size() > 0 && !isFormData && (input->var_layout != MULTIPART)) { diff --git a/modules/openapi-generator/src/main/resources/cpp-qt5-client/HttpRequest.h.mustache b/modules/openapi-generator/src/main/resources/cpp-qt-client/HttpRequest.h.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/cpp-qt5-client/HttpRequest.h.mustache rename to modules/openapi-generator/src/main/resources/cpp-qt-client/HttpRequest.h.mustache diff --git a/modules/openapi-generator/src/main/resources/cpp-qt5-client/Project.mustache b/modules/openapi-generator/src/main/resources/cpp-qt-client/Project.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/cpp-qt5-client/Project.mustache rename to modules/openapi-generator/src/main/resources/cpp-qt-client/Project.mustache diff --git a/modules/openapi-generator/src/main/resources/cpp-qt5-client/README.mustache b/modules/openapi-generator/src/main/resources/cpp-qt-client/README.mustache similarity index 98% rename from modules/openapi-generator/src/main/resources/cpp-qt5-client/README.mustache rename to modules/openapi-generator/src/main/resources/cpp-qt-client/README.mustache index 5f319457532..9692bf79152 100644 --- a/modules/openapi-generator/src/main/resources/cpp-qt5-client/README.mustache +++ b/modules/openapi-generator/src/main/resources/cpp-qt-client/README.mustache @@ -53,10 +53,10 @@ At first generate the JAR by executing: mvn clean package ``` -Use the Jar file to generate the Qt5 Client: +Use the Jar file to generate the Qt Client: ```shell -java -jar target/openapi-generator-cli.jar generate -i -g cpp-qt5-client -o +java -jar target/openapi-generator-cli.jar generate -i -g cpp-qt-client -o ``` ## Getting Started diff --git a/modules/openapi-generator/src/main/resources/cpp-qt5-client/ServerConfiguration.mustache b/modules/openapi-generator/src/main/resources/cpp-qt-client/ServerConfiguration.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/cpp-qt5-client/ServerConfiguration.mustache rename to modules/openapi-generator/src/main/resources/cpp-qt-client/ServerConfiguration.mustache diff --git a/modules/openapi-generator/src/main/resources/cpp-qt5-client/ServerVariable.mustache b/modules/openapi-generator/src/main/resources/cpp-qt-client/ServerVariable.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/cpp-qt5-client/ServerVariable.mustache rename to modules/openapi-generator/src/main/resources/cpp-qt-client/ServerVariable.mustache diff --git a/modules/openapi-generator/src/main/resources/cpp-qt5-client/api-body.mustache b/modules/openapi-generator/src/main/resources/cpp-qt-client/api-body.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/cpp-qt5-client/api-body.mustache rename to modules/openapi-generator/src/main/resources/cpp-qt-client/api-body.mustache diff --git a/modules/openapi-generator/src/main/resources/cpp-qt5-client/api-header.mustache b/modules/openapi-generator/src/main/resources/cpp-qt-client/api-header.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/cpp-qt5-client/api-header.mustache rename to modules/openapi-generator/src/main/resources/cpp-qt-client/api-header.mustache diff --git a/modules/openapi-generator/src/main/resources/cpp-qt5-client/enum.mustache b/modules/openapi-generator/src/main/resources/cpp-qt-client/enum.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/cpp-qt5-client/enum.mustache rename to modules/openapi-generator/src/main/resources/cpp-qt-client/enum.mustache diff --git a/modules/openapi-generator/src/main/resources/cpp-qt5-client/helpers-body.mustache b/modules/openapi-generator/src/main/resources/cpp-qt-client/helpers-body.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/cpp-qt5-client/helpers-body.mustache rename to modules/openapi-generator/src/main/resources/cpp-qt-client/helpers-body.mustache diff --git a/modules/openapi-generator/src/main/resources/cpp-qt5-client/helpers-header.mustache b/modules/openapi-generator/src/main/resources/cpp-qt-client/helpers-header.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/cpp-qt5-client/helpers-header.mustache rename to modules/openapi-generator/src/main/resources/cpp-qt-client/helpers-header.mustache diff --git a/modules/openapi-generator/src/main/resources/cpp-qt5-client/licenseInfo.mustache b/modules/openapi-generator/src/main/resources/cpp-qt-client/licenseInfo.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/cpp-qt5-client/licenseInfo.mustache rename to modules/openapi-generator/src/main/resources/cpp-qt-client/licenseInfo.mustache diff --git a/modules/openapi-generator/src/main/resources/cpp-qt5-client/model-body.mustache b/modules/openapi-generator/src/main/resources/cpp-qt-client/model-body.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/cpp-qt5-client/model-body.mustache rename to modules/openapi-generator/src/main/resources/cpp-qt-client/model-body.mustache diff --git a/modules/openapi-generator/src/main/resources/cpp-qt5-client/model-header.mustache b/modules/openapi-generator/src/main/resources/cpp-qt-client/model-header.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/cpp-qt5-client/model-header.mustache rename to modules/openapi-generator/src/main/resources/cpp-qt-client/model-header.mustache diff --git a/modules/openapi-generator/src/main/resources/cpp-qt5-client/object.mustache b/modules/openapi-generator/src/main/resources/cpp-qt-client/object.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/cpp-qt5-client/object.mustache rename to modules/openapi-generator/src/main/resources/cpp-qt-client/object.mustache diff --git a/modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/CMakeLists.txt.mustache b/modules/openapi-generator/src/main/resources/cpp-qt-qhttpengine-server/CMakeLists.txt.mustache similarity index 93% rename from modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/CMakeLists.txt.mustache rename to modules/openapi-generator/src/main/resources/cpp-qt-qhttpengine-server/CMakeLists.txt.mustache index 54e6d36d73f..71b8bdb45f4 100644 --- a/modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/CMakeLists.txt.mustache +++ b/modules/openapi-generator/src/main/resources/cpp-qt-qhttpengine-server/CMakeLists.txt.mustache @@ -1,5 +1,5 @@ cmake_minimum_required(VERSION 3.2 FATAL_ERROR) -project(cpp-qt5-qhttpengine-server) +project(cpp-qt-qhttpengine-server) include(ExternalProject) diff --git a/modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/Dockerfile.mustache b/modules/openapi-generator/src/main/resources/cpp-qt-qhttpengine-server/Dockerfile.mustache similarity index 78% rename from modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/Dockerfile.mustache rename to modules/openapi-generator/src/main/resources/cpp-qt-qhttpengine-server/Dockerfile.mustache index b0c591d10f6..9dfdd9ab478 100644 --- a/modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/Dockerfile.mustache +++ b/modules/openapi-generator/src/main/resources/cpp-qt-qhttpengine-server/Dockerfile.mustache @@ -23,7 +23,7 @@ RUN apk add --update \ openssl WORKDIR /usr/server -COPY --from=build /usr/server/build/src/cpp-qt5-qhttpengine-server ./build/src/ +COPY --from=build /usr/server/build/src/cpp-qt-qhttpengine-server ./build/src/ COPY --from=build /usr/server/external/ ./external EXPOSE 8080/tcp -ENTRYPOINT ["/usr/server/build/src/cpp-qt5-qhttpengine-server"] \ No newline at end of file +ENTRYPOINT ["/usr/server/build/src/cpp-qt-qhttpengine-server"] diff --git a/modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/HttpFileElement.cpp.mustache b/modules/openapi-generator/src/main/resources/cpp-qt-qhttpengine-server/HttpFileElement.cpp.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/HttpFileElement.cpp.mustache rename to modules/openapi-generator/src/main/resources/cpp-qt-qhttpengine-server/HttpFileElement.cpp.mustache diff --git a/modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/HttpFileElement.h.mustache b/modules/openapi-generator/src/main/resources/cpp-qt-qhttpengine-server/HttpFileElement.h.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/HttpFileElement.h.mustache rename to modules/openapi-generator/src/main/resources/cpp-qt-qhttpengine-server/HttpFileElement.h.mustache diff --git a/modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/LICENSE.txt.mustache b/modules/openapi-generator/src/main/resources/cpp-qt-qhttpengine-server/LICENSE.txt.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/LICENSE.txt.mustache rename to modules/openapi-generator/src/main/resources/cpp-qt-qhttpengine-server/LICENSE.txt.mustache diff --git a/modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/Makefile.mustache b/modules/openapi-generator/src/main/resources/cpp-qt-qhttpengine-server/Makefile.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/Makefile.mustache rename to modules/openapi-generator/src/main/resources/cpp-qt-qhttpengine-server/Makefile.mustache diff --git a/modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/README.md.mustache b/modules/openapi-generator/src/main/resources/cpp-qt-qhttpengine-server/README.md.mustache similarity index 89% rename from modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/README.md.mustache rename to modules/openapi-generator/src/main/resources/cpp-qt-qhttpengine-server/README.md.mustache index e5439dcae3b..68ec6bf4369 100644 --- a/modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/README.md.mustache +++ b/modules/openapi-generator/src/main/resources/cpp-qt-qhttpengine-server/README.md.mustache @@ -1,6 +1,6 @@ -# C++ Qt5 Server +# C++ Qt Server -## Qt5 HTTP Server based on the Qhttpengine +## Qt HTTP Server based on the Qhttpengine 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. @@ -50,18 +50,18 @@ make To run the server ```shell -./build/src/cpp-qt5-qhttpengine-server & +./build/src/cpp-qt-qhttpengine-server & ``` To override the default port via the command line, provide the parameters `port` and `address` like below ```shell -cpp-qt5-qhttpengine-server --port 9080 --address 127.17.0.1 +cpp-qt-qhttpengine-server --port 9080 --address 127.17.0.1 ``` or ```shell -cpp-qt5-qhttpengine-server -p 9080 -a 127.17.0.1 +cpp-qt-qhttpengine-server -p 9080 -a 127.17.0.1 ``` #### Invoke an API @@ -80,13 +80,13 @@ If you dont have docker install [here](https://docs.docker.com/install) Add yourself to the docker group ```shell -docker build --network=host -t cpp-qt5-qhttpengine-server . +docker build --network=host -t cpp-qt-qhttpengine-server . ``` Running with docker ```shell -docker run --rm -it --name=server-container cpp-qt5-qhttpengine-server +docker run --rm -it --name=server-container cpp-qt-qhttpengine-server ``` #### Invoking an API diff --git a/modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/apihandler.cpp.mustache b/modules/openapi-generator/src/main/resources/cpp-qt-qhttpengine-server/apihandler.cpp.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/apihandler.cpp.mustache rename to modules/openapi-generator/src/main/resources/cpp-qt-qhttpengine-server/apihandler.cpp.mustache diff --git a/modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/apihandler.h.mustache b/modules/openapi-generator/src/main/resources/cpp-qt-qhttpengine-server/apihandler.h.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/apihandler.h.mustache rename to modules/openapi-generator/src/main/resources/cpp-qt-qhttpengine-server/apihandler.h.mustache diff --git a/modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/apirequest.cpp.mustache b/modules/openapi-generator/src/main/resources/cpp-qt-qhttpengine-server/apirequest.cpp.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/apirequest.cpp.mustache rename to modules/openapi-generator/src/main/resources/cpp-qt-qhttpengine-server/apirequest.cpp.mustache diff --git a/modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/apirequest.h.mustache b/modules/openapi-generator/src/main/resources/cpp-qt-qhttpengine-server/apirequest.h.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/apirequest.h.mustache rename to modules/openapi-generator/src/main/resources/cpp-qt-qhttpengine-server/apirequest.h.mustache diff --git a/modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/apirouter.cpp.mustache b/modules/openapi-generator/src/main/resources/cpp-qt-qhttpengine-server/apirouter.cpp.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/apirouter.cpp.mustache rename to modules/openapi-generator/src/main/resources/cpp-qt-qhttpengine-server/apirouter.cpp.mustache diff --git a/modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/apirouter.h.mustache b/modules/openapi-generator/src/main/resources/cpp-qt-qhttpengine-server/apirouter.h.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/apirouter.h.mustache rename to modules/openapi-generator/src/main/resources/cpp-qt-qhttpengine-server/apirouter.h.mustache diff --git a/modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/enum.mustache b/modules/openapi-generator/src/main/resources/cpp-qt-qhttpengine-server/enum.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/enum.mustache rename to modules/openapi-generator/src/main/resources/cpp-qt-qhttpengine-server/enum.mustache diff --git a/modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/helpers-body.mustache b/modules/openapi-generator/src/main/resources/cpp-qt-qhttpengine-server/helpers-body.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/helpers-body.mustache rename to modules/openapi-generator/src/main/resources/cpp-qt-qhttpengine-server/helpers-body.mustache diff --git a/modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/helpers-header.mustache b/modules/openapi-generator/src/main/resources/cpp-qt-qhttpengine-server/helpers-header.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/helpers-header.mustache rename to modules/openapi-generator/src/main/resources/cpp-qt-qhttpengine-server/helpers-header.mustache diff --git a/modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/licenseInfo.mustache b/modules/openapi-generator/src/main/resources/cpp-qt-qhttpengine-server/licenseInfo.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/licenseInfo.mustache rename to modules/openapi-generator/src/main/resources/cpp-qt-qhttpengine-server/licenseInfo.mustache diff --git a/modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/main.cpp.mustache b/modules/openapi-generator/src/main/resources/cpp-qt-qhttpengine-server/main.cpp.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/main.cpp.mustache rename to modules/openapi-generator/src/main/resources/cpp-qt-qhttpengine-server/main.cpp.mustache diff --git a/modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/model-body.mustache b/modules/openapi-generator/src/main/resources/cpp-qt-qhttpengine-server/model-body.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/model-body.mustache rename to modules/openapi-generator/src/main/resources/cpp-qt-qhttpengine-server/model-body.mustache diff --git a/modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/model-header.mustache b/modules/openapi-generator/src/main/resources/cpp-qt-qhttpengine-server/model-header.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/model-header.mustache rename to modules/openapi-generator/src/main/resources/cpp-qt-qhttpengine-server/model-header.mustache diff --git a/modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/object.mustache b/modules/openapi-generator/src/main/resources/cpp-qt-qhttpengine-server/object.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/object.mustache rename to modules/openapi-generator/src/main/resources/cpp-qt-qhttpengine-server/object.mustache diff --git a/modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/src-CMakeLists.txt.mustache b/modules/openapi-generator/src/main/resources/cpp-qt-qhttpengine-server/src-CMakeLists.txt.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/cpp-qt5-qhttpengine-server/src-CMakeLists.txt.mustache rename to modules/openapi-generator/src/main/resources/cpp-qt-qhttpengine-server/src-CMakeLists.txt.mustache diff --git a/modules/openapi-generator/src/main/resources/cpp-rest-sdk-client/modelbase-source.mustache b/modules/openapi-generator/src/main/resources/cpp-rest-sdk-client/modelbase-source.mustache index cfe9c44fecc..faa2333603a 100644 --- a/modules/openapi-generator/src/main/resources/cpp-rest-sdk-client/modelbase-source.mustache +++ b/modules/openapi-generator/src/main/resources/cpp-rest-sdk-client/modelbase-source.mustache @@ -249,13 +249,13 @@ bool ModelBase::fromJson( const web::json::value& val, bool & outVal ) } bool ModelBase::fromJson( const web::json::value& val, float & outVal ) { - outVal = !val.is_double() ? std::numeric_limits::quiet_NaN(): static_cast(val.as_double()); - return val.is_double(); + outVal = (!val.is_double() && !val.is_integer()) ? std::numeric_limits::quiet_NaN(): static_cast(val.as_double()); + return val.is_double() || val.is_integer(); } bool ModelBase::fromJson( const web::json::value& val, double & outVal ) { - outVal = !val.is_double() ? std::numeric_limits::quiet_NaN(): val.as_double(); - return val.is_double() ; + outVal = (!val.is_double() && !val.is_integer()) ? std::numeric_limits::quiet_NaN(): val.as_double(); + return val.is_double() || val.is_integer(); } bool ModelBase::fromJson( const web::json::value& val, int32_t & outVal ) { diff --git a/modules/openapi-generator/src/main/resources/cpp-tiny/README.mustache b/modules/openapi-generator/src/main/resources/cpp-tiny/README.mustache new file mode 100644 index 00000000000..e749562a0aa --- /dev/null +++ b/modules/openapi-generator/src/main/resources/cpp-tiny/README.mustache @@ -0,0 +1,43 @@ +# Documentation for OpenAPI Petstore +This is a client generator for microcontrollers on the Espressif32 platform and the Arduino framework +After the client have been generated, you have to change these following variablies: +- root.cert | Provide your service root certificate. +- src/main.cpp | Change wifi name +- src/main.cpp | Change wifi password +- lib/service/AbstractService.h | Change to your url + +# Documentation for {{#openAPI}}{{#info}}{{title}} {{version}} Tiny client cpp (Arduino) {{/info}}{{/openAPI}} + +The project is structured like this: +``` +samples/client/petstore/tiny/cpp/ +├── lib +│ ├── Models +│ ├── service +│ └── TestFiles +├── platformio.ini +├── pre_compiling_bourne.py +├── README.md +├── root.cert +├── src +│ └── main.cpp +└── test + └── RunTests.cpp +``` + +All URIs are relative to {{{scheme}}}://{{{host}}}{{{basePath}}} +{{#apiInfo}}{{#apis}}{{#operations}} +### {{classname}} +|Method | HTTP request | Description| +|------------- | ------------- | -------------| + {{#operation}} +|*{{operationId}}* | *{{httpMethod}}* {{{path}}} | {{{summary}}}.| + {{/operation}} +{{/operations}}{{/apis}}{{/apiInfo}} + +## What are the Model files for the data structures/objects? +|Class | Description| +|------------- | -------------| +{{#models}}{{#model}}|*{{classname}}* | {{{description}}}| +{{/model}}{{/models}} + diff --git a/modules/openapi-generator/src/main/resources/cpp-tiny/helpers-body.mustache b/modules/openapi-generator/src/main/resources/cpp-tiny/helpers-body.mustache new file mode 100644 index 00000000000..c3935b37cde --- /dev/null +++ b/modules/openapi-generator/src/main/resources/cpp-tiny/helpers-body.mustache @@ -0,0 +1,102 @@ +#include "Helpers.h" +#include +#include + +bool isprimitive(std::string type){ + if(type == "std::string" || + type == "int" || + type == "float" || + type == "long" || + type == "double" || + type == "bool" || + type == "std::map" || + type == "std::list") + { + return true; + } + return false; +} + + +void +jsonToValue(void* target, bourne::json value, std::string type) +{ + if (target == NULL || value.is_null()) { + return; + } + + else if (type.compare("bool") == 0) + { + bool* val = static_cast (target); + *val = value.to_bool(); + } + + else if (type.compare("int") == 0) + { + int* val = static_cast (target); + *val = value.to_int(); + } + + else if (type.compare("float") == 0) + { + float* val = static_cast (target); + *val = (float)(value.to_float()); + } + + else if (type.compare("long") == 0) + { + long* val = static_cast (target); + *val = (long)(value.to_int()); + } + + else if (type.compare("double") == 0) + { + double* val = static_cast (target); + *val = value.to_float(); + } + + else if (type.compare("std::string") == 0) + { + std::string* val = static_cast (target); + *val = value.to_string(); + } + else { + return; + } +} + +std::string +stringify(long input){ + std::stringstream stream; + stream << input; + return stream.str(); + +}; + +std::string +stringify(int input){ + std::stringstream stream; + stream << input; + return stream.str(); +}; + +std::string +stringify(double input){ + std::stringstream stream; + stream << input; + return stream.str(); +}; + +std::string +stringify(float input){ + std::stringstream stream; + stream << input; + return stream.str(); +}; + +std::string +stringify(std::string input){ + std::stringstream stream; + stream << input; + return stream.str(); +}; diff --git a/modules/openapi-generator/src/main/resources/cpp-tiny/helpers-header.mustache b/modules/openapi-generator/src/main/resources/cpp-tiny/helpers-header.mustache new file mode 100644 index 00000000000..5ef7d9afdf7 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/cpp-tiny/helpers-header.mustache @@ -0,0 +1,22 @@ +#ifndef TINY_CPP_CLIENT_HELPERS_H_ +#define TINY_CPP_CLIENT_HELPERS_H_ + +#include +#include "bourne/json.hpp" + +bool isprimitive(std::string type); + +void jsonToValue(void* target, bourne::json value, std::string type); + +std::string stringify(long input); + +std::string stringify(int input); + +std::string stringify(double input); + +std::string stringify(float input); + +std::string stringify(std::string input); + +#endif /* TINY_CPP_CLIENT_HELPERS_H_ */ + diff --git a/modules/openapi-generator/src/main/resources/cpp-tiny/main.mustache b/modules/openapi-generator/src/main/resources/cpp-tiny/main.mustache new file mode 100644 index 00000000000..56170a91e0f --- /dev/null +++ b/modules/openapi-generator/src/main/resources/cpp-tiny/main.mustache @@ -0,0 +1,40 @@ +#include "PetApi.h" +{{#isESP8266}} +#include "ESP8266WiFi.h" +{{/isESP8266}} + +const char* ssid = "your wifi name"; // TODO Change wifi name +const char* password = "Your wifi password"; //TODO Change wifi password + + +void setup(){ + //Initialize serial and wait for port to open: + Serial.begin(9600); + delay(100); + + Serial.print("Attempting to connect to SSID: "); + Serial.println(ssid); + WiFi.begin(ssid, password); + + // attempt to connect to Wifi network: + while (WiFi.status() != WL_CONNECTED) { + Serial.print("."); + // wait 1 second for re-trying + delay(1000); + } + + Serial.print("Connected to "); + Serial.println(ssid); + + //Print LAN IP. + Serial.print("IP address set: "); + Serial.println(WiFi.localIP()); + + Tiny::PetApi petapi; + auto resp = petapi.getPetById(10); + Serial.println(resp.code); + Tiny::Pet pet = resp.obj; + Serial.println(pet.toJson().dump().c_str()); +} + +void loop(){} diff --git a/modules/openapi-generator/src/main/resources/cpp-tiny/model-body.mustache b/modules/openapi-generator/src/main/resources/cpp-tiny/model-body.mustache new file mode 100644 index 00000000000..b2f2ee66fd9 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/cpp-tiny/model-body.mustache @@ -0,0 +1,160 @@ + +{{#models}}{{#model}} +#include "{{classname}}.h" + +using namespace Tiny; + +{{classname}}::{{classname}}() +{ + {{#vars}} + {{#isContainer}} + {{name}} = {{defaultValue}}<{{#items}}{{baseType}}{{/items}}>(); + {{/isContainer}} + {{^isContainer}} + {{name}} = {{defaultValue}}; + {{/isContainer}} + {{/vars}} +} + +{{classname}}::{{classname}}(std::string jsonString) +{ + this->fromJson(jsonString); +} + +{{classname}}::~{{classname}}() +{ + +} + +void +{{classname}}::fromJson(std::string jsonObj) +{ + bourne::json object = bourne::json::parse(jsonObj); + + {{#vars}} + const char *{{name}}Key = "{{baseName}}"; + + if(object.has_key({{name}}Key)) + { + bourne::json value = object[{{name}}Key]; + + {{#isContainer}} + {{#isArray}} + + std::list<{{#items}}{{dataType}}{{/items}}> {{name}}_list; + {{#items}}{{dataType}}{{/items}} element; + for(auto& var : value.array_range()) + { + {{#items}} + + {{#isPrimitiveType}} + jsonToValue(&element, var, "{{dataType}}"); + {{/isPrimitiveType}} + + {{^isPrimitiveType}} + element.fromJson(var.dump()); + {{/isPrimitiveType}} + + {{/items}} + {{name}}_list.push_back(element); + } + {{name}} = {{name}}_list; + + {{/isArray}} + {{/isContainer}} + + {{^isContainer}} + + {{#isPrimitiveType}} + jsonToValue(&{{name}}, value, "{{baseType}}"); + {{/isPrimitiveType}} + + {{^isPrimitiveType}} + {{baseType}}* obj = &{{name}}; + obj->fromJson(value.dump()); + {{/isPrimitiveType}} + + {{/isContainer}} + } + + {{/vars}} + +} + +bourne::json +{{classname}}::toJson() +{ + bourne::json object = bourne::json::object(); + + {{#vars}} + + {{#isContainer}} + {{#isArray}} + + {{#items}} + {{#isPrimitiveType}} + + std::list<{{dataType}}> {{name}}_list = {{getter}}(); + bourne::json {{name}}_arr = bourne::json::array(); + + for(auto& var : {{name}}_list) + { + {{name}}_arr.append(var); + } + object["{{name}}"] = {{name}}_arr; + + + {{/isPrimitiveType}} + + {{^isPrimitiveType}} + std::list<{{dataType}}> {{name}}_list = {{getter}}(); + bourne::json {{name}}_arr = bourne::json::array(); + + for(auto& var : {{name}}_list) + { + {{dataType}} obj = var; + {{name}}_arr.append(obj.toJson()); + } + object["{{name}}"] = {{name}}_arr; + + {{/isPrimitiveType}} + {{/items}} + {{/isArray}} + {{/isContainer}} + + + {{^isContainer}} + + {{#isPrimitiveType}} + object["{{name}}"] = {{getter}}(); + {{/isPrimitiveType}} + + {{^isPrimitiveType}} + object["{{name}}"] = {{getter}}().toJson(); + {{/isPrimitiveType}} + + {{/isContainer}} + {{/vars}} + + return object; + +} + +{{#vars}} +{{dataType}}{{#isContainer}}{{#isMap}}{{/isMap}}{{^isMap}}<{{#items}}{{dataType}}{{/items}}>{{/isMap}}{{/isContainer}} +{{classname}}::{{getter}}() +{ + return {{name}}; +} + +void +{{classname}}::{{setter}}({{dataType}} {{#isContainer}}{{#isMap}}{{/isMap}}{{^isMap}}<{{#items}}{{dataType}}{{/items}}>{{/isMap}}{{/isContainer}} {{name}}) +{ + this->{{name}} = {{name}}; +} + +{{/vars}} + + +{{/model}} +{{/models}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/cpp-tiny/model-header.mustache b/modules/openapi-generator/src/main/resources/cpp-tiny/model-header.mustache new file mode 100644 index 00000000000..a71ba0677c1 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/cpp-tiny/model-header.mustache @@ -0,0 +1,81 @@ + +{{#models}}{{#model}}/* + * {{classname}}.h + * + * {{description}} + */ + +#ifndef TINY_CPP_CLIENT_{{classname}}_H_ +#define TINY_CPP_CLIENT_{{classname}}_H_ + +{{/model}}{{/models}} +#include +#include "bourne/json.hpp" +#include "Helpers.h" +{{#imports}} +{{{import}}} +{{/imports}} + +namespace Tiny { +{{#models}}{{#model}} + +/*! \brief {{{description}}} + * + * \ingroup Models + * + */ + +class {{classname}}{ +public: + + /*! \brief Constructor. + */ + {{classname}}(); + {{classname}}(std::string jsonString); + + + /*! \brief Destructor. + */ + virtual ~{{classname}}(); + + + /*! \brief Retrieve a bourne JSON representation of this class. + */ + bourne::json toJson(); + + + /*! \brief Fills in members of this class from bourne JSON object representing it. + */ + void fromJson(std::string jsonObj); + + {{#vars}} + /*! \brief Get {{{description}}} + */ + {{dataType}}{{#isContainer}}{{#isMap}}{{/isMap}}{{^isMap}}<{{#items}}{{dataType}}{{/items}}>{{/isMap}}{{/isContainer}} {{getter}}(); + + /*! \brief Set {{{description}}} + */ + void {{setter}}({{dataType}} {{#isContainer}}{{#isMap}}{{/isMap}}{{^isMap}}<{{#items}}{{dataType}}{{/items}}>{{/isMap}}{{/isContainer}} {{name}}); + {{/vars}} + + + private: + {{#vars}} + {{^isContainer}} + {{#isPrimitiveType}} + {{dataType}} {{name}}{}; + {{/isPrimitiveType}} + {{^isPrimitiveType}} + {{dataType}} {{name}}; + {{/isPrimitiveType}} + {{/isContainer}} + {{#isContainer}} + {{dataType}}{{#isMap}}{{/isMap}}{{^isMap}}<{{#items}}{{dataType}}{{/items}}>{{/isMap}} {{name}}; + {{/isContainer}} + {{/vars}} +}; +{{/model}} +{{/models}} +} + +#endif /* TINY_CPP_CLIENT_{{classname}}_H_ */ diff --git a/modules/openapi-generator/src/main/resources/cpp-tiny/platformio.ini.mustache b/modules/openapi-generator/src/main/resources/cpp-tiny/platformio.ini.mustache new file mode 100644 index 00000000000..1e364ee0ab2 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/cpp-tiny/platformio.ini.mustache @@ -0,0 +1,19 @@ +{{#isESP32}} +[env:esp32] +platform = espressif32 +board = nodemcu-32s +framework = arduino +lib_deps = https://github.com/steinwurf/bourne.git +extra_scripts = pre_compiling_bourne.py +{{/isESP32}} + +{{#isESP8266}} +[env:esp8266] +platform = espressif8266 +board = d1_mini +framework = arduino +lib_deps = https://github.com/steinwurf/bourne.git +build_flags = -fexceptions +build_unflags = -fno-exceptions +extra_scripts = pre_compiling_bourne.py +{{/isESP8266}} diff --git a/modules/openapi-generator/src/main/resources/cpp-tiny/pre_compiling_bourne.py.mustache b/modules/openapi-generator/src/main/resources/cpp-tiny/pre_compiling_bourne.py.mustache new file mode 100644 index 00000000000..96356dcdf15 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/cpp-tiny/pre_compiling_bourne.py.mustache @@ -0,0 +1,25 @@ +Import("env") + +## Compatibility for bourne to work on microcontrollers +# We insert '#define _GLIBCXX_USE_C99' in files that use std::stoll or std::to_string +def insert_c99_into(file): + import fileinput + + path = env['PROJECT_LIBDEPS_DIR'] + "/" + env['PIOENV'] + "/bourne/src/bourne/" + file + value = '#define _GLIBCXX_USE_C99 1\n' + + for line in fileinput.FileInput(path,inplace=1): + if line.startswith('#define _GLIBCXX_USE_C99'): + continue + elif line.startswith('// D'): + line=line.replace(line,line+value) + print(line, end='') + +def fix_parser(): + insert_c99_into('detail/parser.cpp') + +def fix_json(): + insert_c99_into('json.cpp') + +fix_parser() +fix_json() \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/cpp-tiny/root.cert.mustache b/modules/openapi-generator/src/main/resources/cpp-tiny/root.cert.mustache new file mode 100644 index 00000000000..bad9c08efad --- /dev/null +++ b/modules/openapi-generator/src/main/resources/cpp-tiny/root.cert.mustache @@ -0,0 +1,53 @@ +// TODO: Provide your service root certificate. +// Below is two examples of root certificates. + +// Let's encrypt root certificate +/** +"-----BEGIN CERTIFICATE-----\n" \ +"MIIDrzCCApegAwIBAgIQCDvgVpBCRrGhdWrJWZHHSjANBgkqhkiG9w0BAQUFADBh\n" \ +"MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3\n" \ +"d3cuZGlnaWNlcnQuY29tMSAwHgYDVQQDExdEaWdpQ2VydCBHbG9iYWwgUm9vdCBD\n" \ +"QTAeFw0wNjExMTAwMDAwMDBaFw0zMTExMTAwMDAwMDBaMGExCzAJBgNVBAYTAlVT\n" \ +"MRUwEwYDVQQKEwxEaWdpQ2VydCBJbmMxGTAXBgNVBAsTEHd3dy5kaWdpY2VydC5j\n" \ +"b20xIDAeBgNVBAMTF0RpZ2lDZXJ0IEdsb2JhbCBSb290IENBMIIBIjANBgkqhkiG\n" \ +"9w0BAQEFAAOCAQ8AMIIBCgKCAQEA4jvhEXLeqKTTo1eqUKKPC3eQyaKl7hLOllsB\n" \ +"CSDMAZOnTjC3U/dDxGkAV53ijSLdhwZAAIEJzs4bg7/fzTtxRuLWZscFs3YnFo97\n" \ +"nh6Vfe63SKMI2tavegw5BmV/Sl0fvBf4q77uKNd0f3p4mVmFaG5cIzJLv07A6Fpt\n" \ +"43C/dxC//AH2hdmoRBBYMql1GNXRor5H4idq9Joz+EkIYIvUX7Q6hL+hqkpMfT7P\n" \ +"T19sdl6gSzeRntwi5m3OFBqOasv+zbMUZBfHWymeMr/y7vrTC0LUq7dBMtoM1O/4\n" \ +"gdW7jVg/tRvoSSiicNoxBN33shbyTApOB6jtSj1etX+jkMOvJwIDAQABo2MwYTAO\n" \ +"BgNVHQ8BAf8EBAMCAYYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUA95QNVbR\n" \ +"TLtm8KPiGxvDl7I90VUwHwYDVR0jBBgwFoAUA95QNVbRTLtm8KPiGxvDl7I90VUw\n" \ +"DQYJKoZIhvcNAQEFBQADggEBAMucN6pIExIK+t1EnE9SsPTfrgT1eXkIoyQY/Esr\n" \ +"hMAtudXH/vTBH1jLuG2cenTnmCmrEbXjcKChzUyImZOMkXDiqw8cvpOp/2PV5Adg\n" \ +"06O/nVsJ8dWO41P0jmP6P6fbtGbfYmbW0W5BjfIttep3Sp+dWOIrWcBAI+0tKIJF\n" \ +"PnlUkiaY4IBIqDfv8NZ5YBberOgOzW6sRBc4L0na4UU+Krk2U886UAb3LujEV0ls\n" \ +"YSEY1QSteDwsOoBrp+uvFRTp2InBuThs4pFsiv9kuXclVzDAGySj4dzp30d8tbQk\n" \ +"CAUw7C29C79Fv1C5qfPrmAESrciIxpg0X40KPMbp1ZWVbd4=\n" \ +"-----END CERTIFICATE-----\n" +*/ + +// Amazon_Root_CA_1.pem +/** +"-----BEGIN CERTIFICATE-----\n" \ +"MIIDQTCCAimgAwIBAgITBmyfz5m/jAo54vB4ikPmljZbyjANBgkqhkiG9w0BAQsF\n" \ +"ADA5MQswCQYDVQQGEwJVUzEPMA0GA1UEChMGQW1hem9uMRkwFwYDVQQDExBBbWF6\n" \ +"b24gUm9vdCBDQSAxMB4XDTE1MDUyNjAwMDAwMFoXDTM4MDExNzAwMDAwMFowOTEL\n" \ +"MAkGA1UEBhMCVVMxDzANBgNVBAoTBkFtYXpvbjEZMBcGA1UEAxMQQW1hem9uIFJv\n" \ +"b3QgQ0EgMTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALJ4gHHKeNXj\n" \ +"ca9HgFB0fW7Y14h29Jlo91ghYPl0hAEvrAIthtOgQ3pOsqTQNroBvo3bSMgHFzZM\n" \ +"9O6II8c+6zf1tRn4SWiw3te5djgdYZ6k/oI2peVKVuRF4fn9tBb6dNqcmzU5L/qw\n" \ +"IFAGbHrQgLKm+a/sRxmPUDgH3KKHOVj4utWp+UhnMJbulHheb4mjUcAwhmahRWa6\n" \ +"VOujw5H5SNz/0egwLX0tdHA114gk957EWW67c4cX8jJGKLhD+rcdqsq08p8kDi1L\n" \ +"93FcXmn/6pUCyziKrlA4b9v7LWIbxcceVOF34GfID5yHI9Y/QCB/IIDEgEw+OyQm\n" \ +"jgSubJrIqg0CAwEAAaNCMEAwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMC\n" \ +"AYYwHQYDVR0OBBYEFIQYzIU07LwMlJQuCFmcx7IQTgoIMA0GCSqGSIb3DQEBCwUA\n" \ +"A4IBAQCY8jdaQZChGsV2USggNiMOruYou6r4lK5IpDB/G/wkjUu0yKGX9rbxenDI\n" \ +"U5PMCCjjmCXPI6T53iHTfIUJrU6adTrCC2qJeHZERxhlbI1Bjjt/msv0tadQ1wUs\n" \ +"N+gDS63pYaACbvXy8MWy7Vu33PqUXHeeE6V/Uq2V8viTO96LXFvKWlJbYK8U90vv\n" \ +"o/ufQJVtMVT8QtPHRh8jrdkPSHCa2XV4cdFyQzR1bldZwgJcJmApzyMZFo6IQ6XU\n" \ +"5MsI+yMRQ+hDKXJioaldXgjUkK642M4UwtBV8ob2xJNDd2ZhwLnoQdeXeGADbkpy\n" \ +"rqXRfboQnoZsG4q5WTP468SQvvG5\n" \ +"-----END CERTIFICATE-----\n" \ +*/ + diff --git a/modules/openapi-generator/src/main/resources/cpp-tiny/run-tests.mustache b/modules/openapi-generator/src/main/resources/cpp-tiny/run-tests.mustache new file mode 100644 index 00000000000..54bf326c43a --- /dev/null +++ b/modules/openapi-generator/src/main/resources/cpp-tiny/run-tests.mustache @@ -0,0 +1,44 @@ +{{#models}}{{#model}} +#include "{{classname}}Test.cpp" +{{/model}}{{/models}} + + +void setUp(){} + +void tearDown(){} + +void runTests(){ + {{#models}}{{#model}} + {{#vars}} + {{#isPrimitiveType}}{{^isArray}} + RUN_TEST(test_{{classname}}_{{name}}_is_assigned_from_json); + {{/isArray}}{{/isPrimitiveType}} + {{/vars}} + {{/model}}{{/models}} + + {{#models}}{{#model}} + {{#vars}} + {{#isPrimitiveType}}{{^isArray}} + RUN_TEST(test_{{classname}}_{{name}}_is_converted_to_json); + {{/isArray}}{{/isPrimitiveType}} + {{/vars}} + {{/model}}{{/models}} + + +} + +int main(void) { + UNITY_BEGIN(); + runTests(); + return UNITY_END(); +} + +void setup() { + UNITY_BEGIN(); + runTests(); + UNITY_END(); +} + +void loop() { + +} diff --git a/modules/openapi-generator/src/main/resources/cpp-tiny/service/AbstractService.cpp.mustache b/modules/openapi-generator/src/main/resources/cpp-tiny/service/AbstractService.cpp.mustache new file mode 100644 index 00000000000..0c056c85ae3 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/cpp-tiny/service/AbstractService.cpp.mustache @@ -0,0 +1,15 @@ +#include "AbstractService.h" +#include "Arduino.h" + +{{#isESP8266}} +void Tiny::AbstractService::begin(std::string url){ + http.begin(client, String(url.c_str())); +} +{{/isESP8266}} + + +{{#isESP32}} +void Tiny::AbstractService::begin(std::string url){ + http.begin(String(url.c_str()), test_root_ca); //HTTPS connection +} +{{/isESP32}} diff --git a/modules/openapi-generator/src/main/resources/cpp-tiny/service/AbstractService.h.mustache b/modules/openapi-generator/src/main/resources/cpp-tiny/service/AbstractService.h.mustache new file mode 100644 index 00000000000..7dc46b5b20f --- /dev/null +++ b/modules/openapi-generator/src/main/resources/cpp-tiny/service/AbstractService.h.mustache @@ -0,0 +1,39 @@ +#ifndef TINY_CPP_CLIENT_ABSTRACTSERVICE_H_ +#define TINY_CPP_CLIENT_ABSTRACTSERVICE_H_ +{{#isESP8266}} +#include +#include +{{/isESP8266}} + +{{#isESP32}} +#include "HTTPClient.h" +{{/isESP32}} +#include "Response.h" +namespace Tiny { + +/** +* Class +* Generated with openapi::tiny-cpp-client +*/ +class AbstractService { +public: +HTTPClient http; +{{#isESP8266}} +WiFiClient client; +{{/isESP8266}} +std::string basepath = "https://petstore3.swagger.io/api/v3"; // TODO: change to your url + +void begin(std::string url); + +{{#isESP32}} +// Go and comment out a certificate in root.cert, if you get an error here +// Certificate from file +const char* test_root_ca = +#include "../../root.cert" +; +{{/isESP32}} + +}; // end class +}// namespace Tinyclient + +#endif /* TINY_CPP_CLIENT_ABSTRACTSERVICE_H_ */ diff --git a/modules/openapi-generator/src/main/resources/cpp-tiny/service/Response.h.mustache b/modules/openapi-generator/src/main/resources/cpp-tiny/service/Response.h.mustache new file mode 100644 index 00000000000..9b7b616b8f1 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/cpp-tiny/service/Response.h.mustache @@ -0,0 +1,25 @@ +#ifndef TINY_CPP_CLIENT_RESPONSE_H_ +#define TINY_CPP_CLIENT_RESPONSE_H_ +#include + +namespace Tiny { + +/** +* Class +* Generated with openapi::tiny-cpp-client +*/ +template + class Response { + public: + + Response(T _obj, int _code){ + obj = _obj; + code = _code; + } + + int code; + T obj; + }; + } // namespace Tinyclient + +#endif /* TINY_CPP_CLIENT_RESPONSE_H_ */ diff --git a/modules/openapi-generator/src/main/resources/cpp-tiny/service/api-body.mustache b/modules/openapi-generator/src/main/resources/cpp-tiny/service/api-body.mustache new file mode 100644 index 00000000000..dc129868837 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/cpp-tiny/service/api-body.mustache @@ -0,0 +1,219 @@ +#include "{{classname}}.h" + +using namespace Tiny; + +{{#operations}} + + {{! Method }} + {{#operation}} + + Response< + {{#returnType}} + {{#returnContainer}} + {{#isArray}} + {{returnType}}<{{returnBaseType}}> + {{/isArray}} + {{#isMap}} + String + {{/isMap}} + {{/returnContainer}} + {{^returnContainer}} + {{returnType}} + {{/returnContainer}} + {{/returnType}} + {{^returnType}} + String + {{/returnType}} + > + {{classname}}:: + {{! Method name }} + {{nickname}}( + {{! Params }} + {{#allParams}} + {{! Arrays }} + {{#isContainer}}{{{dataType}}}<{{baseType}}> {{paramName}}{{/isContainer}}{{#isMap}}// TODO: Implement Maps{{/isMap}} + {{! Normal types/objects }} + {{^isContainer}}{{{dataType}}} {{paramName}}{{/isContainer}} + {{^-last}}, {{/-last}} + {{/allParams}} + ) + {{! Method start}} + { + std::string url = basepath + "{{{path}}}"; //{{#pathParams}}{{{paramName}}} {{/pathParams}} + // Query | {{#queryParams}}{{paramName}} {{/queryParams}} + // Headers | {{#headerParams}}{{paramName}} {{/headerParams}} + // Form | {{#formParams}}{{paramName}} {{/formParams}} + // Body | {{#bodyParam}}{{paramName}}{{/bodyParam}} + + {{#pathParams}} + std::string s_{{paramName}}("{"); + s_{{paramName}}.append("{{{baseName}}}"); + s_{{paramName}}.append("}"); + + int pos = url.find(s_{{paramName}}); + + url.erase(pos, s_{{paramName}}.length()); + url.insert(pos, stringify({{paramName}})); + {{/pathParams}} + + begin(url); + + std::string payload = ""; + // Send Request + // METHOD | {{httpMethod}} + {{#bodyParam}} + http.addHeader("Content-Type", "application/json"); + + {{#isContainer}} + {{#isArray}} + {{#items}} + {{#isPrimitiveType}} + bourne::json tmp_arr = bourne::json::array(); + for(auto& var : {{paramName}}) + { + tmp_arr.append(var); + } + payload = tmp_arr.dump(); + {{/isPrimitiveType}} + + {{^isPrimitiveType}} + bourne::json tmp_arr = bourne::json::array(); + for(auto& var : {{paramName}}) + { + auto tmp = var.toJson(); + tmp_arr.append(tmp); + + } + payload = tmp_arr.dump(); + {{/isPrimitiveType}} + {{/items}} + {{/isArray}} + {{/isContainer}} + + {{^isContainer}} + {{#isPrimitiveType}} + payload = stringify({{paramName}}); + {{/isPrimitiveType}} + + {{^isPrimitiveType}} + payload = {{paramName}}.toJson().dump(); + {{/isPrimitiveType}} + {{/isContainer}} + + {{/bodyParam}} + int httpCode = http.sendRequest("{{httpMethod}}", reinterpret_cast(&payload[0]), payload.length()); + + // Handle Request + String output = http.getString(); + std::string output_string = output.c_str(); + + http.end(); + + {{#returnType}} + + {{#returnContainer}} + {{#isArray}} + + std::list<{{returnBaseType}}> obj = std::list<{{returnBaseType}}>(); + bourne::json jsonPayload(output_string); + + {{#returnBaseType}} + + {{#isBool}} + for(auto& var : jsonPayload.array_range()) + { + {{returnBaseType}} tmp = var.to_bool(); + obj.push_back(tmp); + } + {{/isBool}} + + {{#isInteger}} + for(auto& var : jsonPayload.array_range()) + { + {{returnBaseType}} tmp = var.to_int(); + obj.push_back(tmp); + } + {{/isInteger}} + + {{#isLong}} + for(auto& var : jsonPayload.array_range()) + { + {{returnBaseType}} tmp = (long)(var.to_int()); + obj.push_back(tmp); + } + {{/isLong}} + + {{#isFloat}} + for(auto& var : jsonPayload.array_range()) + { + {{returnBaseType}} tmp = (float)(var.to_float()); + obj.push_back(tmp); + } + {{/isFloat}} + + {{#isString}} + for(auto& var : jsonPayload.array_range()) + { + {{returnBaseType}} tmp = var.to_string(); + obj.push_back(tmp); + } + {{/isString}} + + + {{^isBool}}{{^isInteger}}{{^isLong}}{{^isString}}{{^isFloat}} + for(auto& var : jsonPayload.array_range()) + { + {{returnBaseType}} tmp(var.dump()); + obj.push_back(tmp); + } + {{/isFloat}}{{/isString}}{{/isLong}}{{/isInteger}}{{/isBool}} + + {{/returnBaseType}} + + {{/isArray}} + + {{#isMap}} + //TODO: Implement map logic here + {{/isMap}} + + {{/returnContainer}} + + {{^returnContainer}} + {{#returnTypeIsPrimitive}} + bourne::json jsonPayload(output_string); + {{returnType}} obj; + jsonToValue(&obj, jsonPayload, "{{returnType}}"); + {{/returnTypeIsPrimitive}} + + {{^returnTypeIsPrimitive}} + {{returnType}} obj(output_string); + {{/returnTypeIsPrimitive}} + {{/returnContainer}} + + {{/returnType}} + + {{#returnType}} + {{#returnContainer}} + {{#isArray}} + Response<{{returnType}}<{{returnBaseType}}>> response(obj, httpCode); + {{/isArray}} + {{#isMap}} + //TODO: No support for maps. + Response response(output, httpCode); + {{/isMap}} + {{/returnContainer}} + {{^returnContainer}} + Response<{{returnType}}> response(obj, httpCode); + {{/returnContainer}} + {{/returnType}} + {{^returnType}} + Response response(output, httpCode); + {{/returnType}} + return response; + } + {{/operation}} + + + +{{/operations}} + diff --git a/modules/openapi-generator/src/main/resources/cpp-tiny/service/api-header.mustache b/modules/openapi-generator/src/main/resources/cpp-tiny/service/api-header.mustache new file mode 100644 index 00000000000..416369dcf31 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/cpp-tiny/service/api-header.mustache @@ -0,0 +1,74 @@ +#ifndef TINY_CPP_CLIENT_{{classname}}_H_ +#define TINY_CPP_CLIENT_{{classname}}_H_ + +{{{defaultInclude}}} +#include "Response.h" +#include "Arduino.h" +#include "AbstractService.h" +#include "Helpers.h" +#include + +{{#imports}} +{{{import}}} +{{/imports}} + +namespace Tiny { + +{{#operations}} +/** + * Class {{basename}} + * Generated with openapi::tiny-cpp-client + */ + +class {{classname}} : public AbstractService { +public: + {{! Constructor }} + {{classname}}() = default; + + {{! Destructor }} + virtual ~{{classname}}() = default; + + {{! Service endpoint }} + {{#operation}} + /** + * {{{summary}}}. + * + * {{{notes}}}{{#allParams}} + * \param {{paramName}} {{{description}}}{{#required}} *Required*{{/required}}{{/allParams}} + */ + Response< + {{#returnType}} + {{#returnContainer}} + {{#isArray}} + {{returnType}}<{{returnBaseType}}> + {{/isArray}} + {{#isMap}} + String + {{/isMap}} + {{/returnContainer}} + {{^returnContainer}} + {{returnType}} + {{/returnContainer}} + {{/returnType}} + {{^returnType}} + String + {{/returnType}} + > + {{! Method name }} + {{nickname}}( + {{! Params }} + {{#allParams}} + {{! Arrays }} + {{#isContainer}}{{{dataType}}}<{{baseType}}> {{paramName}}{{/isContainer}} + {{! Normal types/objects }} + {{^isContainer}}{{{dataType}}} {{paramName}}{{/isContainer}} + {{^-last}}, {{/-last}} + {{/allParams}} + ); + {{/operation}} +}; {{! Service endpoint end }} +{{/operations}} + +} {{! namespace end }} + +#endif /* TINY_CPP_CLIENT_{{classname}}_H_ */ \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/cpp-tiny/unit-test-model.mustache b/modules/openapi-generator/src/main/resources/cpp-tiny/unit-test-model.mustache new file mode 100644 index 00000000000..14894973b81 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/cpp-tiny/unit-test-model.mustache @@ -0,0 +1,161 @@ +{{#models}}{{#model}} +#include "{{classname}}.h" + +using namespace Tiny; + +#include +#include +#include +#include "bourne/json.hpp" + + +{{#vars}} +{{#isPrimitiveType}}{{^isArray}} +void test_{{classname}}_{{name}}_is_assigned_from_json() +{ + {{#isInteger}} + bourne::json input = + { + "{{name}}", 1 + }; + + {{classname}} obj(input.dump()); + + TEST_ASSERT_EQUAL_INT(1, obj.{{getter}}()); + {{/isInteger}} + + + {{#isString}} + bourne::json input = + { + "{{name}}", "hello" + }; + + {{classname}} obj(input.dump()); + + TEST_ASSERT_EQUAL_STRING("hello", obj.{{getter}}().c_str()); + {{/isString}} + + + {{#isBoolean}} + bourne::json input = + { + "{{name}}", true + }; + + {{classname}} obj(input.dump()); + + TEST_ASSERT(true == obj.{{getter}}()); + {{/isBoolean}} + + + {{#isLong}} + bourne::json input = + { + "{{name}}", 1 + }; + + {{classname}} obj(input.dump()); + + TEST_ASSERT_EQUAL_INT(1, obj.{{getter}}()); + {{/isLong}} + + + {{#isFloat}} + bourne::json input = + { + "{{name}}", 1.0 + }; + + {{classname}} obj(input.dump()); + + TEST_ASSERT_EQUAL_FLOAT(1.0, obj.{{getter}}()); + {{/isFloat}} +} +{{/isArray}}{{/isPrimitiveType}} +{{/vars}} + +{{#vars}} +{{#isPrimitiveType}}{{^isArray}} +void test_{{classname}}_{{name}}_is_converted_to_json() +{ + {{#isInteger}} + bourne::json input = + { + "{{name}}", 1 + }; + + {{classname}} obj(input.dump()); + + bourne::json output = bourne::json::object(); + + output = obj.toJson(); + + TEST_ASSERT(input["{{name}}"] == output["{{name}}"]); + {{/isInteger}} + + {{#isString}} + bourne::json input = + { + "{{name}}", "hello" + }; + + {{classname}} obj(input.dump()); + + bourne::json output = bourne::json::object(); + + output = obj.toJson(); + + TEST_ASSERT(input["{{name}}"] == output["{{name}}"]); + {{/isString}} + + {{#isBoolean}} + bourne::json input = + { + "{{name}}", true + }; + + {{classname}} obj(input.dump()); + + bourne::json output = bourne::json::object(); + + output = obj.toJson(); + + TEST_ASSERT(input["{{name}}"] == output["{{name}}"]); + {{/isBoolean}} + + {{#isLong}} + bourne::json input = + { + "{{name}}", 1 + }; + + {{classname}} obj(input.dump()); + + bourne::json output = bourne::json::object(); + + output = obj.toJson(); + + TEST_ASSERT(input["{{name}}"] == output["{{name}}"]); + {{/isLong}} + + {{#isFloat}} + bourne::json input = + { + "{{name}}", 1.0 + }; + + {{classname}} obj(input.dump()); + + bourne::json output = bourne::json::object(); + + output = obj.toJson(); + + TEST_ASSERT(input["{{name}}"] == output["{{name}}"]); + {{/isFloat}} +} +{{/isArray}}{{/isPrimitiveType}} +{{/vars}} + +{{/model}} +{{/models}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/cpp-tiny/unittest.mustache b/modules/openapi-generator/src/main/resources/cpp-tiny/unittest.mustache new file mode 100644 index 00000000000..c6a1f23a6e3 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/cpp-tiny/unittest.mustache @@ -0,0 +1,132 @@ +#include "Pet.h" +#include +#include +#include +#include "bourne/json.hpp" + +void setUp(){ +} + + +void tearDown(){ +} + +void test_id_is_assigned(){ + bourne::json petJSON = + { + "id", 1 + }; + + Tiny::Pet pet(petJSON.dump()); + + + TEST_ASSERT_EQUAL_INT(1, pet.getId()); +} + +void test_name_is_assigned(){ + bourne::json petJSON = + { + "name", "Shiba" + }; + + Tiny::Pet pet(petJSON.dump()); + + TEST_ASSERT_EQUAL_STRING("Shiba", pet.getName().c_str()); + +} + +void test_status_is_assigned(){ + bourne::json petJSON = + { + "status", "Sold" + }; + + Tiny::Pet pet(petJSON.dump()); + + TEST_ASSERT_EQUAL_STRING("Sold", pet.getStatus().c_str()); +} + +void test_category_object_is_assigned(){ + + bourne::json catJSON = + { + "id", 3, + "name", "Small dog" + }; + + bourne::json petJSON = + { + "category", catJSON, + }; + + Tiny::Pet pet(petJSON.dump()); + + TEST_ASSERT_EQUAL_STRING("Small dog", pet.getCategory().getName().c_str()); + TEST_ASSERT_EQUAL_INT(3, pet.getCategory().getId()); + +} + + +void test_photo_string_list_is_assigned(){ + + std::list photoList = {"url1", "url2", "url3", "url4"}; + + bourne::json photoARR = bourne::json::array("url1", "url2", "url3", "url4"); + + bourne::json petJSON = + { + "photoUrls", photoARR, + }; + + Tiny::Pet pet(petJSON.dump()); + + TEST_ASSERT(photoList == pet.getPhotoUrls()); +} + +void test_tags_object_list_is_assigned(){ + bourne::json aTag = + { + "id", 2, + "name", "Hello" + }; + + bourne::json tagsARR = bourne::json::array(aTag); + bourne::json petJSON = + { + "tags", tagsARR, + }; + + Tiny::Pet pet(petJSON.dump()); + + TEST_ASSERT_EQUAL_INT(2, pet.getTags().front().getId()); + TEST_ASSERT_EQUAL_STRING("Hello", pet.getTags().front().getName().c_str()); +} + + + +void runTests(){ + RUN_TEST(test_id_is_assigned); + RUN_TEST(test_category_object_is_assigned); + RUN_TEST(test_name_is_assigned); + RUN_TEST(test_status_is_assigned); + RUN_TEST(test_photo_string_list_is_assigned); + RUN_TEST(test_tags_object_list_is_assigned); +} + +int main(void) { + UNITY_BEGIN(); + runTests(); + return UNITY_END(); +} + +void setup() { + UNITY_BEGIN(); + runTests(); + UNITY_END(); +} + +void loop() { + +} + + diff --git a/modules/openapi-generator/src/main/resources/cpp-ue4/api-header.mustache b/modules/openapi-generator/src/main/resources/cpp-ue4/api-header.mustache index 17b42e942ea..b6059901809 100644 --- a/modules/openapi-generator/src/main/resources/cpp-ue4/api-header.mustache +++ b/modules/openapi-generator/src/main/resources/cpp-ue4/api-header.mustache @@ -35,7 +35,7 @@ public: {{#operations}}{{#operation}}DECLARE_DELEGATE_OneParam(F{{operationIdCamelCase}}Delegate, const {{operationIdCamelCase}}Response&); {{/operation}}{{/operations}} {{#operations}}{{#operation}}{{#description}}/* {{{description}}} */ - {{/description}}bool {{operationIdCamelCase}}(const {{operationIdCamelCase}}Request& Request, const F{{operationIdCamelCase}}Delegate& Delegate = F{{operationIdCamelCase}}Delegate()) const; + {{/description}}FHttpRequestPtr {{operationIdCamelCase}}(const {{operationIdCamelCase}}Request& Request, const F{{operationIdCamelCase}}Delegate& Delegate = F{{operationIdCamelCase}}Delegate()) const; {{/operation}}{{/operations}} private: {{#operations}}{{#operation}}void On{{operationIdCamelCase}}Response(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, F{{operationIdCamelCase}}Delegate Delegate) const; diff --git a/modules/openapi-generator/src/main/resources/cpp-ue4/api-operations-header.mustache b/modules/openapi-generator/src/main/resources/cpp-ue4/api-operations-header.mustache index 2319c59b3fa..f4810ba5888 100644 --- a/modules/openapi-generator/src/main/resources/cpp-ue4/api-operations-header.mustache +++ b/modules/openapi-generator/src/main/resources/cpp-ue4/api-operations-header.mustache @@ -35,6 +35,9 @@ public: {{/enumVars}} }; {{/allowableValues}} + + static FString EnumToString(const {{{enumName}}}& EnumValue); + static bool EnumFromString(const FString& EnumAsString, {{{enumName}}}& EnumValue); {{#description}}/* {{{description}}} */ {{/description}}{{^required}}TOptional<{{/required}}{{{datatypeWithEnum}}}{{^required}}>{{/required}} {{paramName}}{{#required}}{{#defaultValue}} = {{{defaultValue}}}{{/defaultValue}}{{/required}}; {{/isEnum}} diff --git a/modules/openapi-generator/src/main/resources/cpp-ue4/api-operations-source.mustache b/modules/openapi-generator/src/main/resources/cpp-ue4/api-operations-source.mustache index 07b557157ea..4d262483e1f 100644 --- a/modules/openapi-generator/src/main/resources/cpp-ue4/api-operations-source.mustache +++ b/modules/openapi-generator/src/main/resources/cpp-ue4/api-operations-source.mustache @@ -32,6 +32,28 @@ inline FString ToString(const {{classname}}::{{operationIdCamelCase}}Request::{{ return TEXT(""); } +FString {{classname}}::{{operationIdCamelCase}}Request::EnumToString(const {{classname}}::{{operationIdCamelCase}}Request::{{{enumName}}}& EnumValue) +{ + return ToString(EnumValue); +} + +inline bool FromString(const FString& EnumAsString, {{classname}}::{{operationIdCamelCase}}Request::{{{enumName}}}& Value) +{ + static TMap StringToEnum = { {{#allowableValues}}{{#enumVars}} + { TEXT("{{{value}}}"), {{classname}}::{{operationIdCamelCase}}Request::{{{enumName}}}::{{name}} },{{/enumVars}}{{/allowableValues}} }; + + const auto Found = StringToEnum.Find(EnumAsString); + if(Found) + Value = *Found; + + return Found != nullptr; +} + +bool {{classname}}::{{operationIdCamelCase}}Request::EnumFromString(const FString& EnumAsString, {{classname}}::{{operationIdCamelCase}}Request::{{{enumName}}}& EnumValue) +{ + return FromString(EnumAsString, EnumValue); +} + inline FStringFormatArg ToStringFormatArg(const {{classname}}::{{operationIdCamelCase}}Request::{{{enumName}}}& Value) { return FStringFormatArg(ToString(Value)); @@ -48,15 +70,8 @@ inline bool TryGetJsonValue(const TSharedPtr& JsonValue, {{classname FString TmpValue; if (JsonValue->TryGetString(TmpValue)) { - static TMap StringToEnum = { {{#enumVars}} - { TEXT("{{{value}}}"), {{classname}}::{{operationIdCamelCase}}Request::{{{enumName}}}::{{name}} },{{/enumVars}} }; - - const auto Found = StringToEnum.Find(TmpValue); - if(Found) - { - Value = *Found; + if(FromString(TmpValue, Value)) return true; - } } {{/allowableValues}} return false; diff --git a/modules/openapi-generator/src/main/resources/cpp-ue4/api-source.mustache b/modules/openapi-generator/src/main/resources/cpp-ue4/api-source.mustache index 9bd9f3b87bd..2ab5b0db9cd 100644 --- a/modules/openapi-generator/src/main/resources/cpp-ue4/api-source.mustache +++ b/modules/openapi-generator/src/main/resources/cpp-ue4/api-source.mustache @@ -125,10 +125,10 @@ void {{classname}}::HandleResponse(FHttpResponsePtr HttpResponse, bool bSucceede {{#operations}} {{#operation}} -bool {{classname}}::{{operationIdCamelCase}}(const {{operationIdCamelCase}}Request& Request, const F{{operationIdCamelCase}}Delegate& Delegate /*= F{{operationIdCamelCase}}Delegate()*/) const +FHttpRequestPtr {{classname}}::{{operationIdCamelCase}}(const {{operationIdCamelCase}}Request& Request, const F{{operationIdCamelCase}}Delegate& Delegate /*= F{{operationIdCamelCase}}Delegate()*/) const { if (!IsValid()) - return false; + return nullptr; FHttpRequestRef HttpRequest = CreateHttpRequest(Request); HttpRequest->SetURL(*(Url + Request.ComputePath())); @@ -141,7 +141,8 @@ bool {{classname}}::{{operationIdCamelCase}}(const {{operationIdCamelCase}}Reque Request.SetupHttpRequest(HttpRequest); HttpRequest->OnProcessRequestComplete().BindRaw(this, &{{classname}}::On{{operationIdCamelCase}}Response, Delegate); - return HttpRequest->ProcessRequest(); + HttpRequest->ProcessRequest(); + return HttpRequest; } void {{classname}}::On{{operationIdCamelCase}}Response(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, F{{operationIdCamelCase}}Delegate Delegate) const diff --git a/modules/openapi-generator/src/main/resources/cpp-ue4/model-header.mustache b/modules/openapi-generator/src/main/resources/cpp-ue4/model-header.mustache index 900dcf7f318..8742ad7a85f 100644 --- a/modules/openapi-generator/src/main/resources/cpp-ue4/model-header.mustache +++ b/modules/openapi-generator/src/main/resources/cpp-ue4/model-header.mustache @@ -36,6 +36,9 @@ public: Values Value{{#defaultValue}} = {{{defaultValue}}}{{/defaultValue}}; {{/allowableValues}} + + static FString EnumToString(const Values& EnumValue); + static bool EnumFromString(const FString& EnumAsString, Values& EnumValue); {{/isEnum}} {{^isEnum}} FString Value{{#defaultValue}} = {{{defaultValue}}}{{/defaultValue}}; @@ -51,6 +54,9 @@ public: {{/enumVars}} }; {{/allowableValues}} + + static FString EnumToString(const {{{enumName}}}& EnumValue); + static bool EnumFromString(const FString& EnumAsString, {{{enumName}}}& EnumValue); {{#description}}/* {{{description}}} */ {{/description}}{{^required}}TOptional<{{/required}}{{{datatypeWithEnum}}}{{^required}}>{{/required}} {{name}}{{#required}}{{#defaultValue}} = {{{defaultValue}}}{{/defaultValue}}{{/required}}; {{/isEnum}} diff --git a/modules/openapi-generator/src/main/resources/cpp-ue4/model-source.mustache b/modules/openapi-generator/src/main/resources/cpp-ue4/model-source.mustache index d084f8a8033..3022a7a935d 100644 --- a/modules/openapi-generator/src/main/resources/cpp-ue4/model-source.mustache +++ b/modules/openapi-generator/src/main/resources/cpp-ue4/model-source.mustache @@ -28,6 +28,28 @@ inline FString ToString(const {{classname}}::Values& Value) return TEXT(""); } +FString {{classname}}::EnumToString(const {{classname}}::Values& EnumValue) +{ + return ToString(EnumValue); +} + +inline bool FromString(const FString& EnumAsString, {{classname}}::Values& Value) +{ + static TMap StringToEnum = { {{#allowableValues}}{{#enumVars}} + { TEXT("{{{value}}}"), {{classname}}::Values::{{name}} },{{/enumVars}}{{/allowableValues}} }; + + const auto Found = StringToEnum.Find(EnumAsString); + if(Found) + Value = *Found; + + return Found != nullptr; +} + +bool {{classname}}::EnumFromString(const FString& EnumAsString, {{classname}}::Values& EnumValue) +{ + return FromString(EnumAsString, EnumValue); +} + inline FStringFormatArg ToStringFormatArg(const {{classname}}::Values& Value) { return FStringFormatArg(ToString(Value)); @@ -44,15 +66,8 @@ inline bool TryGetJsonValue(const TSharedPtr& JsonValue, {{classname FString TmpValue; if (JsonValue->TryGetString(TmpValue)) { - static TMap StringToEnum = { {{#enumVars}} - { TEXT("{{{value}}}"), {{classname}}::Values::{{name}} },{{/enumVars}} }; - - const auto Found = StringToEnum.Find(TmpValue); - if(Found) - { - Value = *Found; + if(FromString(TmpValue, Value)) return true; - } } {{/allowableValues}} return false; @@ -78,6 +93,28 @@ inline FString ToString(const {{classname}}::{{{enumName}}}& Value) return TEXT(""); } +FString {{classname}}::EnumToString(const {{classname}}::{{{enumName}}}& EnumValue) +{ + return ToString(EnumValue); +} + +inline bool FromString(const FString& EnumAsString, {{classname}}::{{{enumName}}}& Value) +{ + static TMap StringToEnum = { {{#allowableValues}}{{#enumVars}} + { TEXT("{{{value}}}"), {{classname}}::{{{enumName}}}::{{name}} },{{/enumVars}}{{/allowableValues}} }; + + const auto Found = StringToEnum.Find(EnumAsString); + if(Found) + Value = *Found; + + return Found != nullptr; +} + +bool {{classname}}::EnumFromString(const FString& EnumAsString, {{classname}}::{{{enumName}}}& EnumValue) +{ + return FromString(EnumAsString, EnumValue); +} + inline FStringFormatArg ToStringFormatArg(const {{classname}}::{{{enumName}}}& Value) { return FStringFormatArg(ToString(Value)); @@ -94,15 +131,8 @@ inline bool TryGetJsonValue(const TSharedPtr& JsonValue, {{classname FString TmpValue; if (JsonValue->TryGetString(TmpValue)) { - static TMap StringToEnum = { {{#enumVars}} - { TEXT("{{{value}}}"), {{classname}}::{{{enumName}}}::{{name}} },{{/enumVars}} }; - - const auto Found = StringToEnum.Find(TmpValue); - if(Found) - { - Value = *Found; + if(FromString(TmpValue, Value)) return true; - } } {{/allowableValues}} return false; diff --git a/modules/openapi-generator/src/main/resources/crystal/api.mustache b/modules/openapi-generator/src/main/resources/crystal/api.mustache index 8b8daabb5f3..787189be854 100644 --- a/modules/openapi-generator/src/main/resources/crystal/api.mustache +++ b/modules/openapi-generator/src/main/resources/crystal/api.mustache @@ -128,9 +128,9 @@ module {{moduleName}} local_var_path = "{{{path}}}"{{#pathParams}}.sub("{" + "{{baseName}}" + "}", URI.encode({{paramName}}.to_s){{^strictSpecBehavior}}.gsub("%2F", "/"){{/strictSpecBehavior}}){{/pathParams}} # query parameters - query_params = Hash(Symbol, String).new + query_params = Hash(String, String).new {{#queryParams}} - query_params[:"{{{baseName}}}"] = {{#collectionFormat}}@api_client.build_collection_param({{{paramName}}}, :{{{collectionFormat}}}){{/collectionFormat}}{{^collectionFormat}}{{{paramName}}}{{/collectionFormat}} + query_params["{{{baseName}}}"] = {{#collectionFormat}}@api_client.build_collection_param({{{paramName}}}, :{{{collectionFormat}}}){{/collectionFormat}}{{^collectionFormat}}{{{paramName}}}{{/collectionFormat}} {{/queryParams}} # header parameters diff --git a/modules/openapi-generator/src/main/resources/crystal/api_client.mustache b/modules/openapi-generator/src/main/resources/crystal/api_client.mustache index 6831e51bae0..9852faa90f9 100644 --- a/modules/openapi-generator/src/main/resources/crystal/api_client.mustache +++ b/modules/openapi-generator/src/main/resources/crystal/api_client.mustache @@ -163,7 +163,7 @@ module {{moduleName}} # @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_names.each do |auth_name| auth_setting = @config.auth_settings[auth_name] next unless auth_setting case auth_setting[:in] @@ -256,7 +256,7 @@ module {{moduleName}} # # @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 : Symbol, path : String, operation : Symbol, return_type : String, post_body : String?, auth_names = [] of String, header_params = {} of String => String, query_params = {} of Symbol => String, form_params = {} of Symbol => String) + def call_api(http_method : Symbol, path : String, operation : Symbol, return_type : String, post_body : String?, auth_names = [] of String, header_params = {} of String => String, query_params = {} of String => String, form_params = {} of Symbol => String) #ssl_options = { # :ca_file => @config.ssl_ca_file, # :verify => @config.ssl_verify, @@ -274,6 +274,8 @@ module {{moduleName}} # conn.adapter(Faraday.default_adapter) #end + update_params_for_auth! header_params, query_params, auth_names + if !post_body.nil? && !post_body.empty? # use JSON string in the payload form_or_body = post_body diff --git a/modules/openapi-generator/src/main/resources/crystal/configuration.mustache b/modules/openapi-generator/src/main/resources/crystal/configuration.mustache index cc2e15e93fa..103cf1820b2 100644 --- a/modules/openapi-generator/src/main/resources/crystal/configuration.mustache +++ b/modules/openapi-generator/src/main/resources/crystal/configuration.mustache @@ -30,7 +30,7 @@ module {{moduleName}} # @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" + # config.api_key[:api_key] = "xxx" property api_key : Hash(Symbol, String) # Defines API key prefixes used with API Key authentications. @@ -38,7 +38,7 @@ module {{moduleName}} # @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" + # config.api_key_prefix[:api_key] = "Token" property api_key_prefix : Hash(Symbol, String) # Defines the username used with HTTP basic authentication. @@ -119,6 +119,7 @@ module {{moduleName}} # https://github.com/typhoeus/ethon/blob/master/lib/ethon/easy/queryable.rb#L96 #property params_encoding : String? + # Create a new `Configuration`. def initialize @scheme = "{{scheme}}" @host = "{{host}}{{#port}}:{{{.}}}{{/port}}" @@ -141,9 +142,19 @@ module {{moduleName}} @password = nil @access_token = nil @temp_folder_path = nil + end - # TODO revise below to support block - #yield(self) if block_given? + # Create a new `Configuration` with block. + # + # ``` + # config = Petstore::Configuration.new do |config| + # config.username = "xxx" + # config.password = "xxx" + # end + # ``` + def initialize + initialize + yield self end # The default Configuration object. @@ -151,8 +162,9 @@ module {{moduleName}} @@default ||= Configuration.new end + # Configure object with block. def configure - yield(self) if block_given? + yield self end def scheme=(scheme) @@ -183,10 +195,10 @@ module {{moduleName}} # 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) - if @api_key_prefix[param_name] - "#{@api_key_prefix[param_name]} #{@api_key[param_name]}" + if prefix = @api_key_prefix[param_name]? + "#{prefix} #{@api_key[param_name]}" else - @api_key[param_name] + @api_key[param_name]? || "" end end @@ -204,7 +216,7 @@ module {{moduleName}} type: "api_key", in: {{#isKeyInHeader}}"header"{{/isKeyInHeader}}{{#isKeyInQuery}}"query"{{/isKeyInQuery}}, key: "{{keyParamName}}", - value: api_key_with_prefix("{{keyParamName}}") + value: api_key_with_prefix(:{{keyParamName}}) }, {{/isApiKey}} {{#isBasic}} diff --git a/modules/openapi-generator/src/main/resources/crystal/shard_name.mustache b/modules/openapi-generator/src/main/resources/crystal/shard_name.mustache index 7e3e9b162d4..6d2de8333a3 100644 --- a/modules/openapi-generator/src/main/resources/crystal/shard_name.mustache +++ b/modules/openapi-generator/src/main/resources/crystal/shard_name.mustache @@ -9,18 +9,21 @@ module {{moduleName}} VERSION = {{ `shards version #{__DIR__}`.chomp.stringify }} + # Return the default `Configuration` object. + def self.configure + Configuration.default + end + # Customize default settings for the SDK using block. - # {{moduleName}}.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 + # + # ``` + # {{moduleName}}.configure do |config| + # config.username = "xxx" + # config.password = "xxx" + # end + # ``` + def self.configure + yield Configuration.default end end diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore/ApiClient.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore/ApiClient.mustache index 6d0e25d93f4..65cbf8d76bc 100644 --- a/modules/openapi-generator/src/main/resources/csharp-netcore/ApiClient.mustache +++ b/modules/openapi-generator/src/main/resources/csharp-netcore/ApiClient.mustache @@ -106,7 +106,7 @@ namespace {{packageName}}.Client var bytes = response.RawBytes; if (response.Headers != null) { - var filePath = String.IsNullOrEmpty(_configuration.TempFolderPath) + var filePath = string.IsNullOrEmpty(_configuration.TempFolderPath) ? Path.GetTempPath() : _configuration.TempFolderPath; var regex = new Regex(@"Content-Disposition=.*filename=['""]?([^'""\s]+)['""]?$"); @@ -130,7 +130,7 @@ namespace {{packageName}}.Client return DateTime.Parse(response.Content, null, System.Globalization.DateTimeStyles.RoundtripKind); } - if (type == typeof(String) || type.Name.StartsWith("System.Nullable")) // return primitive type + if (type == typeof(string) || type.Name.StartsWith("System.Nullable")) // return primitive type { return Convert.ChangeType(response.Content, type); } @@ -163,7 +163,7 @@ namespace {{packageName}}.Client /// {{>visibility}} partial class ApiClient : ISynchronousClient{{#supportsAsync}}, IAsynchronousClient{{/supportsAsync}} { - private readonly String _baseUrl; + private readonly string _baseUrl; /// /// Specifies the settings on a object. @@ -208,7 +208,7 @@ namespace {{packageName}}.Client /// /// The target service's base path in URL format. /// - public ApiClient(String basePath) + public ApiClient(string basePath) { if (string.IsNullOrEmpty(basePath)) throw new ArgumentException("basePath cannot be empty"); @@ -269,7 +269,7 @@ namespace {{packageName}}.Client /// private RestRequest NewRequest( HttpMethod method, - String path, + string path, RequestOptions options, IReadableConfiguration configuration) { @@ -594,7 +594,7 @@ namespace {{packageName}}.Client if (RetryConfiguration.AsyncRetryPolicy != null) { var policy = RetryConfiguration.AsyncRetryPolicy; - var policyResult = await policy.ExecuteAndCaptureAsync(() => client.ExecuteAsync(req, cancellationToken)).ConfigureAwait(false); + var policyResult = await policy.ExecuteAndCaptureAsync((ct) => client.ExecuteAsync(req, ct), cancellationToken).ConfigureAwait(false); response = (policyResult.Outcome == OutcomeType.Successful) ? client.Deserialize(policyResult.Result) : new RestResponse { Request = req, diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore/ApiResponse.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore/ApiResponse.mustache index 35bd9f72d31..161c2acd16c 100644 --- a/modules/openapi-generator/src/main/resources/csharp-netcore/ApiResponse.mustache +++ b/modules/openapi-generator/src/main/resources/csharp-netcore/ApiResponse.mustache @@ -36,7 +36,7 @@ namespace {{packageName}}.Client /// /// Gets or sets any error text defined by the calling client. /// - String ErrorText { get; set; } + string ErrorText { get; set; } /// /// Gets or sets any cookies passed along on the response. @@ -77,7 +77,7 @@ namespace {{packageName}}.Client /// /// Gets or sets any error text defined by the calling client. /// - public String ErrorText { get; set; } + public string ErrorText { get; set; } /// /// Gets or sets any cookies passed along on the response. diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore/ClientUtils.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore/ClientUtils.mustache index dd9a5f90fdc..3c04dcdbd0c 100644 --- a/modules/openapi-generator/src/main/resources/csharp-netcore/ClientUtils.mustache +++ b/modules/openapi-generator/src/main/resources/csharp-netcore/ClientUtils.mustache @@ -120,7 +120,7 @@ namespace {{packageName}}.Client /// URL encode a string /// Credit/Ref: https://github.com/restsharp/RestSharp/blob/master/RestSharp/Extensions/StringExtensions.cs#L50 /// - /// String to be URL encoded + /// string to be URL encoded /// Byte array public static string UrlEncode(string input) { @@ -154,7 +154,7 @@ namespace {{packageName}}.Client /// /// Encode string in base64 format. /// - /// String to be encoded. + /// string to be encoded. /// Encoded string. public static string Base64Encode(string text) { @@ -182,7 +182,7 @@ namespace {{packageName}}.Client /// /// The Content-Type array to select from. /// The Content-Type header to use. - public static String SelectHeaderContentType(String[] contentTypes) + public static string SelectHeaderContentType(string[] contentTypes) { if (contentTypes.Length == 0) return null; @@ -203,7 +203,7 @@ namespace {{packageName}}.Client /// /// The accepts array to select from. /// The Accept header to use. - public static String SelectHeaderAccept(String[] accepts) + public static string SelectHeaderAccept(string[] accepts) { if (accepts.Length == 0) return null; @@ -211,7 +211,7 @@ namespace {{packageName}}.Client if (accepts.Contains("application/json", StringComparer.OrdinalIgnoreCase)) return "application/json"; - return String.Join(",", accepts); + return string.Join(",", accepts); } /// @@ -229,9 +229,9 @@ namespace {{packageName}}.Client /// /// MIME /// Returns True if MIME type is json. - public static bool IsJsonMime(String mime) + public static bool IsJsonMime(string mime) { - if (String.IsNullOrWhiteSpace(mime)) return false; + if (string.IsNullOrWhiteSpace(mime)) return false; return JsonRegex.IsMatch(mime) || mime.Equals("application/json-patch+json"); } diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore/Configuration.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore/Configuration.mustache index 718db517d4e..ead56414441 100644 --- a/modules/openapi-generator/src/main/resources/csharp-netcore/Configuration.mustache +++ b/modules/openapi-generator/src/main/resources/csharp-netcore/Configuration.mustache @@ -68,7 +68,7 @@ namespace {{packageName}}.Client /// Defines the base path of the target API server. /// Example: http://localhost:3000/v1/ /// - private String _basePath; + private string _basePath; /// /// Gets or sets the API key based on the authentication name. @@ -496,9 +496,9 @@ namespace {{packageName}}.Client /// /// Returns a string with essential information for debugging. /// - public static String ToDebugReport() + public static string ToDebugReport() { - String report = "C# SDK ({{{packageName}}}) Debug Report:\n"; + string report = "C# SDK ({{{packageName}}}) Debug Report:\n"; report += " OS: " + System.Environment.OSVersion + "\n"; report += " .NET Framework Version: " + System.Environment.Version + "\n"; report += " Version of the API: {{{version}}}\n"; diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore/HttpSigningConfiguration.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore/HttpSigningConfiguration.mustache index 597f503e558..cc8c275e40b 100644 --- a/modules/openapi-generator/src/main/resources/csharp-netcore/HttpSigningConfiguration.mustache +++ b/modules/openapi-generator/src/main/resources/csharp-netcore/HttpSigningConfiguration.mustache @@ -120,7 +120,7 @@ namespace {{packageName}}.Client } } - var httpValues = HttpUtility.ParseQueryString(String.Empty); + var httpValues = HttpUtility.ParseQueryString(string.Empty); foreach (var parameter in requestOptions.QueryParameters) { #if (NETCOREAPP) @@ -153,7 +153,7 @@ namespace {{packageName}}.Client uriBuilder.Query = httpValues.ToString().Replace("+", "%20"); var dateTime = DateTime.Now; - String Digest = String.Empty; + string Digest = string.Empty; //get the body string requestBody = string.Empty; @@ -230,7 +230,7 @@ namespace {{packageName}}.Client } } - var headersKeysString = String.Join(" ", HttpSignatureHeader.Keys); + var headersKeysString = string.Join(" ", HttpSignatureHeader.Keys); var headerValuesList = new List(); foreach (var keyVal in HttpSignatureHeader) @@ -411,10 +411,10 @@ namespace {{packageName}}.Client return derBytes.ToArray(); } - private RSACryptoServiceProvider GetRSAProviderFromPemFile(String pemfile, SecureString keyPassPharse = null) + private RSACryptoServiceProvider GetRSAProviderFromPemFile(string pemfile, SecureString keyPassPharse = null) { - const String pempubheader = "-----BEGIN PUBLIC KEY-----"; - const String pempubfooter = "-----END PUBLIC KEY-----"; + const string pempubheader = "-----BEGIN PUBLIC KEY-----"; + const string pempubfooter = "-----END PUBLIC KEY-----"; bool isPrivateKeyFile = true; byte[] pemkey = null; @@ -441,11 +441,11 @@ namespace {{packageName}}.Client return null; } - private byte[] ConvertPrivateKeyToBytes(String instr, SecureString keyPassPharse = null) + private byte[] ConvertPrivateKeyToBytes(string instr, SecureString keyPassPharse = null) { - const String pemprivheader = "-----BEGIN RSA PRIVATE KEY-----"; - const String pemprivfooter = "-----END RSA PRIVATE KEY-----"; - String pemstr = instr.Trim(); + 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)) @@ -456,7 +456,7 @@ namespace {{packageName}}.Client StringBuilder sb = new StringBuilder(pemstr); sb.Replace(pemprivheader, ""); sb.Replace(pemprivfooter, ""); - String pvkstr = sb.ToString().Trim(); + string pvkstr = sb.ToString().Trim(); try { // if there are no PEM encryption info lines, this is an UNencrypted PEM private key @@ -472,12 +472,12 @@ namespace {{packageName}}.Client { return null; } - String saltline = str.ReadLine(); + string saltline = str.ReadLine(); if (!saltline.StartsWith("DEK-Info: DES-EDE3-CBC,")) { return null; } - String saltstr = saltline.Substring(saltline.IndexOf(",") + 1).Trim(); + 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); @@ -487,7 +487,7 @@ namespace {{packageName}}.Client } //------ remaining b64 data is encrypted RSA key ---- - String encryptedstr = str.ReadToEnd(); + string encryptedstr = str.ReadToEnd(); try { //should have b64 encrypted RSA key now diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore/IApiAccessor.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore/IApiAccessor.mustache index 5ef01aa6c0d..a269f56e904 100644 --- a/modules/openapi-generator/src/main/resources/csharp-netcore/IApiAccessor.mustache +++ b/modules/openapi-generator/src/main/resources/csharp-netcore/IApiAccessor.mustache @@ -19,7 +19,7 @@ namespace {{packageName}}.Client /// Gets the base path of the API client. /// /// The base path - String GetBasePath(); + string GetBasePath(); /// /// Provides a factory method hook for the creation of exceptions. diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore/IAsynchronousClient.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore/IAsynchronousClient.mustache index 8dca28d0f88..f0c88fae473 100644 --- a/modules/openapi-generator/src/main/resources/csharp-netcore/IAsynchronousClient.mustache +++ b/modules/openapi-generator/src/main/resources/csharp-netcore/IAsynchronousClient.mustache @@ -21,7 +21,7 @@ namespace {{packageName}}.Client /// 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)); + 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. @@ -32,7 +32,7 @@ namespace {{packageName}}.Client /// 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)); + 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. @@ -43,7 +43,7 @@ namespace {{packageName}}.Client /// 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)); + 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. @@ -54,7 +54,7 @@ namespace {{packageName}}.Client /// 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)); + 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. @@ -65,7 +65,7 @@ namespace {{packageName}}.Client /// 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)); + 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. @@ -76,7 +76,7 @@ namespace {{packageName}}.Client /// 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)); + 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. @@ -87,6 +87,6 @@ namespace {{packageName}}.Client /// 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)); + Task> PatchAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); } } diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore/ISynchronousClient.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore/ISynchronousClient.mustache index 1ac0b2a8691..c09bfbfed66 100644 --- a/modules/openapi-generator/src/main/resources/csharp-netcore/ISynchronousClient.mustache +++ b/modules/openapi-generator/src/main/resources/csharp-netcore/ISynchronousClient.mustache @@ -20,7 +20,7 @@ namespace {{packageName}}.Client /// Per-request configurable settings. /// The return type. /// The response data, decorated with - ApiResponse Get(String path, RequestOptions options, IReadableConfiguration configuration = null); + ApiResponse Get(string path, RequestOptions options, IReadableConfiguration configuration = null); /// /// Executes a blocking call to some using the POST http verb. @@ -30,7 +30,7 @@ namespace {{packageName}}.Client /// Per-request configurable settings. /// The return type. /// The response data, decorated with - ApiResponse Post(String path, RequestOptions options, IReadableConfiguration configuration = null); + ApiResponse Post(string path, RequestOptions options, IReadableConfiguration configuration = null); /// /// Executes a blocking call to some using the PUT http verb. @@ -40,7 +40,7 @@ namespace {{packageName}}.Client /// Per-request configurable settings. /// The return type. /// The response data, decorated with - ApiResponse Put(String path, RequestOptions options, IReadableConfiguration configuration = null); + ApiResponse Put(string path, RequestOptions options, IReadableConfiguration configuration = null); /// /// Executes a blocking call to some using the DELETE http verb. @@ -50,7 +50,7 @@ namespace {{packageName}}.Client /// Per-request configurable settings. /// The return type. /// The response data, decorated with - ApiResponse Delete(String path, RequestOptions options, IReadableConfiguration configuration = null); + ApiResponse Delete(string path, RequestOptions options, IReadableConfiguration configuration = null); /// /// Executes a blocking call to some using the HEAD http verb. @@ -60,7 +60,7 @@ namespace {{packageName}}.Client /// Per-request configurable settings. /// The return type. /// The response data, decorated with - ApiResponse Head(String path, RequestOptions options, IReadableConfiguration configuration = null); + ApiResponse Head(string path, RequestOptions options, IReadableConfiguration configuration = null); /// /// Executes a blocking call to some using the OPTIONS http verb. @@ -70,7 +70,7 @@ namespace {{packageName}}.Client /// Per-request configurable settings. /// The return type. /// The response data, decorated with - ApiResponse Options(String path, RequestOptions options, IReadableConfiguration configuration = null); + ApiResponse Options(string path, RequestOptions options, IReadableConfiguration configuration = null); /// /// Executes a blocking call to some using the PATCH http verb. @@ -80,6 +80,6 @@ namespace {{packageName}}.Client /// Per-request configurable settings. /// The return type. /// The response data, decorated with - ApiResponse Patch(String path, RequestOptions options, IReadableConfiguration configuration = null); + ApiResponse Patch(string path, RequestOptions options, IReadableConfiguration configuration = null); } } diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore/RequestOptions.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore/RequestOptions.mustache index 224eb497d28..dc924c733c1 100644 --- a/modules/openapi-generator/src/main/resources/csharp-netcore/RequestOptions.mustache +++ b/modules/openapi-generator/src/main/resources/csharp-netcore/RequestOptions.mustache @@ -16,29 +16,29 @@ namespace {{packageName}}.Client /// /// Parameters to be bound to path parts of the Request's URL /// - public Dictionary PathParameters { get; set; } + 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; } + public Multimap QueryParameters { get; set; } /// /// Header parameters to be applied to to the request. /// Keys may have 1 or more values associated. /// - public Multimap HeaderParameters { get; set; } + public Multimap HeaderParameters { get; set; } /// /// Form parameters to be sent along with the request. /// - public Dictionary FormParameters { get; set; } + public Dictionary FormParameters { get; set; } /// /// File parameters to be sent along with the request. /// - public Dictionary FileParameters { get; set; } + public Dictionary FileParameters { get; set; } /// /// Cookies to be sent along with the request. @@ -59,8 +59,8 @@ namespace {{packageName}}.Client QueryParameters = new Multimap(); HeaderParameters = new Multimap(); FormParameters = new Dictionary(); - FileParameters = new Dictionary(); + FileParameters = new Dictionary(); Cookies = new List(); } } -} \ No newline at end of file +} diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore/api.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore/api.mustache index 40d3bfd6596..8d84eecefb4 100644 --- a/modules/openapi-generator/src/main/resources/csharp-netcore/api.mustache +++ b/modules/openapi-generator/src/main/resources/csharp-netcore/api.mustache @@ -115,7 +115,7 @@ namespace {{packageName}}.{{apiPackage}} /// Initializes a new instance of the class. /// /// - public {{classname}}(String basePath) + public {{classname}}(string basePath) { this.Configuration = {{packageName}}.Client.Configuration.MergeConfigurations( {{packageName}}.Client.GlobalConfiguration.Instance, @@ -188,7 +188,7 @@ namespace {{packageName}}.{{apiPackage}} /// Gets the base path of the API client. /// /// The base path - public String GetBasePath() + public string GetBasePath() { return this.Configuration.BasePath; } @@ -248,14 +248,14 @@ namespace {{packageName}}.{{apiPackage}} {{/allParams}} {{packageName}}.Client.RequestOptions localVarRequestOptions = new {{packageName}}.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { {{#consumes}} "{{{mediaType}}}"{{^-last}},{{/-last}} {{/consumes}} }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { {{#produces}} "{{{mediaType}}}"{{^-last}},{{/-last}} {{/produces}} @@ -353,19 +353,19 @@ namespace {{packageName}}.{{apiPackage}} {{#isApiKey}} {{#isKeyInCookie}} // cookie parameter support - if (!String.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("{{keyParamName}}"))) + if (!string.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("{{keyParamName}}"))) { localVarRequestOptions.Cookies.Add(new Cookie("{{keyParamName}}", this.Configuration.GetApiKeyWithPrefix("{{keyParamName}}"))); } {{/isKeyInCookie}} {{#isKeyInHeader}} - if (!String.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("{{keyParamName}}"))) + if (!string.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("{{keyParamName}}"))) { localVarRequestOptions.HeaderParameters.Add("{{keyParamName}}", this.Configuration.GetApiKeyWithPrefix("{{keyParamName}}")); } {{/isKeyInHeader}} {{#isKeyInQuery}} - if (!String.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("{{keyParamName}}"))) + if (!string.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("{{keyParamName}}"))) { localVarRequestOptions.QueryParameters.Add({{packageName}}.Client.ClientUtils.ParameterToMultiMap("", "{{keyParamName}}", this.Configuration.GetApiKeyWithPrefix("{{keyParamName}}"))); } @@ -373,21 +373,21 @@ namespace {{packageName}}.{{apiPackage}} {{/isApiKey}} {{#isBasicBasic}} // http basic authentication required - if (!String.IsNullOrEmpty(this.Configuration.Username) || !String.IsNullOrEmpty(this.Configuration.Password)) + if (!string.IsNullOrEmpty(this.Configuration.Username) || !string.IsNullOrEmpty(this.Configuration.Password)) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Basic " + {{packageName}}.Client.ClientUtils.Base64Encode(this.Configuration.Username + ":" + this.Configuration.Password)); } {{/isBasicBasic}} {{#isBasicBearer}} // bearer authentication required - if (!String.IsNullOrEmpty(this.Configuration.AccessToken)) + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); } {{/isBasicBearer}} {{#isOAuth}} // oauth required - if (!String.IsNullOrEmpty(this.Configuration.AccessToken)) + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); } @@ -463,14 +463,14 @@ namespace {{packageName}}.{{apiPackage}} {{packageName}}.Client.RequestOptions localVarRequestOptions = new {{packageName}}.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { {{#consumes}} "{{{mediaType}}}"{{^-last}}, {{/-last}} {{/consumes}} }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { {{#produces}} "{{{mediaType}}}"{{^-last}},{{/-last}} {{/produces}} @@ -546,19 +546,19 @@ namespace {{packageName}}.{{apiPackage}} {{#isApiKey}} {{#isKeyInCookie}} // cookie parameter support - if (!String.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("{{keyParamName}}"))) + if (!string.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("{{keyParamName}}"))) { localVarRequestOptions.Cookies.Add(new Cookie("{{keyParamName}}", this.Configuration.GetApiKeyWithPrefix("{{keyParamName}}"))); } {{/isKeyInCookie}} {{#isKeyInHeader}} - if (!String.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("{{keyParamName}}"))) + if (!string.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("{{keyParamName}}"))) { localVarRequestOptions.HeaderParameters.Add("{{keyParamName}}", this.Configuration.GetApiKeyWithPrefix("{{keyParamName}}")); } {{/isKeyInHeader}} {{#isKeyInQuery}} - if (!String.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("{{keyParamName}}"))) + if (!string.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("{{keyParamName}}"))) { localVarRequestOptions.QueryParameters.Add({{packageName}}.Client.ClientUtils.ParameterToMultiMap("", "{{keyParamName}}", this.Configuration.GetApiKeyWithPrefix("{{keyParamName}}"))); } @@ -567,14 +567,14 @@ namespace {{packageName}}.{{apiPackage}} {{#isBasic}} {{#isBasicBasic}} // http basic authentication required - if (!String.IsNullOrEmpty(this.Configuration.Username) || !String.IsNullOrEmpty(this.Configuration.Password)) + if (!string.IsNullOrEmpty(this.Configuration.Username) || !string.IsNullOrEmpty(this.Configuration.Password)) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Basic " + {{packageName}}.Client.ClientUtils.Base64Encode(this.Configuration.Username + ":" + this.Configuration.Password)); } {{/isBasicBasic}} {{#isBasicBearer}} // bearer authentication required - if (!String.IsNullOrEmpty(this.Configuration.AccessToken)) + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); } @@ -582,7 +582,7 @@ namespace {{packageName}}.{{apiPackage}} {{/isBasic}} {{#isOAuth}} // oauth required - if (!String.IsNullOrEmpty(this.Configuration.AccessToken)) + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); } diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/httpclient/ApiClient.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/httpclient/ApiClient.mustache index 5477cb0cc73..e9c39ea9f6d 100644 --- a/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/httpclient/ApiClient.mustache +++ b/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/httpclient/ApiClient.mustache @@ -80,9 +80,9 @@ namespace {{packageName}}.Client } } - public T Deserialize(HttpResponseMessage response) + public async Task Deserialize(HttpResponseMessage response) { - var result = (T)Deserialize(response, typeof(T)); + var result = (T) await Deserialize(response, typeof(T)); return result; } @@ -92,22 +92,22 @@ namespace {{packageName}}.Client /// The HTTP response. /// Object type. /// Object representation of the JSON string. - internal object Deserialize(HttpResponseMessage response, Type type) + internal async Task Deserialize(HttpResponseMessage response, Type type) { IList headers = response.Headers.Select(x => x.Key + "=" + x.Value).ToList(); if (type == typeof(byte[])) // return byte array { - return response.Content.ReadAsByteArrayAsync().GetAwaiter().GetResult(); + return await response.Content.ReadAsByteArrayAsync(); } // TODO: ? if (type.IsAssignableFrom(typeof(Stream))) if (type == typeof(Stream)) { - var bytes = response.Content.ReadAsByteArrayAsync().GetAwaiter().GetResult(); + var bytes = await response.Content.ReadAsByteArrayAsync(); if (headers != null) { - var filePath = String.IsNullOrEmpty(_configuration.TempFolderPath) + var filePath = string.IsNullOrEmpty(_configuration.TempFolderPath) ? Path.GetTempPath() : _configuration.TempFolderPath; var regex = new Regex(@"Content-Disposition=.*filename=['""]?([^'""\s]+)['""]?$"); @@ -128,18 +128,18 @@ namespace {{packageName}}.Client if (type.Name.StartsWith("System.Nullable`1[[System.DateTime")) // return a datetime object { - return DateTime.Parse(response.Content.ReadAsStringAsync().GetAwaiter().GetResult(), null, System.Globalization.DateTimeStyles.RoundtripKind); + return DateTime.Parse(await response.Content.ReadAsStringAsync(), null, System.Globalization.DateTimeStyles.RoundtripKind); } - if (type == typeof(String) || type.Name.StartsWith("System.Nullable")) // return primitive type + if (type == typeof(string) || type.Name.StartsWith("System.Nullable")) // return primitive type { - return Convert.ChangeType(response.Content.ReadAsStringAsync().GetAwaiter().GetResult(), type); + return Convert.ChangeType(await response.Content.ReadAsStringAsync(), type); } // at this point, it must be a model (json) try { - return JsonConvert.DeserializeObject(response.Content.ReadAsStringAsync().GetAwaiter().GetResult(), type, _serializerSettings); + return JsonConvert.DeserializeObject(await response.Content.ReadAsStringAsync(), type, _serializerSettings); } catch (Exception e) { @@ -166,7 +166,7 @@ namespace {{packageName}}.Client /// {{>visibility}} partial class ApiClient : IDisposable, ISynchronousClient{{#supportsAsync}}, IAsynchronousClient{{/supportsAsync}} { - private readonly String _baseUrl; + private readonly string _baseUrl; private readonly HttpClientHandler _httpClientHandler; private readonly HttpClient _httpClient; @@ -206,7 +206,7 @@ namespace {{packageName}}.Client /// /// The target service's base path in URL format. /// - public ApiClient(String basePath) + public ApiClient(string basePath) { if (string.IsNullOrEmpty(basePath)) throw new ArgumentException("basePath cannot be empty"); @@ -243,7 +243,7 @@ namespace {{packageName}}.Client /// Some configuration settings will not be applied without passing an HttpClientHandler. /// The features affected are: Setting and Retrieving Cookies, Client Certificates, Proxy settings. /// - public ApiClient(HttpClient client, String basePath, HttpClientHandler handler = null) + public ApiClient(HttpClient client, string basePath, HttpClientHandler handler = null) { if (client == null) throw new ArgumentNullException("client cannot be null"); if (string.IsNullOrEmpty(basePath)) throw new ArgumentException("basePath cannot be empty"); @@ -278,12 +278,10 @@ namespace {{packageName}}.Client { foreach (var fileParam in options.FileParameters) { - var fileStream = fileParam.Value as FileStream; - var fileStreamName = fileStream != null ? System.IO.Path.GetFileName(fileStream.Name) : null; - var content = new StreamContent(fileParam.Value); + var content = new StreamContent(fileParam.Value.Content); content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); multipartContent.Add(content, fileParam.Key, - fileStreamName ?? "no_file_name_provided"); + fileParam.Value.Name); } } return multipartContent; @@ -303,7 +301,7 @@ namespace {{packageName}}.Client /// private HttpRequestMessage NewRequest( HttpMethod method, - String path, + string path, RequestOptions options, IReadableConfiguration configuration) { @@ -315,11 +313,7 @@ namespace {{packageName}}.Client builder.AddPathParameters(options.PathParameters); - // In case of POST or PUT pass query parameters in request body - if (method != HttpMethod.Post && method != HttpMethod.Put) - { - builder.AddQueryParameters(options.QueryParameters); - } + builder.AddQueryParameters(options.QueryParameters); HttpRequestMessage request = new HttpRequestMessage(method, builder.GetFullUri()); @@ -370,11 +364,11 @@ namespace {{packageName}}.Client { if (options.Data != null) { - if (options.Data is Stream s) + if (options.Data is FileParameter fp) { contentType = contentType ?? "application/octet-stream"; - var streamContent = new StreamContent(s); + var streamContent = new StreamContent(fp.Content); streamContent.Headers.ContentType = new MediaTypeHeaderValue(contentType); request.Content = streamContent; } @@ -516,7 +510,7 @@ namespace {{packageName}}.Client return await ToApiResponse(response, default(T), req.RequestUri); } - object responseData = deserializer.Deserialize(response); + object responseData = await deserializer.Deserialize(response); // if the response type is oneOf/anyOf, call FromJSON to deserialize the data if (typeof({{{packageName}}}.{{modelPackage}}.AbstractOpenAPISchema).IsAssignableFrom(typeof(T))) diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/httpclient/FileParameter.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/httpclient/FileParameter.mustache new file mode 100644 index 00000000000..3fa243ed54f --- /dev/null +++ b/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/httpclient/FileParameter.mustache @@ -0,0 +1,54 @@ +{{>partial_header}} + +using System.IO; + +namespace {{packageName}}.Client +{ + + /// + /// Represents a File passed to the API as a Parameter, allows using different backends for files + /// + public class FileParameter + { + /// + /// The filename + /// + public string Name { get; set; } = "no_name_provided"; + + /// + /// The content of the file + /// + public Stream Content { get; set; } + + /// + /// Construct a FileParameter just from the contents, will extract the filename from a filestream + /// + /// The file content + public FileParameter(Stream content) + { + if (content is FileStream fs) + { + Name = fs.Name; + } + Content = content; + } + + /// + /// Construct a FileParameter from name and content + /// + /// The filename + /// The file content + public FileParameter(string filename, Stream content) + { + Name = filename; + Content = content; + } + + /// + /// Implicit conversion of stream to file parameter. Useful for backwards compatibility. + /// + /// Stream to convert + /// FileParameter + public static implicit operator FileParameter(Stream s) => new FileParameter(s); + } +} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/httpclient/RequestOptions.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/httpclient/RequestOptions.mustache new file mode 100644 index 00000000000..bc5a8e348b8 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/httpclient/RequestOptions.mustache @@ -0,0 +1,66 @@ +{{>partial_header}} + +using System; +using System.Collections.Generic; +using System.IO; +using System.Net; + +namespace {{packageName}}.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 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 Dictionary FileParameters { get; set; } + + /// + /// Cookies to be sent along with the request. + /// + public List Cookies { 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 Dictionary(); + Cookies = new List(); + } + } +} diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/httpclient/api.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/httpclient/api.mustache index 0a3389d0a45..20ddfe96b98 100644 --- a/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/httpclient/api.mustache +++ b/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/httpclient/api.mustache @@ -122,7 +122,7 @@ namespace {{packageName}}.{{apiPackage}} /// The target service's base path in URL format. /// /// - public {{classname}}(String basePath) + public {{classname}}(string basePath) { this.Configuration = {{packageName}}.Client.Configuration.MergeConfigurations( {{packageName}}.Client.GlobalConfiguration.Instance, @@ -188,7 +188,7 @@ namespace {{packageName}}.{{apiPackage}} /// Some configuration settings will not be applied without passing an HttpClientHandler. /// The features affected are: Setting and Retrieving Cookies, Client Certificates, Proxy settings. /// - public {{classname}}(HttpClient client, String basePath, HttpClientHandler handler = null) + public {{classname}}(HttpClient client, string basePath, HttpClientHandler handler = null) { if (client == null) throw new ArgumentNullException("client"); @@ -286,7 +286,7 @@ namespace {{packageName}}.{{apiPackage}} /// Gets the base path of the API client. /// /// The base path - public String GetBasePath() + public string GetBasePath() { return this.Configuration.BasePath; } @@ -346,14 +346,14 @@ namespace {{packageName}}.{{apiPackage}} {{/allParams}} {{packageName}}.Client.RequestOptions localVarRequestOptions = new {{packageName}}.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { {{#consumes}} "{{{mediaType}}}"{{^-last}},{{/-last}} {{/consumes}} }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { {{#produces}} "{{{mediaType}}}"{{^-last}},{{/-last}} {{/produces}} @@ -451,19 +451,19 @@ namespace {{packageName}}.{{apiPackage}} {{#isApiKey}} {{#isKeyInCookie}} // cookie parameter support - if (!String.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("{{keyParamName}}"))) + if (!string.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("{{keyParamName}}"))) { localVarRequestOptions.Cookies.Add(new Cookie("{{keyParamName}}", this.Configuration.GetApiKeyWithPrefix("{{keyParamName}}"))); } {{/isKeyInCookie}} {{#isKeyInHeader}} - if (!String.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("{{keyParamName}}"))) + if (!string.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("{{keyParamName}}"))) { localVarRequestOptions.HeaderParameters.Add("{{keyParamName}}", this.Configuration.GetApiKeyWithPrefix("{{keyParamName}}")); } {{/isKeyInHeader}} {{#isKeyInQuery}} - if (!String.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("{{keyParamName}}"))) + if (!string.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("{{keyParamName}}"))) { localVarRequestOptions.QueryParameters.Add({{packageName}}.Client.ClientUtils.ParameterToMultiMap("", "{{keyParamName}}", this.Configuration.GetApiKeyWithPrefix("{{keyParamName}}"))); } @@ -471,21 +471,21 @@ namespace {{packageName}}.{{apiPackage}} {{/isApiKey}} {{#isBasicBasic}} // http basic authentication required - if (!String.IsNullOrEmpty(this.Configuration.Username) || !String.IsNullOrEmpty(this.Configuration.Password)) + if (!string.IsNullOrEmpty(this.Configuration.Username) || !string.IsNullOrEmpty(this.Configuration.Password)) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Basic " + {{packageName}}.Client.ClientUtils.Base64Encode(this.Configuration.Username + ":" + this.Configuration.Password)); } {{/isBasicBasic}} {{#isBasicBearer}} // bearer authentication required - if (!String.IsNullOrEmpty(this.Configuration.AccessToken)) + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); } {{/isBasicBearer}} {{#isOAuth}} // oauth required - if (!String.IsNullOrEmpty(this.Configuration.AccessToken)) + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); } @@ -561,14 +561,14 @@ namespace {{packageName}}.{{apiPackage}} {{packageName}}.Client.RequestOptions localVarRequestOptions = new {{packageName}}.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { {{#consumes}} "{{{mediaType}}}"{{^-last}}, {{/-last}} {{/consumes}} }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { {{#produces}} "{{{mediaType}}}"{{^-last}},{{/-last}} {{/produces}} @@ -644,19 +644,19 @@ namespace {{packageName}}.{{apiPackage}} {{#isApiKey}} {{#isKeyInCookie}} // cookie parameter support - if (!String.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("{{keyParamName}}"))) + if (!string.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("{{keyParamName}}"))) { localVarRequestOptions.Cookies.Add(new Cookie("{{keyParamName}}", this.Configuration.GetApiKeyWithPrefix("{{keyParamName}}"))); } {{/isKeyInCookie}} {{#isKeyInHeader}} - if (!String.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("{{keyParamName}}"))) + if (!string.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("{{keyParamName}}"))) { localVarRequestOptions.HeaderParameters.Add("{{keyParamName}}", this.Configuration.GetApiKeyWithPrefix("{{keyParamName}}")); } {{/isKeyInHeader}} {{#isKeyInQuery}} - if (!String.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("{{keyParamName}}"))) + if (!string.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("{{keyParamName}}"))) { localVarRequestOptions.QueryParameters.Add({{packageName}}.Client.ClientUtils.ParameterToMultiMap("", "{{keyParamName}}", this.Configuration.GetApiKeyWithPrefix("{{keyParamName}}"))); } @@ -665,14 +665,14 @@ namespace {{packageName}}.{{apiPackage}} {{#isBasic}} {{#isBasicBasic}} // http basic authentication required - if (!String.IsNullOrEmpty(this.Configuration.Username) || !String.IsNullOrEmpty(this.Configuration.Password)) + if (!string.IsNullOrEmpty(this.Configuration.Username) || !string.IsNullOrEmpty(this.Configuration.Password)) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Basic " + {{packageName}}.Client.ClientUtils.Base64Encode(this.Configuration.Username + ":" + this.Configuration.Password)); } {{/isBasicBasic}} {{#isBasicBearer}} // bearer authentication required - if (!String.IsNullOrEmpty(this.Configuration.AccessToken)) + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); } @@ -680,7 +680,7 @@ namespace {{packageName}}.{{apiPackage}} {{/isBasic}} {{#isOAuth}} // oauth required - if (!String.IsNullOrEmpty(this.Configuration.AccessToken)) + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); } diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/httpclient/model.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/httpclient/model.mustache new file mode 100644 index 00000000000..0de1e05e514 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/csharp-netcore/libraries/httpclient/model.mustache @@ -0,0 +1,48 @@ +{{>partial_header}} + +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; +{{#models}} +{{#model}} +{{#discriminator}} +using JsonSubTypes; +{{/discriminator}} +{{/model}} +{{/models}} +{{#validatable}} +using System.ComponentModel.DataAnnotations; +{{/validatable}} +using FileParameter = {{packageName}}.Client.FileParameter; +using OpenAPIDateConverter = {{packageName}}.Client.OpenAPIDateConverter; +{{#useCompareNetObjects}} +using OpenAPIClientUtils = {{packageName}}.Client.ClientUtils; +{{/useCompareNetObjects}} +{{#models}} +{{#model}} +{{#oneOf}} +{{#-first}} +using System.Reflection; +{{/-first}} +{{/oneOf}} +{{#aneOf}} +{{#-first}} +using System.Reflection; +{{/-first}} +{{/aneOf}} + +namespace {{packageName}}.{{modelPackage}} +{ +{{#isEnum}}{{>modelEnum}}{{/isEnum}}{{^isEnum}}{{#oneOf}}{{#-first}}{{>modelOneOf}}{{/-first}}{{/oneOf}}{{#anyOf}}{{#-first}}{{>modelAnyOf}}{{/-first}}{{/anyOf}}{{^oneOf}}{{^anyOf}}{{>modelGeneric}}{{/anyOf}}{{/oneOf}}{{/isEnum}} +{{/model}} +{{/models}} +} diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore/modelAnyOf.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore/modelAnyOf.mustache index 0bb2f488666..931f7646da8 100644 --- a/modules/openapi-generator/src/main/resources/csharp-netcore/modelAnyOf.mustache +++ b/modules/openapi-generator/src/main/resources/csharp-netcore/modelAnyOf.mustache @@ -115,7 +115,7 @@ catch (Exception exception) { // deserialization failed, try the next one - System.Diagnostics.Debug.WriteLine(String.Format("Failed to deserialize `{0}` into {{{.}}}: {1}", jsonString, exception.ToString())); + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into {{{.}}}: {1}", jsonString, exception.ToString())); } {{/anyOf}} @@ -195,7 +195,7 @@ /// JSON Serializer public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { - writer.WriteRawValue((String)(typeof({{classname}}).GetMethod("ToJson").Invoke(value, null))); + writer.WriteRawValue((string)(typeof({{classname}}).GetMethod("ToJson").Invoke(value, null))); } /// diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore/modelGeneric.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore/modelGeneric.mustache index 3ecfa611d68..6eb1a2359d0 100644 --- a/modules/openapi-generator/src/main/resources/csharp-netcore/modelGeneric.mustache +++ b/modules/openapi-generator/src/main/resources/csharp-netcore/modelGeneric.mustache @@ -31,6 +31,7 @@ {{#description}} /// {{description}} {{/description}} + {{^conditionalSerialization}} [DataMember(Name = "{{baseName}}"{{#required}}, IsRequired = true{{/required}}, EmitDefaultValue = {{#vendorExtensions.x-emit-default-value}}true{{/vendorExtensions.x-emit-default-value}}{{^vendorExtensions.x-emit-default-value}}{{#isBoolean}}true{{/isBoolean}}{{^isBoolean}}{{#isNullable}}true{{/isNullable}}{{^isNullable}}false{{/isNullable}}{{/isBoolean}}{{/vendorExtensions.x-emit-default-value}})] public {{#complexType}}{{{complexType}}}{{/complexType}}{{^complexType}}{{{datatypeWithEnum}}}{{/complexType}}{{^isContainer}}{{^required}}?{{/required}}{{/isContainer}} {{name}} { get; set; } {{#isReadOnly}} @@ -44,6 +45,47 @@ return false; } {{/isReadOnly}} + {{/conditionalSerialization}} + {{#conditionalSerialization}} + {{#isReadOnly}} + [DataMember(Name = "{{baseName}}"{{#required}}, IsRequired = true{{/required}}, EmitDefaultValue = {{#vendorExtensions.x-emit-default-value}}true{{/vendorExtensions.x-emit-default-value}}{{^vendorExtensions.x-emit-default-value}}{{#isBoolean}}true{{/isBoolean}}{{^isBoolean}}{{#isNullable}}true{{/isNullable}}{{^isNullable}}false{{/isNullable}}{{/isBoolean}}{{/vendorExtensions.x-emit-default-value}})] + public {{#complexType}}{{{complexType}}}{{/complexType}}{{^complexType}}{{{datatypeWithEnum}}}{{/complexType}}{{^isContainer}}{{^required}}?{{/required}}{{/isContainer}} {{name}} { get; set; } + + + /// + /// Returns false as {{name}} should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerialize{{name}}() + { + return false; + } + {{/isReadOnly}} + + {{^isReadOnly}} + [DataMember(Name = "{{baseName}}"{{#required}}, IsRequired = true{{/required}}, EmitDefaultValue = {{#vendorExtensions.x-emit-default-value}}true{{/vendorExtensions.x-emit-default-value}}{{^vendorExtensions.x-emit-default-value}}{{#isBoolean}}true{{/isBoolean}}{{^isBoolean}}{{#isNullable}}true{{/isNullable}}{{^isNullable}}false{{/isNullable}}{{/isBoolean}}{{/vendorExtensions.x-emit-default-value}})] + public {{#complexType}}{{{complexType}}}{{/complexType}}{{^complexType}}{{{datatypeWithEnum}}}{{/complexType}}{{^isContainer}}{{^required}}?{{/required}}{{/isContainer}} {{name}} + { + get{ return _{{name}};} + set + { + _{{name}} = value; + _flag{{name}} = true; + } + } + private {{#complexType}}{{{complexType}}}{{/complexType}}{{^complexType}}{{{datatypeWithEnum}}}{{/complexType}}{{^isContainer}}{{^required}}?{{/required}}{{/isContainer}} _{{name}}; + private bool _flag{{name}}; + + /// + /// Returns false as {{name}} should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerialize{{name}}() + { + return _flag{{name}}; + } + {{/isReadOnly}} + {{/conditionalSerialization}} {{/isEnum}} {{/vars}} {{#hasRequired}} @@ -78,6 +120,7 @@ {{^isInherited}} {{^isReadOnly}} {{#required}} + {{^conditionalSerialization}} {{^vendorExtensions.x-csharp-value-type}} // to ensure "{{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}}" is required (not null) this.{{name}} = {{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}} ?? throw new ArgumentNullException("{{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}} is a required property for {{classname}} and cannot be null"); @@ -85,6 +128,16 @@ {{#vendorExtensions.x-csharp-value-type}} this.{{name}} = {{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}}; {{/vendorExtensions.x-csharp-value-type}} + {{/conditionalSerialization}} + {{#conditionalSerialization}} + {{^vendorExtensions.x-csharp-value-type}} + // to ensure "{{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}}" is required (not null) + this._{{name}} = {{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}} ?? throw new ArgumentNullException("{{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}} is a required property for {{classname}} and cannot be null"); + {{/vendorExtensions.x-csharp-value-type}} + {{#vendorExtensions.x-csharp-value-type}} + this._{{name}} = {{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}}; + {{/vendorExtensions.x-csharp-value-type}} + {{/conditionalSerialization}} {{/required}} {{/isReadOnly}} {{/isInherited}} @@ -103,7 +156,12 @@ {{/vendorExtensions.x-csharp-value-type}} {{/defaultValue}} {{^defaultValue}} + {{^conditionalSerialization}} this.{{name}} = {{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}}; + {{/conditionalSerialization}} + {{#conditionalSerialization}} + this._{{name}} = {{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}}; + {{/conditionalSerialization}} {{/defaultValue}} {{/required}} {{/isReadOnly}} @@ -121,6 +179,7 @@ /// {{^description}}Gets or Sets {{{name}}}{{/description}}{{#description}}{{description}}{{/description}} /// {{#description}} /// {{description}}{{/description}} + {{^conditionalSerialization}} [DataMember(Name = "{{baseName}}"{{#required}}, IsRequired = true{{/required}}, EmitDefaultValue = {{#vendorExtensions.x-emit-default-value}}true{{/vendorExtensions.x-emit-default-value}}{{^vendorExtensions.x-emit-default-value}}{{#isBoolean}}true{{/isBoolean}}{{^isBoolean}}{{#isNullable}}true{{/isNullable}}{{^isNullable}}false{{/isNullable}}{{/isBoolean}}{{/vendorExtensions.x-emit-default-value}})] {{#isDate}} [JsonConverter(typeof(OpenAPIDateConverter))] @@ -136,8 +195,52 @@ { return false; } - {{/isReadOnly}} + {{/conditionalSerialization}} + {{#conditionalSerialization}} + {{#isReadOnly}} + [DataMember(Name = "{{baseName}}"{{#required}}, IsRequired = true{{/required}}, EmitDefaultValue = {{#vendorExtensions.x-emit-default-value}}true{{/vendorExtensions.x-emit-default-value}}{{^vendorExtensions.x-emit-default-value}}{{#isBoolean}}true{{/isBoolean}}{{^isBoolean}}{{#isNullable}}true{{/isNullable}}{{^isNullable}}false{{/isNullable}}{{/isBoolean}}{{/vendorExtensions.x-emit-default-value}})] + {{#isDate}} + [JsonConverter(typeof(OpenAPIDateConverter))] + {{/isDate}} + public {{{dataType}}} {{name}} { get; private set; } + + /// + /// Returns false as {{name}} should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerialize{{name}}() + { + return false; + } + {{/isReadOnly}} + {{^isReadOnly}} + {{#isDate}} + [JsonConverter(typeof(OpenAPIDateConverter))] + {{/isDate}} + [DataMember(Name = "{{baseName}}"{{#required}}, IsRequired = true{{/required}}, EmitDefaultValue = {{#vendorExtensions.x-emit-default-value}}true{{/vendorExtensions.x-emit-default-value}}{{^vendorExtensions.x-emit-default-value}}{{#isBoolean}}true{{/isBoolean}}{{^isBoolean}}{{#isNullable}}true{{/isNullable}}{{^isNullable}}false{{/isNullable}}{{/isBoolean}}{{/vendorExtensions.x-emit-default-value}})] + public {{{dataType}}} {{name}} + { + get{ return _{{name}};} + set + { + _{{name}} = value; + _flag{{name}} = true; + } + } + private {{{dataType}}} _{{name}}; + private bool _flag{{name}}; + + /// + /// Returns false as {{name}} should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerialize{{name}}() + { + return _flag{{name}}; + } + {{/isReadOnly}} + {{/conditionalSerialization}} {{/isEnum}} {{/isInherited}} {{/vars}} @@ -300,6 +403,7 @@ {{/parent}} {{#vars}} {{#hasValidation}} + {{^isEnum}} {{#maxLength}} // {{{name}}} ({{{dataType}}}) maxLength if(this.{{{name}}} != null && this.{{{name}}}.Length > {{maxLength}}) @@ -343,6 +447,7 @@ {{/isByteArray}} {{/pattern}} + {{/isEnum}} {{/hasValidation}} {{/vars}} yield break; diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore/modelOneOf.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore/modelOneOf.mustache index 6b26e1245a0..d2d6e28b3f9 100644 --- a/modules/openapi-generator/src/main/resources/csharp-netcore/modelOneOf.mustache +++ b/modules/openapi-generator/src/main/resources/csharp-netcore/modelOneOf.mustache @@ -116,7 +116,7 @@ return new{{classname}}; {{/mappedModels}} default: - System.Diagnostics.Debug.WriteLine(String.Format("Failed to lookup discriminator value `{0}` for {{classname}}. Possible values:{{#mappedModels}} {{{mappingName}}}{{/mappedModels}}", discriminatorValue)); + System.Diagnostics.Debug.WriteLine(string.Format("Failed to lookup discriminator value `{0}` for {{classname}}. Possible values:{{#mappedModels}} {{{mappingName}}}{{/mappedModels}}", discriminatorValue)); break; } @@ -143,7 +143,7 @@ catch (Exception exception) { // deserialization failed, try the next one - System.Diagnostics.Debug.WriteLine(String.Format("Failed to deserialize `{0}` into {{{.}}}: {1}", jsonString, exception.ToString())); + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into {{{.}}}: {1}", jsonString, exception.ToString())); } {{/oneOf}} @@ -232,7 +232,7 @@ /// JSON Serializer public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { - writer.WriteRawValue((String)(typeof({{classname}}).GetMethod("ToJson").Invoke(value, null))); + writer.WriteRawValue((string)(typeof({{classname}}).GetMethod("ToJson").Invoke(value, null))); } /// diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore/netcore_project.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore/netcore_project.mustache index 7d77d34b4d8..4f29dcf3d34 100644 --- a/modules/openapi-generator/src/main/resources/csharp-netcore/netcore_project.mustache +++ b/modules/openapi-generator/src/main/resources/csharp-netcore/netcore_project.mustache @@ -19,6 +19,9 @@ git{{#releaseNote}} {{releaseNote}}{{/releaseNote}}{{#packageTags}} {{{packageTags}}}{{/packageTags}} + {{#nullableReferenceTypes}} + annotations + {{/nullableReferenceTypes}} 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 2cb30d650a5..fd4168d0d4c 100644 --- a/modules/openapi-generator/src/main/resources/csharp/netcore_project.mustache +++ b/modules/openapi-generator/src/main/resources/csharp/netcore_project.mustache @@ -15,6 +15,9 @@ true {{packageName}} {{packageVersion}} + {{#nullableReferenceTypes}} + annotations + {{/nullableReferenceTypes}} diff --git a/modules/openapi-generator/src/main/resources/dart-dio/api.mustache b/modules/openapi-generator/src/main/resources/dart-dio/api.mustache index dff1dcd4235..522815498c5 100644 --- a/modules/openapi-generator/src/main/resources/dart-dio/api.mustache +++ b/modules/openapi-generator/src/main/resources/dart-dio/api.mustache @@ -63,10 +63,7 @@ class {{classname}} { ...?extra, }, validateStatus: validateStatus, - contentType: [{{^hasConsumes}} - 'application/json',{{/hasConsumes}}{{#hasConsumes}}{{#consumes}} - '{{{mediaType}}}',{{/consumes}}{{/hasConsumes}} - ].first, + contentType: '{{^hasConsumes}}application/json{{/hasConsumes}}{{#hasConsumes}}{{#prioritizedContentTypes}}{{#-first}}{{{mediaType}}}{{/-first}}{{/prioritizedContentTypes}}{{/hasConsumes}}', cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, diff --git a/modules/openapi-generator/src/main/resources/dart-dio/gitignore.mustache b/modules/openapi-generator/src/main/resources/dart-dio/gitignore.mustache index 8092a49d515..6d2ac22c0b4 100644 --- a/modules/openapi-generator/src/main/resources/dart-dio/gitignore.mustache +++ b/modules/openapi-generator/src/main/resources/dart-dio/gitignore.mustache @@ -30,8 +30,12 @@ pubspec.lock # Don’t commit files and directories created by other development environments. # For example, if your development environment creates any of the following files, # consider putting them in a global ignore file: -*.iml // IntelliJ -*.ipr // IntelliJ -*.iws // IntelliJ -.idea/ // IntelliJ -.DS_Store // Mac + +# IntelliJ +*.iml +*.ipr +*.iws +.idea/ + +# Mac +.DS_Store diff --git a/modules/openapi-generator/src/main/resources/dart-dio/pubspec.mustache b/modules/openapi-generator/src/main/resources/dart-dio/pubspec.mustache index 025230b7357..2484e50837a 100644 --- a/modules/openapi-generator/src/main/resources/dart-dio/pubspec.mustache +++ b/modules/openapi-generator/src/main/resources/dart-dio/pubspec.mustache @@ -2,8 +2,6 @@ name: {{pubName}} version: {{pubVersion}} description: {{pubDescription}} homepage: {{pubHomepage}} -authors: - - '{{{pubAuthor}}} <{{{pubAuthorEmail}}}>' environment: sdk: '>=2.7.0 <3.0.0' diff --git a/modules/openapi-generator/src/main/resources/dart/libraries/dio/README.mustache b/modules/openapi-generator/src/main/resources/dart/libraries/dio/README.mustache index 3ef0679e726..69591ce24a3 100644 --- a/modules/openapi-generator/src/main/resources/dart/libraries/dio/README.mustache +++ b/modules/openapi-generator/src/main/resources/dart/libraries/dio/README.mustache @@ -60,9 +60,9 @@ Please follow the [installation procedure](#installation--usage) and then run th import 'package:{{pubName}}/{{pubName}}.dart'; {{#apiInfo}}{{#apis}}{{#-first}}{{#operations}}{{#operation}}{{#-first}} -final api = {{classname}}(); +final api = {{clientName}}().get{{classname}}(); {{#allParams}} -final {{paramName}} = {{#isArray}}[{{/isArray}}{{#isBodyParam}}{{dataType}}(){{/isBodyParam}}{{^isBodyParam}}{{{example}}}{{/isBodyParam}}{{#isArray}}]{{/isArray}}; // {{{dataType}}} | {{{description}}} +final {{{dataType}}} {{paramName}} = {{{example}}}; // {{{dataType}}} | {{{description}}} {{/allParams}} try { @@ -82,7 +82,7 @@ All URIs are relative to *{{basePath}}* Class | Method | HTTP request | Description ------------ | ------------- | ------------- | ------------- -{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}*{{classname}}* | [**{{operationId}}**]({{apiDocPath}}{{classname}}.md#{{operationIdLowerCase}}) | **{{httpMethod}}** {{path}} | {{#summary}}{{summary}}{{/summary}} +{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}[*{{classname}}*]({{modelDocPath}}{{{classname}}}.md) | [**{{operationId}}**]({{apiDocPath}}{{classname}}.md#{{operationIdLowerCase}}) | **{{httpMethod}}** {{path}} | {{#summary}}{{summary}}{{/summary}} {{/operation}}{{/operations}}{{/apis}}{{/apiInfo}} ## Documentation For Models diff --git a/modules/openapi-generator/src/main/resources/dart/libraries/dio/api.mustache b/modules/openapi-generator/src/main/resources/dart/libraries/dio/api.mustache index 34cf9554991..cdfe8be4dd8 100644 --- a/modules/openapi-generator/src/main/resources/dart/libraries/dio/api.mustache +++ b/modules/openapi-generator/src/main/resources/dart/libraries/dio/api.mustache @@ -19,9 +19,29 @@ class {{classname}} { const {{classname}}(this._dio{{#useBuiltValue}}, this._serializers{{/useBuiltValue}}); {{#operation}} - /// {{{summary}}} + /// {{#summary}}{{.}}{{/summary}}{{^summary}}{{nickname}}{{/summary}} + /// {{notes}} /// - /// {{{notes}}} + /// Parameters: + {{#allParams}} + /// * [{{paramName}}] {{#description}}- {{{.}}}{{/description}} + {{/allParams}} + /// * [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]{{#returnType}} containing a [Response] with a [{{{returnType}}}] as data{{/returnType}} + /// Throws [DioError] if API call or serialization fails + {{#externalDocs}} + /// {{description}} + /// Also see [{{summary}} Documentation]({{url}}) + {{/externalDocs}} + {{#isDeprecated}} + @Deprecated('This operation has been deprecated') + {{/isDeprecated}} Future> {{nickname}}({ {{#allParams}}{{#isPathParam}} required {{{dataType}}} {{paramName}},{{/isPathParam}}{{#isQueryParam}} {{#required}}required {{/required}}{{{dataType}}}{{^required}}?{{/required}} {{paramName}},{{/isQueryParam}}{{#isHeaderParam}} @@ -60,43 +80,38 @@ class {{classname}} { },{{/authMethods}} ],{{/hasAuthMethods}} ...?extra, - }, - contentType: [{{^hasConsumes}} - 'application/json',{{/hasConsumes}}{{#hasConsumes}}{{#consumes}} - '{{{mediaType}}}',{{/consumes}}{{/hasConsumes}} - ].first, + },{{#hasConsumes}} + contentType: '{{#prioritizedContentTypes}}{{#-first}}{{{mediaType}}}{{/-first}}{{/prioritizedContentTypes}}',{{/hasConsumes}} validateStatus: validateStatus, - ); + );{{#hasQueryParams}} final _queryParameters = { {{#queryParams}} - {{^required}}{{^isNullable}}if ({{{paramName}}} != null) {{/isNullable}}{{/required}}r'{{baseName}}': {{paramName}}, + {{^required}}{{^isNullable}}if ({{{paramName}}} != null) {{/isNullable}}{{/required}}r'{{baseName}}': {{#useBuiltValue}}{{>serialization/built_value/query_param}}{{/useBuiltValue}}, {{/queryParams}} - }; - {{#hasBodyOrFormParams}} + };{{/hasQueryParams}}{{#hasBodyOrFormParams}} dynamic _bodyData; try { {{#useBuiltValue}}{{>serialization/built_value/serialize}}{{/useBuiltValue}} - } catch(error) { + } catch(error, stackTrace) { throw DioError( requestOptions: _options.compose( _dio.options, - _path, - queryParameters: _queryParameters, + _path,{{#hasQueryParams}} + queryParameters: _queryParameters,{{/hasQueryParams}} ), type: DioErrorType.other, error: error, - ); - } - {{/hasBodyOrFormParams}} + )..stackTrace = stackTrace; + }{{/hasBodyOrFormParams}} final _response = await _dio.request( _path,{{#hasBodyOrFormParams}} data: _bodyData,{{/hasBodyOrFormParams}} - options: _options, - queryParameters: _queryParameters, + options: _options,{{#hasQueryParams}} + queryParameters: _queryParameters,{{/hasQueryParams}} cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, @@ -107,13 +122,13 @@ class {{classname}} { try { {{#useBuiltValue}}{{>serialization/built_value/deserialize}}{{/useBuiltValue}} - } catch (error) { + } catch (error, stackTrace) { throw DioError( requestOptions: _response.requestOptions, response: _response, type: DioErrorType.other, error: error, - ); + )..stackTrace = stackTrace; } return Response<{{{returnType}}}>( diff --git a/modules/openapi-generator/src/main/resources/dart/libraries/dio/api_doc.mustache b/modules/openapi-generator/src/main/resources/dart/libraries/dio/api_doc.mustache index 1e28b16012e..548c8b140ce 100644 --- a/modules/openapi-generator/src/main/resources/dart/libraries/dio/api_doc.mustache +++ b/modules/openapi-generator/src/main/resources/dart/libraries/dio/api_doc.mustache @@ -45,17 +45,17 @@ import 'package:{{pubName}}/api.dart'; {{/authMethods}} {{/hasAuthMethods}} -var api_instance = new {{classname}}(); +final api = {{clientName}}().get{{classname}}(); {{#allParams}} -var {{paramName}} = {{#isArray}}[{{/isArray}}{{#isBodyParam}}new {{{dataType}}}(){{/isBodyParam}}{{^isBodyParam}}{{{example}}}{{/isBodyParam}}{{#isArray}}]{{/isArray}}; // {{{dataType}}} | {{{description}}} +final {{{dataType}}} {{paramName}} = {{{example}}}; // {{{dataType}}} | {{{description}}} {{/allParams}} try { - {{#returnType}}var result = {{/returnType}}api_instance.{{{operationId}}}({{#allParams}}{{paramName}}{{^-last}}, {{/-last}}{{/allParams}}); + {{#returnType}}final response = {{/returnType}}api.{{{operationId}}}({{#allParams}}{{paramName}}{{^-last}}, {{/-last}}{{/allParams}}); {{#returnType}} - print(result); + print(response); {{/returnType}} -} catch (e) { +} catch on DioError (e) { print('Exception when calling {{classname}}->{{operationId}}: $e\n'); } ``` @@ -64,12 +64,12 @@ try { {{^allParams}}This endpoint does not need any parameter.{{/allParams}}{{#allParams}}{{#-last}} Name | Type | Description | Notes ------------- | ------------- | ------------- | -------------{{/-last}}{{/allParams}} -{{#allParams}} **{{paramName}}** | {{#isPrimitiveType}}**{{{dataType}}}**{{/isPrimitiveType}}{{^isPrimitiveType}}[**{{{dataType}}}**]({{baseType}}.md){{/isPrimitiveType}}| {{{description}}} | {{^required}}[optional] {{/required}}{{#defaultValue}}[default to {{{defaultValue}}}]{{/defaultValue}} +{{#allParams}} **{{paramName}}** | {{#isPrimitiveType}}**{{dataType}}**{{/isPrimitiveType}}{{^isPrimitiveType}}[**{{dataType}}**]({{baseType}}.md){{/isPrimitiveType}}| {{{description}}} | {{^required}}[optional] {{/required}}{{#defaultValue}}[default to {{{defaultValue}}}]{{/defaultValue}} {{/allParams}} ### Return type -{{#returnType}}{{#returnTypeIsPrimitive}}**{{{returnType}}}**{{/returnTypeIsPrimitive}}{{^returnTypeIsPrimitive}}[**{{{returnType}}}**]({{returnBaseType}}.md){{/returnTypeIsPrimitive}}{{/returnType}}{{^returnType}}void (empty response body){{/returnType}} +{{#returnType}}{{#returnTypeIsPrimitive}}**{{returnType}}**{{/returnTypeIsPrimitive}}{{^returnTypeIsPrimitive}}[**{{returnType}}**]({{returnBaseType}}.md){{/returnTypeIsPrimitive}}{{/returnType}}{{^returnType}}void (empty response body){{/returnType}} ### Authorization diff --git a/modules/openapi-generator/src/main/resources/dart/libraries/dio/api_util.mustache b/modules/openapi-generator/src/main/resources/dart/libraries/dio/api_util.mustache deleted file mode 100644 index 4cdc6bcea3c..00000000000 --- a/modules/openapi-generator/src/main/resources/dart/libraries/dio/api_util.mustache +++ /dev/null @@ -1,28 +0,0 @@ -{{>header}} -import 'dart:convert'; - -import 'package:built_collection/built_collection.dart'; -import 'package:built_value/serializer.dart'; - -/// Format the given form parameter object into something that Dio can handle. -/// Returns primitive or String. -/// Returns List/Map if the value is BuildList/BuiltMap. -dynamic encodeFormParameter(Serializers serializers, dynamic value, FullType type) { - if (value == null) { - return ''; - } - if (value is String || value is num || value is bool) { - return value; - } - final serialized = serializers.serialize( - value as Object, - specifiedType: type, - ); - if (serialized is String) { - return serialized; - } - if (value is BuiltList || value is BuiltMap) { - return serialized; - } - return json.encode(serialized); -} diff --git a/modules/openapi-generator/src/main/resources/dart/libraries/dio/gitignore.mustache b/modules/openapi-generator/src/main/resources/dart/libraries/dio/gitignore.mustache index 8092a49d515..6d2ac22c0b4 100644 --- a/modules/openapi-generator/src/main/resources/dart/libraries/dio/gitignore.mustache +++ b/modules/openapi-generator/src/main/resources/dart/libraries/dio/gitignore.mustache @@ -30,8 +30,12 @@ pubspec.lock # Don’t commit files and directories created by other development environments. # For example, if your development environment creates any of the following files, # consider putting them in a global ignore file: -*.iml // IntelliJ -*.ipr // IntelliJ -*.iws // IntelliJ -.idea/ // IntelliJ -.DS_Store // Mac + +# IntelliJ +*.iml +*.ipr +*.iws +.idea/ + +# Mac +.DS_Store diff --git a/modules/openapi-generator/src/main/resources/dart/libraries/dio/object_doc.mustache b/modules/openapi-generator/src/main/resources/dart/libraries/dio/object_doc.mustache index f2a52db11a4..84b70087bf4 100644 --- a/modules/openapi-generator/src/main/resources/dart/libraries/dio/object_doc.mustache +++ b/modules/openapi-generator/src/main/resources/dart/libraries/dio/object_doc.mustache @@ -8,7 +8,7 @@ import 'package:{{pubName}}/api.dart'; ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -{{#vars}}**{{name}}** | {{#isPrimitiveType}}**{{{dataType}}}**{{/isPrimitiveType}}{{^isPrimitiveType}}[**{{{dataType}}}**]({{complexType}}.md){{/isPrimitiveType}} | {{{description}}} | {{^required}}[optional] {{/required}}{{#readOnly}}[readonly] {{/readOnly}}{{#defaultValue}}[default to {{{defaultValue}}}]{{/defaultValue}} +{{#vars}}**{{name}}** | {{#isPrimitiveType}}**{{dataType}}**{{/isPrimitiveType}}{{^isPrimitiveType}}[**{{dataType}}**]({{complexType}}.md){{/isPrimitiveType}} | {{{description}}} | {{^required}}[optional] {{/required}}{{#readOnly}}[readonly] {{/readOnly}}{{#defaultValue}}[default to {{{defaultValue}}}]{{/defaultValue}} {{/vars}} [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) 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 b2eef72f91e..991de1e44b5 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 @@ -2,8 +2,6 @@ name: {{pubName}} version: {{pubVersion}} description: {{pubDescription}} homepage: {{pubHomepage}} -authors: - - '{{{pubAuthor}}} <{{{pubAuthorEmail}}}>' environment: sdk: '>=2.12.0 <3.0.0' diff --git a/modules/openapi-generator/src/main/resources/dart/libraries/dio/serialization/built_value/api_util.mustache b/modules/openapi-generator/src/main/resources/dart/libraries/dio/serialization/built_value/api_util.mustache new file mode 100644 index 00000000000..fb5ab08aeda --- /dev/null +++ b/modules/openapi-generator/src/main/resources/dart/libraries/dio/serialization/built_value/api_util.mustache @@ -0,0 +1,75 @@ +{{>header}} +import 'dart:convert'; +import 'dart:typed_data'; + +import 'package:built_collection/built_collection.dart'; +import 'package:built_value/serializer.dart'; +import 'package:dio/dio.dart'; +import 'package:dio/src/parameter.dart'; + +/// Format the given form parameter object into something that Dio can handle. +/// Returns primitive or String. +/// Returns List/Map if the value is BuildList/BuiltMap. +dynamic encodeFormParameter(Serializers serializers, dynamic value, FullType type) { + if (value == null) { + return ''; + } + if (value is String || value is num || value is bool) { + return value; + } + final serialized = serializers.serialize( + value as Object, + specifiedType: type, + ); + if (serialized is String) { + return serialized; + } + if (value is BuiltList || value is BuiltSet || value is BuiltMap) { + return serialized; + } + return json.encode(serialized); +} + +dynamic encodeQueryParameter( + Serializers serializers, + dynamic value, + FullType type, +) { + if (value == null) { + return ''; + } + if (value is String || value is num || value is bool) { + return value; + } + if (value is Uint8List) { + // Currently not sure how to serialize this + return value; + } + final serialized = serializers.serialize( + value as Object, + specifiedType: type, + ); + if (serialized == null) { + return ''; + } + if (serialized is String) { + return serialized; + } + return serialized; +} + +ListParam encodeCollectionQueryParameter( + Serializers serializers, + dynamic value, + FullType type, { + ListFormat format = ListFormat.multi, +}) { + final serialized = serializers.serialize( + value as Object, + specifiedType: type, + ); + if (value is BuiltList || value is BuiltSet) { + return ListParam(List.of((serialized as Iterable).cast()), format); + } + throw ArgumentError('Invalid value passed to encodeCollectionQueryParameter'); +} diff --git a/modules/openapi-generator/src/main/resources/dart/libraries/dio/serialization/built_value/class.mustache b/modules/openapi-generator/src/main/resources/dart/libraries/dio/serialization/built_value/class.mustache index f359b8d5a91..9eb53c756c7 100644 --- a/modules/openapi-generator/src/main/resources/dart/libraries/dio/serialization/built_value/class.mustache +++ b/modules/openapi-generator/src/main/resources/dart/libraries/dio/serialization/built_value/class.mustache @@ -7,8 +7,18 @@ part '{{classFilename}}.g.dart'; Classes with polymorphism or composition may generate unused imports, these need to be ignored for said classes so that there are no lint errors. }} -{{#parentModel}}// ignore_for_file: unused_import{{/parentModel}} +{{#parentModel}} +// ignore_for_file: unused_import +{{/parentModel}} +/// {{#description}}{{{.}}}{{/description}}{{^description}}{{classname}}{{/description}} +{{#hasVars}} +/// +/// Properties: +{{#allVars}} +/// * [{{{name}}}] {{#description}}- {{{.}}}{{/description}} +{{/allVars}} +{{/hasVars}} abstract class {{classname}} implements Built<{{classname}}, {{classname}}Builder> { {{#vars}} {{#description}} diff --git a/modules/openapi-generator/src/main/resources/dart/libraries/dio/serialization/built_value/date.mustache b/modules/openapi-generator/src/main/resources/dart/libraries/dio/serialization/built_value/date.mustache index c3a87eae259..b21c7f544be 100644 --- a/modules/openapi-generator/src/main/resources/dart/libraries/dio/serialization/built_value/date.mustache +++ b/modules/openapi-generator/src/main/resources/dart/libraries/dio/serialization/built_value/date.mustache @@ -24,9 +24,10 @@ class Date implements Comparable { /// Convert to a [DateTime]. DateTime toDateTime({bool utc = false}) { if (utc) { - DateTime.utc(year, month, day); + return DateTime.utc(year, month, day); + } else { + return DateTime(year, month, day); } - return DateTime(year, month, day); } @override @@ -66,4 +67,4 @@ class Date implements Comparable { extension DateTimeToDate on DateTime { Date toDate() => Date(year, month, day); -} \ No newline at end of file +} diff --git a/modules/openapi-generator/src/main/resources/dart/libraries/dio/serialization/built_value/query_param.mustache b/modules/openapi-generator/src/main/resources/dart/libraries/dio/serialization/built_value/query_param.mustache new file mode 100644 index 00000000000..3a27e77225e --- /dev/null +++ b/modules/openapi-generator/src/main/resources/dart/libraries/dio/serialization/built_value/query_param.mustache @@ -0,0 +1 @@ +{{#isContainer}}encodeCollectionQueryParameter<{{{baseType}}}>{{/isContainer}}{{^isContainer}}encodeQueryParameter{{/isContainer}}(_serializers, {{{paramName}}}, const FullType({{^isContainer}}{{{dataType}}}){{/isContainer}}{{#isContainer}}Built{{#isMap}}Map{{/isMap}}{{#isArray}}{{#uniqueItems}}Set{{/uniqueItems}}{{^uniqueItems}}List{{/uniqueItems}}{{/isArray}}, [{{#isMap}}FullType(String), {{/isMap}}FullType({{{baseType}}})]), format: ListFormat.{{collectionFormat}}{{/isContainer}}) \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/dart/libraries/dio/serialization/built_value/serialize.mustache b/modules/openapi-generator/src/main/resources/dart/libraries/dio/serialization/built_value/serialize.mustache index 5794f34ad1a..60dcd1773ba 100644 --- a/modules/openapi-generator/src/main/resources/dart/libraries/dio/serialization/built_value/serialize.mustache +++ b/modules/openapi-generator/src/main/resources/dart/libraries/dio/serialization/built_value/serialize.mustache @@ -1,13 +1,22 @@ {{#hasFormParams}} - _bodyData = {{#isMultipart}}FormData.fromMap({{/isMultipart}}{ + {{#isMultipart}} + _bodyData = FormData.fromMap({ {{#formParams}} - {{^required}}{{^isNullable}}if ({{{paramName}}} != null) {{/isNullable}}{{/required}}r'{{{baseName}}}': {{#isFile}}MultipartFile.fromBytes({{{paramName}}}, filename: r'{{{baseName}}}'){{/isFile}}{{^isFile}}encodeFormParameter(_serializers, {{{paramName}}}, const FullType({{^isContainer}}{{{baseType}}}{{/isContainer}}{{#isContainer}}Built{{#isMap}}Map{{/isMap}}{{#isArray}}{{#uniqueItems}}Set{{/uniqueItems}}{{^uniqueItems}}List{{/uniqueItems}}{{/isArray}}, [{{#isMap}}FullType(String), {{/isMap}}FullType({{{baseType}}})]{{/isContainer}})){{/isFile}}, + {{^required}}{{^isNullable}}if ({{{paramName}}} != null) {{/isNullable}}{{/required}}r'{{{baseName}}}': {{#isFile}}{{{paramName}}}{{/isFile}}{{^isFile}}encodeFormParameter(_serializers, {{{paramName}}}, const FullType({{^isContainer}}{{{baseType}}}{{/isContainer}}{{#isContainer}}Built{{#isMap}}Map{{/isMap}}{{#isArray}}{{#uniqueItems}}Set{{/uniqueItems}}{{^uniqueItems}}List{{/uniqueItems}}{{/isArray}}, [{{#isMap}}FullType(String), {{/isMap}}FullType({{{baseType}}})]{{/isContainer}})){{/isFile}}, {{/formParams}} - }{{#isMultipart}}){{/isMultipart}}; + }); + {{/isMultipart}} + {{^isMultipart}} + _bodyData = { + {{#formParams}} + {{^required}}{{^isNullable}}if ({{{paramName}}} != null) {{/isNullable}}{{/required}}r'{{{baseName}}}': {{>serialization/built_value/query_param}}, + {{/formParams}} + }; + {{/isMultipart}} {{/hasFormParams}} {{#bodyParam}} {{#isPrimitiveType}} - _bodyData = {{paramName}}; + _bodyData = {{paramName}}{{#isFile}}.finalize(){{/isFile}}; {{/isPrimitiveType}} {{^isPrimitiveType}} {{#isContainer}} diff --git a/modules/openapi-generator/src/main/resources/dart2/analysis_options.mustache b/modules/openapi-generator/src/main/resources/dart2/analysis_options.mustache new file mode 100644 index 00000000000..83d5a10bd7b --- /dev/null +++ b/modules/openapi-generator/src/main/resources/dart2/analysis_options.mustache @@ -0,0 +1,3 @@ +analyzer: + strong-mode: + implicit-casts: true diff --git a/modules/openapi-generator/src/main/resources/dart2/api.mustache b/modules/openapi-generator/src/main/resources/dart2/api.mustache index d99ba2b325f..a7bb9289143 100644 --- a/modules/openapi-generator/src/main/resources/dart2/api.mustache +++ b/modules/openapi-generator/src/main/resources/dart2/api.mustache @@ -95,43 +95,41 @@ class {{{classname}}} { {{/headerParams}} {{/hasHeaderParams}} - final contentTypes = [{{#consumes}}'{{{mediaType}}}'{{^-last}}, {{/-last}}{{/consumes}}]; + final contentTypes = [{{#prioritizedContentTypes}}'{{{mediaType}}}'{{^-last}}, {{/-last}}{{/prioritizedContentTypes}}]; final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = [{{#authMethods}}'{{{name}}}'{{^-last}}, {{/-last}}{{/authMethods}}]; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - {{#formParams}} - {{^isFile}} - if ({{{paramName}}} != null) { - hasFields = true; - mp.fields[r'{{{baseName}}}'] = parameterToString({{{paramName}}}); - } - {{/isFile}} - {{#isFile}} - if ({{{paramName}}} != null) { - hasFields = true; - mp.fields[r'{{{baseName}}}'] = {{{paramName}}}.field; - mp.files.add({{{paramName}}}); - } - {{/isFile}} - {{/formParams}} - if (hasFields) { - postBody = mp; - } - } else { - {{#formParams}} - {{^isFile}} - if ({{{paramName}}} != null) { - formParams[r'{{{baseName}}}'] = parameterToString({{{paramName}}}); - } - {{/isFile}} - {{/formParams}} + {{#isMultipart}} + bool hasFields = false; + final mp = MultipartRequest('{{{httpMethod}}}', Uri.parse(path)); + {{#formParams}} + {{^isFile}} + if ({{{paramName}}} != null) { + hasFields = true; + mp.fields[r'{{{baseName}}}'] = parameterToString({{{paramName}}}); } + {{/isFile}} + {{#isFile}} + if ({{{paramName}}} != null) { + hasFields = true; + mp.fields[r'{{{baseName}}}'] = {{{paramName}}}.field; + mp.files.add({{{paramName}}}); + } + {{/isFile}} + {{/formParams}} + if (hasFields) { + postBody = mp; + } + {{/isMultipart}} + {{^isMultipart}} + {{#formParams}} + {{^isFile}} + if ({{{paramName}}} != null) { + formParams[r'{{{baseName}}}'] = parameterToString({{{paramName}}}); + } + {{/isFile}} + {{/formParams}} + {{/isMultipart}} return await apiClient.invokeAPI( path, diff --git a/modules/openapi-generator/src/main/resources/dart2/api_client.mustache b/modules/openapi-generator/src/main/resources/dart2/api_client.mustache index f3af060d514..d7f90713d5f 100644 --- a/modules/openapi-generator/src/main/resources/dart2/api_client.mustache +++ b/modules/openapi-generator/src/main/resources/dart2/api_client.mustache @@ -65,7 +65,7 @@ class ApiClient { Future invokeAPI( String path, String method, - Iterable queryParams, + List queryParams, Object body, Map headerParams, Map formParams, @@ -177,13 +177,13 @@ class ApiClient { List queryParams, Map headerParams, ) { - authNames.forEach((authName) { + for(final authName in authNames) { final auth = _authentications[authName]; if (auth == null) { throw ArgumentError('Authentication undefined: $authName'); } auth.applyToParams(queryParams, headerParams); - }); + } } {{#native_serialization}} diff --git a/modules/openapi-generator/src/main/resources/dart2/api_exception.mustache b/modules/openapi-generator/src/main/resources/dart2/api_exception.mustache index 40f4fda731e..28f734e5587 100644 --- a/modules/openapi-generator/src/main/resources/dart2/api_exception.mustache +++ b/modules/openapi-generator/src/main/resources/dart2/api_exception.mustache @@ -10,6 +10,7 @@ class ApiException implements Exception { Exception innerException; StackTrace stackTrace; + @override String toString() { if (message == null) { return 'ApiException'; diff --git a/modules/openapi-generator/src/main/resources/dart2/api_helper.mustache b/modules/openapi-generator/src/main/resources/dart2/api_helper.mustache index 92f394176f6..e99fbb0505d 100644 --- a/modules/openapi-generator/src/main/resources/dart2/api_helper.mustache +++ b/modules/openapi-generator/src/main/resources/dart2/api_helper.mustache @@ -19,7 +19,7 @@ Iterable _convertParametersForCollectionFormat( final params = []; // preconditions - if (name != null && !name.isEmpty && value != null) { + if (name != null && name.isNotEmpty && value != null) { if (value is List) { // get the collection format, default: csv collectionFormat = (collectionFormat == null || collectionFormat.isEmpty) diff --git a/modules/openapi-generator/src/main/resources/dart2/pubspec.mustache b/modules/openapi-generator/src/main/resources/dart2/pubspec.mustache index 93c848aa5c1..4ce12df9e48 100644 --- a/modules/openapi-generator/src/main/resources/dart2/pubspec.mustache +++ b/modules/openapi-generator/src/main/resources/dart2/pubspec.mustache @@ -5,8 +5,6 @@ name: '{{{pubName}}}' version: '{{{pubVersion}}}' description: '{{{pubDescription}}}' -authors: - - '{{{pubAuthor}}} <{{{pubAuthorEmail}}}>' homepage: '{{{pubHomepage}}}' environment: sdk: '>=2.12.0 <3.0.0' diff --git a/modules/openapi-generator/src/main/resources/dart2/serialization/native/native_class.mustache b/modules/openapi-generator/src/main/resources/dart2/serialization/native/native_class.mustache index 0e4520d3e98..1d599915a0a 100644 --- a/modules/openapi-generator/src/main/resources/dart2/serialization/native/native_class.mustache +++ b/modules/openapi-generator/src/main/resources/dart2/serialization/native/native_class.mustache @@ -132,9 +132,19 @@ class {{{classname}}} { {{/items.complexType}} {{/items.isArray}} {{^items.isArray}} + {{#items.isMap}} {{{name}}}: json[r'{{{baseName}}}'] == null ? null - : {{{complexType}}}.mapFromJson(json[r'{{{baseName}}}']), + {{#items.complexType}} + : {{items.complexType}}.mapFromJson(json[r'{{{baseName}}}']), + {{/items.complexType}} + {{^items.complexType}} + : (json[r'{{{baseName}}}'] as Map).cast(), + {{/items.complexType}} + {{/items.isMap}} + {{^items.isMap}} + {{{name}}}: json[r'{{{baseName}}}'] + {{/items.isMap}} {{/items.isArray}} {{/isMap}} {{^isMap}} @@ -189,12 +199,12 @@ class {{{classname}}} { static List<{{{classname}}}> listFromJson(List json, {bool emptyIsNull, bool growable,}) => json == null || json.isEmpty ? true == emptyIsNull ? null : <{{{classname}}}>[] - : json.map((v) => {{{classname}}}.fromJson(v)).toList(growable: true == growable); + : json.map((dynamic value) => {{{classname}}}.fromJson(value)).toList(growable: true == growable); static Map mapFromJson(Map json) { final map = {}; - if (json != null && json.isNotEmpty) { - json.forEach((String key, dynamic v) => map[key] = {{{classname}}}.fromJson(v)); + if (json?.isNotEmpty == true) { + json.forEach((key, value) => map[key] = {{{classname}}}.fromJson(value)); } return map; } @@ -202,9 +212,9 @@ class {{{classname}}} { // maps a json object with a list of {{{classname}}}-objects as value to a dart map static Map> mapListFromJson(Map json, {bool emptyIsNull, bool growable,}) { final map = >{}; - if (json != null && json.isNotEmpty) { - json.forEach((String key, dynamic v) { - map[key] = {{{classname}}}.listFromJson(v, emptyIsNull: emptyIsNull, growable: growable); + if (json?.isNotEmpty == true) { + json.forEach((key, value) { + map[key] = {{{classname}}}.listFromJson(value, emptyIsNull: emptyIsNull, growable: growable,); }); } return map; diff --git a/modules/openapi-generator/src/main/resources/erlang-client/api.mustache b/modules/openapi-generator/src/main/resources/erlang-client/api.mustache index a2335745bbb..ddb5dee0138 100644 --- a/modules/openapi-generator/src/main/resources/erlang-client/api.mustache +++ b/modules/openapi-generator/src/main/resources/erlang-client/api.mustache @@ -3,7 +3,7 @@ -export([{{#operations}}{{#operation}}{{^-first}}, {{/-first}}{{operationId}}/{{arityRequired}}, {{operationId}}/{{arityOptional}}{{/operation}}{{/operations}}]). --define(BASE_URL, "{{{basePathWithoutHost}}}"). +-define(BASE_URL, <<"{{{basePathWithoutHost}}}">>). {{#operations}} {{#operation}} @@ -21,7 +21,7 @@ Cfg = maps:get(cfg, Optional, application:get_env(kuberl, config, #{})), Method = {{httpMethod}}, - Path = ["{{{replacedPathName}}}"], + Path = [<<"{{{replacedPathName}}}">>], QS = {{#queryParams.isEmpty}}[]{{/queryParams.isEmpty}}{{^queryParams.isEmpty}}lists:flatten([{{#joinWithComma}}{{#queryParams}}{{#required}}{{#qsEncode}}{{this}}{{/qsEncode}} {{/required}}{{/queryParams}}{{/joinWithComma}}])++{{packageName}}_utils:optional_params([{{#joinWithComma}}{{#queryParams}}{{^required}} '{{baseName}}'{{/required}}{{/queryParams}}{{/joinWithComma}}], _OptionalParams){{/queryParams.isEmpty}}, Headers = {{#headerParams.isEmpty}}[]{{/headerParams.isEmpty}}{{^headerParams.isEmpty}}[{{#headerParams}}{{#required}} {<<"{{baseName}}">>, {{paramName}}}{{/required}}{{/headerParams}}]++{{packageName}}_utils:optional_params([{{#joinWithComma}}{{#headerParams}}{{^required}} '{{baseName}}'{{/required}}{{/headerParams}}{{/joinWithComma}}], _OptionalParams){{/headerParams.isEmpty}}, Body1 = {{^formParams.isEmpty}}{form, [{{#joinWithComma}}{{#formParams}}{{#required}} {<<"{{baseName}}">>, {{paramName}}}{{/required}}{{/formParams}}{{/joinWithComma}}]++{{packageName}}_utils:optional_params([{{#joinWithComma}}{{#formParams}}{{^required}} '{{baseName}}'{{/required}}{{/formParams}}{{/joinWithComma}}], _OptionalParams)}{{/formParams.isEmpty}}{{#formParams.isEmpty}}{{#bodyParams.isEmpty}}[]{{/bodyParams.isEmpty}}{{^bodyParams.isEmpty}}{{#bodyParams}}{{paramName}}{{/bodyParams}}{{/bodyParams.isEmpty}}{{/formParams.isEmpty}}, diff --git a/modules/openapi-generator/src/main/resources/erlang-server/handler.mustache b/modules/openapi-generator/src/main/resources/erlang-server/handler.mustache index 80314899a38..270d3ee7050 100644 --- a/modules/openapi-generator/src/main/resources/erlang-server/handler.mustache +++ b/modules/openapi-generator/src/main/resources/erlang-server/handler.mustache @@ -209,7 +209,7 @@ process_response(Response, Req0, State = #state{operation_id = OperationID}) -> {stop, Req, State} end. --spec handle_request_json(cowboy_req:req(), state()) -> {cowboy_req:resp_body(), cowboy_req:req(), state()}. +-spec handle_request_json(cowboy_req:req(), state()) -> processed_response(). handle_request_json( Req0, @@ -233,7 +233,7 @@ handle_request_json( Body, ValidatorState ), - PreparedBody = jsx:encode(Body), + PreparedBody = prepare_body(Code, Body), Response = {ok, {Code, Headers, PreparedBody}}, process_response(Response, Req1, State); {error, Reason, Req1} -> @@ -241,3 +241,10 @@ handle_request_json( end. validate_headers(_, Req) -> {true, Req}. + +prepare_body(204, Body) when map_size(Body) == 0; length(Body) == 0 -> + <<>>; +prepare_body(304, Body) when map_size(Body) == 0; length(Body) == 0 -> + <<>>; +prepare_body(_Code, Body) -> + jsx:encode(Body). diff --git a/modules/openapi-generator/src/main/resources/erlang-server/logic_handler.mustache b/modules/openapi-generator/src/main/resources/erlang-server/logic_handler.mustache index c8af361cd96..eb0688e682c 100644 --- a/modules/openapi-generator/src/main/resources/erlang-server/logic_handler.mustache +++ b/modules/openapi-generator/src/main/resources/erlang-server/logic_handler.mustache @@ -15,8 +15,7 @@ -type handler_response() ::{ Status :: cowboy:http_status(), Headers :: cowboy:http_headers(), - Body :: #{} -}. + Body :: jsx:json_term()}. -export_type([handler_response/0]). diff --git a/modules/openapi-generator/src/main/resources/erlang-server/server.mustache b/modules/openapi-generator/src/main/resources/erlang-server/server.mustache index 204a8fd8659..cca0af57a84 100644 --- a/modules/openapi-generator/src/main/resources/erlang-server/server.mustache +++ b/modules/openapi-generator/src/main/resources/erlang-server/server.mustache @@ -64,4 +64,4 @@ get_default_opts(LogicHandler) -> #{env => get_default_dispatch(LogicHandler)}. store_key(Key, Value, Opts) -> - lists:keystore(Key, 1, Opts, {Key, Value}). + maps:put(Key, Value, Opts). 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 8eb63de4ea0..c8636474dc9 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 @@ -33,6 +33,8 @@ func NewRouter() *gin.Engine { router.POST(route.Pattern, route.HandlerFunc) case http.MethodPut: router.PUT(route.Pattern, route.HandlerFunc) + case http.MethodPatch: + router.PATCH(route.Pattern, route.HandlerFunc) case http.MethodDelete: router.DELETE(route.Pattern, route.HandlerFunc) } 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 2c6b5da8b52..6dd5138e525 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 @@ -6,7 +6,14 @@ import ( "net/http" "strings" +{{#routers}} + {{#mux}} "github.com/gorilla/mux" + {{/mux}} + {{#chi}} + "github.com/go-chi/chi/v5" + {{/chi}} +{{/routers}} ) // A {{classname}}Controller binds http requests to an api service and writes the service results to the http response @@ -47,23 +54,27 @@ func (c *{{classname}}Controller) {{nickname}}(w http.ResponseWriter, r *http.Re } {{/isMultipart}} {{/hasFormParams}} - {{#hasPathParams}} + {{#routers}} + {{#mux}} + {{#hasPathParams}} params := mux.Vars(r) - {{/hasPathParams}} + {{/hasPathParams}} + {{/mux}} + {{/routers}} {{#hasQueryParams}} query := r.URL.Query() {{/hasQueryParams}} {{#allParams}} {{#isPathParam}} {{#isLong}} - {{paramName}}, err := parseInt64Parameter(params["{{baseName}}"], {{required}}) + {{paramName}}, err := parseInt64Parameter({{#routers}}{{#mux}}params["{{baseName}}"]{{/mux}}{{#chi}}chi.URLParam(r, "{{baseName}}"){{/chi}}{{/routers}}, {{required}}) if err != nil { w.WriteHeader(http.StatusBadRequest) return } {{/isLong}} {{#isInteger}} - {{paramName}}, err := parseInt32Parameter(params["{{baseName}}"], {{required}}) + {{paramName}}, err := parseInt32Parameter({{#routers}}{{#mux}}params["{{baseName}}"]{{/mux}}{{#chi}}chi.URLParam(r, "{{baseName}}"){{/chi}}{{/routers}}, {{required}}) if err != nil { w.WriteHeader(http.StatusBadRequest) return @@ -71,7 +82,7 @@ func (c *{{classname}}Controller) {{nickname}}(w http.ResponseWriter, r *http.Re {{/isInteger}} {{^isLong}} {{^isInteger}} - {{paramName}} := params["{{baseName}}"] + {{paramName}} := {{#routers}}{{#mux}}params["{{baseName}}"]{{/mux}}{{#chi}}chi.URLParam(r, "{{baseName}}"){{/chi}}{{/routers}} {{/isInteger}}{{/isLong}} {{/isPathParam}} {{#isQueryParam}} @@ -90,7 +101,7 @@ func (c *{{classname}}Controller) {{nickname}}(w http.ResponseWriter, r *http.Re } {{/isInteger}} {{#isBoolean}} - {{paramName}}, err := parseBoolParameter(query.Get("{{paramName}}")) + {{paramName}}, err := parseBoolParameter(query.Get("{{baseName}}")) if err != nil { w.WriteHeader(500) return @@ -99,7 +110,7 @@ func (c *{{classname}}Controller) {{nickname}}(w http.ResponseWriter, r *http.Re {{^isLong}} {{^isInteger}} {{^isBoolean}} - {{paramName}} := {{#isArray}}strings.Split({{/isArray}}query.Get("{{paramName}}"){{#isArray}}, ","){{/isArray}} + {{paramName}} := {{#isArray}}strings.Split({{/isArray}}query.Get("{{baseName}}"){{#isArray}}, ","){{/isArray}} {{/isBoolean}} {{/isInteger}} {{/isLong}} diff --git a/modules/openapi-generator/src/main/resources/go-server/go.mod.mustache b/modules/openapi-generator/src/main/resources/go-server/go.mod.mustache index 18f7e897253..ad22f71f6ba 100644 --- a/modules/openapi-generator/src/main/resources/go-server/go.mod.mustache +++ b/modules/openapi-generator/src/main/resources/go-server/go.mod.mustache @@ -2,4 +2,17 @@ module {{gitHost}}/{{gitUserId}}/{{gitRepoId}} go 1.13 +{{#routers}} + {{#mux}} require github.com/gorilla/mux v1.7.3 + {{#featureCORS}} +require github.com/gorilla/handlers v1.5.1 + {{/featureCORS}} + {{/mux}} + {{#chi}} +require github.com/go-chi/chi/v5 v5.0.3 + {{#featureCORS}} +require github.com/go-chi/cors v1.2.0 + {{/featureCORS}} + {{/chi}} +{{/routers}} 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 2f67ffafc3b..89860a8fe72 100644 --- a/modules/openapi-generator/src/main/resources/go-server/model.mustache +++ b/modules/openapi-generator/src/main/resources/go-server/model.mustache @@ -17,6 +17,16 @@ const ( ){{/isEnum}}{{^isEnum}}{{#description}} // {{classname}} - {{{description}}}{{/description}} type {{classname}} struct { +{{#parent}} +{{^isMap}} +{{^isArray}} + {{{parent}}} +{{/isArray}} +{{/isMap}} +{{#isArray}} + Items {{{parent}}} +{{/isArray}} +{{/parent}} {{#vars}}{{#description}} // {{{description}}}{{/description}} {{name}} {{#isNullable}}*{{/isNullable}}{{{dataType}}} `json:"{{baseName}}{{^required}},omitempty{{/required}}"{{#vendorExtensions.x-go-custom-tag}} {{{.}}}{{/vendorExtensions.x-go-custom-tag}}` 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 d76397166c6..b26f8febb41 100644 --- a/modules/openapi-generator/src/main/resources/go-server/routers.mustache +++ b/modules/openapi-generator/src/main/resources/go-server/routers.mustache @@ -4,10 +4,21 @@ package {{packageName}} import ( "encoding/json" "errors" +{{#routers}} + {{#mux}} "github.com/gorilla/mux" {{#featureCORS}} "github.com/gorilla/handlers" {{/featureCORS}} + {{/mux}} + {{#chi}} + "github.com/go-chi/chi/v5" + "github.com/go-chi/chi/v5/middleware" + {{#featureCORS}} + "github.com/go-chi/cors" + {{/featureCORS}} + {{/chi}} +{{/routers}} "io/ioutil" "mime/multipart" "net/http" @@ -35,12 +46,25 @@ type Router interface { const errMsgRequiredMissing = "required parameter is missing" // NewRouter creates a new router for any number of api routers -func NewRouter(routers ...Router) *mux.Router { +func NewRouter(routers ...Router) {{#routers}}{{#mux}}*mux.Router{{/mux}}{{#chi}}chi.Router{{/chi}}{{/routers}} { +{{#routers}} + {{#mux}} router := mux.NewRouter().StrictSlash(true) + {{/mux}} + {{#chi}} + router := chi.NewRouter() + router.Use(middleware.Logger) + {{#featureCORS}} + router.Use(cors.Handler(cors.Options{})) + {{/featureCORS}} + {{/chi}} +{{/routers}} for _, api := range routers { for _, route := range api.Routes() { var handler http.Handler handler = route.HandlerFunc +{{#routers}} + {{#mux}} handler = Logger(handler, route.Name) {{#featureCORS}} handler = handlers.CORS()(handler) @@ -51,6 +75,11 @@ func NewRouter(routers ...Router) *mux.Router { Path(route.Pattern). Name(route.Name). Handler(handler) + {{/mux}} + {{#chi}} + router.Method(route.Method, route.Pattern, handler) + {{/chi}} +{{/routers}} } } @@ -59,7 +88,7 @@ func NewRouter(routers ...Router) *mux.Router { // 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 { - {{#addResponseHeader}} + {{#addResponseHeaders}} wHeader := w.Header() if headers != nil { for key, values := range headers { @@ -69,10 +98,10 @@ func EncodeJSONResponse(i interface{}, status *int,{{#addResponseHeaders}} heade } } wHeader.Set("Content-Type", "application/json; charset=UTF-8") - {{/addResponseHeader}} - {{^addResponseHeader}} + {{/addResponseHeaders}} + {{^addResponseHeaders}} w.Header().Set("Content-Type", "application/json; charset=UTF-8") - {{/addResponseHeader}} + {{/addResponseHeaders}} if status != nil { w.WriteHeader(*status) } else { diff --git a/modules/openapi-generator/src/main/resources/go/client.mustache b/modules/openapi-generator/src/main/resources/go/client.mustache index 476a2081f88..572bd7f800c 100644 --- a/modules/openapi-generator/src/main/resources/go/client.mustache +++ b/modules/openapi-generator/src/main/resources/go/client.mustache @@ -9,6 +9,7 @@ import ( "errors" "fmt" "io" + "io/ioutil" "log" "mime/multipart" "net/http" @@ -419,6 +420,15 @@ func (c *APIClient) decode(v interface{}, b []byte, contentType string) (err err *s = string(b) return nil } + if f, ok := v.(**os.File); ok { + *f, err = ioutil.TempFile("", "HttpClientFile") + if err != nil { + return + } + _, err = (*f).Write(b) + _, err = (*f).Seek(0, io.SeekStart) + return + } if xmlCheck.MatchString(contentType) { if err = xml.Unmarshal(b, v); err != nil { return err diff --git a/modules/openapi-generator/src/main/resources/haskell-servant/API.mustache b/modules/openapi-generator/src/main/resources/haskell-servant/API.mustache index ab052a4f468..87e7c874aee 100644 --- a/modules/openapi-generator/src/main/resources/haskell-servant/API.mustache +++ b/modules/openapi-generator/src/main/resources/haskell-servant/API.mustache @@ -14,8 +14,8 @@ -fno-warn-unused-binds -fno-warn-unused-imports -freduction-depth=328 #-} module {{title}}.API - -- * Client and Server - ( Config(..) + ( -- * Client and Server + Config(..) , {{title}}Backend(..) , create{{title}}Client , run{{title}}Server 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 b1459f92a78..9ad7d579940 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.1.7 + 1.2.0 4.13 2.1.0-beta.124 1.4.0.Final diff --git a/modules/openapi-generator/src/main/resources/kotlin-client/README.mustache b/modules/openapi-generator/src/main/resources/kotlin-client/README.mustache index 110b828a0b9..546790a7fb6 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-client/README.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-client/README.mustache @@ -7,7 +7,7 @@ * Gradle 6.8.3 {{/jvm}} {{#multiplatform}} -* Kotlin 1.3.50 +* Kotlin 1.5.10 {{/multiplatform}} ## Build @@ -89,4 +89,4 @@ Authentication schemes defined for the API: {{/scopes}} {{/isOAuth}} -{{/authMethods}} \ No newline at end of file +{{/authMethods}} 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 1f58112db53..c5d0f13b5e1 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 @@ -7,18 +7,18 @@ wrapper { } buildscript { - ext.kotlin_version = '1.4.30' + ext.kotlin_version = '1.5.10' {{#jvm-retrofit2}} - ext.retrofitVersion = '2.7.2' + ext.retrofitVersion = '2.9.0' {{/jvm-retrofit2}} {{#useRxJava}} ext.rxJavaVersion = '1.3.8' {{/useRxJava}} {{#useRxJava2}} - ext.rxJava2Version = '2.2.20' + ext.rxJava2Version = '2.2.21' {{/useRxJava2}} {{#useRxJava3}} - ext.rxJava3Version = '3.0.10' + ext.rxJava3Version = '3.0.12' {{/useRxJava3}} repositories { @@ -52,67 +52,67 @@ test { } dependencies { - compile "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version" + implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version" {{#moshi}} {{^moshiCodeGen}} - compile "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version" - compile "com.squareup.moshi:moshi-kotlin:1.11.0" + implementation "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version" + implementation "com.squareup.moshi:moshi-kotlin:1.12.0" {{/moshiCodeGen}} {{#moshiCodeGen}} - compile "com.squareup.moshi:moshi:1.11.0" - kapt "com.squareup.moshi:moshi-kotlin-codegen:1.11.0" + implementation "com.squareup.moshi:moshi:1.12.0" + kapt "com.squareup.moshi:moshi-kotlin-codegen:1.12.0" {{/moshiCodeGen}} {{/moshi}} {{#gson}} - compile "com.google.code.gson:gson:2.8.6" + implementation "com.google.code.gson:gson:2.8.7" {{/gson}} {{#jackson}} - compile "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version" - compile "com.fasterxml.jackson.module:jackson-module-kotlin:2.12.1" - compile "com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.12.1" + implementation "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version" + implementation "com.fasterxml.jackson.module:jackson-module-kotlin:2.12.3" + implementation "com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.12.3" {{/jackson}} {{#kotlinx_serialization}} - compile "org.jetbrains.kotlinx:kotlinx-serialization-json:1.1.0" + implementation "org.jetbrains.kotlinx:kotlinx-serialization-json:1.2.1" {{/kotlinx_serialization}} {{#jvm-okhttp3}} - compile "com.squareup.okhttp3:okhttp:3.12.13" + implementation "com.squareup.okhttp3:okhttp:3.12.13" {{/jvm-okhttp3}} {{#jvm-okhttp4}} - compile "com.squareup.okhttp3:okhttp:4.9.0" + implementation "com.squareup.okhttp3:okhttp:4.9.1" {{/jvm-okhttp4}} {{#threetenbp}} - compile "org.threeten:threetenbp:1.5.0" + implementation "org.threeten:threetenbp:1.5.1" {{/threetenbp}} {{#jvm-retrofit2}} {{#hasOAuthMethods}} - compile "org.apache.oltu.oauth2:org.apache.oltu.oauth2.client:1.0.0" + implementation "org.apache.oltu.oauth2:org.apache.oltu.oauth2.client:1.0.2" {{/hasOAuthMethods}} - compile "com.squareup.okhttp3:logging-interceptor:4.9.0" + implementation "com.squareup.okhttp3:logging-interceptor:4.9.1" {{#useRxJava}} - compile "io.reactivex:rxjava:$rxJavaVersion" - compile "com.squareup.retrofit2:adapter-rxjava:$retrofitVersion" + implementation "io.reactivex:rxjava:$rxJavaVersion" + implementation "com.squareup.retrofit2:adapter-rxjava:$retrofitVersion" {{/useRxJava}} {{#useRxJava2}} - compile "io.reactivex.rxjava2:rxjava:$rxJava2Version" - compile "com.squareup.retrofit2:adapter-rxjava2:$retrofitVersion" + implementation "io.reactivex.rxjava2:rxjava:$rxJava2Version" + implementation "com.squareup.retrofit2:adapter-rxjava2:$retrofitVersion" {{/useRxJava2}} {{#useRxJava3}} - compile "io.reactivex.rxjava3:rxjava:$rxJava3Version" - compile "com.squareup.retrofit2:adapter-rxjava3:2.9.0" + implementation "io.reactivex.rxjava3:rxjava:$rxJava3Version" + implementation "com.squareup.retrofit2:adapter-rxjava3:2.9.0" {{/useRxJava3}} - compile "com.squareup.retrofit2:retrofit:$retrofitVersion" + implementation "com.squareup.retrofit2:retrofit:$retrofitVersion" {{#gson}} - compile "com.squareup.retrofit2:converter-gson:$retrofitVersion" + implementation "com.squareup.retrofit2:converter-gson:$retrofitVersion" {{/gson}} {{#moshi}} - compile "com.squareup.retrofit2:converter-moshi:$retrofitVersion" + implementation "com.squareup.retrofit2:converter-moshi:$retrofitVersion" {{/moshi}} {{#kotlinx_serialization}} - compile "com.jakewharton.retrofit:retrofit2-kotlinx-serialization-converter:0.8.0" + implementation "com.jakewharton.retrofit:retrofit2-kotlinx-serialization-converter:0.8.0" {{/kotlinx_serialization}} - compile "com.squareup.retrofit2:converter-scalars:$retrofitVersion" + implementation "com.squareup.retrofit2:converter-scalars:$retrofitVersion" {{/jvm-retrofit2}} - testCompile "io.kotlintest:kotlintest-runner-junit5:3.4.2" + testImplementation "io.kotlintest:kotlintest-runner-junit5:3.4.2" } {{#kotlinx_serialization}} 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 216df66eeac..093d3031839 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 @@ -29,7 +29,8 @@ import kotlinx.parcelize.Parcelize {{/multiplatform}} {{#multiplatform}} import kotlinx.serialization.* -import kotlinx.serialization.internal.CommonEnumSerializer +import kotlinx.serialization.descriptors.* +import kotlinx.serialization.encoding.* {{/multiplatform}} {{#serializableModel}} import java.io.Serializable @@ -44,7 +45,7 @@ import java.io.Serializable {{#parcelizeModels}} @Parcelize {{/parcelizeModels}} -{{#multiplatform}}@Serializable{{/multiplatform}}{{#kotlinx_serialization}}{{#serializableModel}}@KSerializable{{/serializableModel}}{{^serializableModel}}@Serializable{{/serializableModel}}{{/kotlinx_serialization}}{{#moshi}}{{#moshiCodeGen}}@JsonClass(generateAdapter = true){{/moshiCodeGen}}{{/moshi}}{{#jackson}}{{#discriminator}}{{>typeInfoAnnotation}}{{/discriminator}}{{/jackson}} +{{#multiplatform}}{{#discriminator}}{{/discriminator}}{{^discriminator}}@Serializable{{/discriminator}}{{/multiplatform}}{{#kotlinx_serialization}}{{#serializableModel}}@KSerializable{{/serializableModel}}{{^serializableModel}}@Serializable{{/serializableModel}}{{/kotlinx_serialization}}{{#moshi}}{{#moshiCodeGen}}@JsonClass(generateAdapter = true){{/moshiCodeGen}}{{/moshi}}{{#jackson}}{{#discriminator}}{{>typeInfoAnnotation}}{{/discriminator}}{{/jackson}} {{#isDeprecated}} @Deprecated(message = "This schema is deprecated.") {{/isDeprecated}} @@ -69,9 +70,14 @@ import java.io.Serializable * {{{description}}} * Values: {{#allowableValues}}{{#enumVars}}{{&name}}{{^-last}},{{/-last}}{{/enumVars}}{{/allowableValues}} */ + {{^multiplatform}} {{#kotlinx_serialization}} - @KSerializable + {{#serializableModel}}@KSerializable{{/serializableModel}}{{^serializableModel}}@Serializable{{/serializableModel}} {{/kotlinx_serialization}} + {{/multiplatform}} + {{#multiplatform}} + @Serializable + {{/multiplatform}} {{#nonPublicApi}}internal {{/nonPublicApi}}enum class {{{nameInCamelCase}}}(val value: {{^isContainer}}{{dataType}}{{/isContainer}}{{#isContainer}}kotlin.String{{/isContainer}}) { {{#allowableValues}} {{#enumVars}} @@ -90,7 +96,7 @@ import java.io.Serializable {{/kotlinx_serialization}} {{/multiplatform}} {{#multiplatform}} - {{&name}}({{{value}}}){{^-last}},{{/-last}}{{#-last}};{{/-last}} + @SerialName(value = {{^isString}}"{{/isString}}{{{value}}}{{^isString}}"{{/isString}}) {{&name}}({{{value}}}){{^-last}},{{/-last}}{{#-last}};{{/-last}} {{/multiplatform}} {{/enumVars}} {{/allowableValues}} diff --git a/modules/openapi-generator/src/main/resources/kotlin-client/data_class_opt_var.mustache b/modules/openapi-generator/src/main/resources/kotlin-client/data_class_opt_var.mustache index deae3ebd5dc..2ce65fd1d16 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-client/data_class_opt_var.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-client/data_class_opt_var.mustache @@ -18,4 +18,4 @@ {{#deprecated}} @Deprecated(message = "This property is deprecated.") {{/deprecated}} - {{#multiplatform}}@SerialName(value = "{{{vendorExtensions.x-base-name-literal}}}") {{/multiplatform}}{{#isInherited}}override {{/isInherited}}{{>modelMutable}} {{{name}}}: {{#isArray}}{{#isList}}kotlin.collections.List{{/isList}}{{^isList}}kotlin.Array{{/isList}}<{{^items.isEnum}}{{^items.isPrimitiveType}}{{^items.isModel}}{{#kotlinx_serialization}}@Contextual {{/kotlinx_serialization}}{{/items.isModel}}{{/items.isPrimitiveType}}{{{items.dataType}}}{{/items.isEnum}}{{#items.isEnum}}{{classname}}.{{{nameInCamelCase}}}{{/items.isEnum}}>{{/isArray}}{{^isEnum}}{{^isArray}}{{{dataType}}}{{/isArray}}{{/isEnum}}{{#isEnum}}{{^isArray}}{{classname}}.{{{nameInCamelCase}}}{{/isArray}}{{/isEnum}}? = {{#defaultvalue}}{{defaultvalue}}{{/defaultvalue}}{{^defaultvalue}}null{{/defaultvalue}} \ No newline at end of file + {{#multiplatform}}@SerialName(value = "{{{vendorExtensions.x-base-name-literal}}}") {{/multiplatform}}{{#isInherited}}override {{/isInherited}}{{>modelMutable}} {{{name}}}: {{#isArray}}{{#isList}}{{#uniqueItems}}kotlin.collections.Set{{/uniqueItems}}{{^uniqueItems}}kotlin.collections.List{{/uniqueItems}}{{/isList}}{{^isList}}kotlin.Array{{/isList}}<{{^items.isEnum}}{{^items.isPrimitiveType}}{{^items.isModel}}{{#kotlinx_serialization}}@Contextual {{/kotlinx_serialization}}{{/items.isModel}}{{/items.isPrimitiveType}}{{{items.dataType}}}{{/items.isEnum}}{{#items.isEnum}}{{classname}}.{{{nameInCamelCase}}}{{/items.isEnum}}>{{/isArray}}{{^isEnum}}{{^isArray}}{{{dataType}}}{{/isArray}}{{/isEnum}}{{#isEnum}}{{^isArray}}{{classname}}.{{{nameInCamelCase}}}{{/isArray}}{{/isEnum}}? = {{#defaultvalue}}{{defaultvalue}}{{/defaultvalue}}{{^defaultvalue}}null{{/defaultvalue}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/kotlin-client/data_class_req_var.mustache b/modules/openapi-generator/src/main/resources/kotlin-client/data_class_req_var.mustache index 2c44be195c8..d7a2fcf31bd 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-client/data_class_req_var.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-client/data_class_req_var.mustache @@ -18,4 +18,4 @@ {{#deprecated}} @Deprecated(message = "This property is deprecated.") {{/deprecated}} - {{#multiplatform}}@SerialName(value = "{{{vendorExtensions.x-base-name-literal}}}") @Required {{/multiplatform}}{{#isInherited}}override {{/isInherited}}{{>modelMutable}} {{{name}}}: {{#isArray}}{{#isList}}kotlin.collections.List{{/isList}}{{^isList}}kotlin.Array{{/isList}}<{{^items.isEnum}}{{^items.isPrimitiveType}}{{^items.isModel}}{{#kotlinx_serialization}}@Contextual {{/kotlinx_serialization}}{{/items.isModel}}{{/items.isPrimitiveType}}{{{items.dataType}}}{{/items.isEnum}}{{#items.isEnum}}{{classname}}.{{{nameInCamelCase}}}{{/items.isEnum}}>{{/isArray}}{{^isEnum}}{{^isArray}}{{{dataType}}}{{/isArray}}{{/isEnum}}{{#isEnum}}{{^isArray}}{{classname}}.{{{nameInCamelCase}}}{{/isArray}}{{/isEnum}}{{#isNullable}}?{{/isNullable}} \ No newline at end of file + {{#multiplatform}}@SerialName(value = "{{{vendorExtensions.x-base-name-literal}}}") @Required {{/multiplatform}}{{#isInherited}}override {{/isInherited}}{{>modelMutable}} {{{name}}}: {{#isArray}}{{#isList}}{{#isUniqueItems}}kotlin.collections.Set{{/isUniqueItems}}{{^isUniqueItems}}kotlin.collections.List{{/isUniqueItems}}{{/isList}}{{^isList}}kotlin.Array{{/isList}}<{{^items.isEnum}}{{^items.isPrimitiveType}}{{^items.isModel}}{{#kotlinx_serialization}}@Contextual {{/kotlinx_serialization}}{{/items.isModel}}{{/items.isPrimitiveType}}{{{items.dataType}}}{{/items.isEnum}}{{#items.isEnum}}{{classname}}.{{{nameInCamelCase}}}{{/items.isEnum}}>{{/isArray}}{{^isEnum}}{{^isArray}}{{{dataType}}}{{/isArray}}{{/isEnum}}{{#isEnum}}{{^isArray}}{{classname}}.{{{nameInCamelCase}}}{{/isArray}}{{/isEnum}}{{#isNullable}}?{{/isNullable}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/kotlin-client/enum_class.mustache b/modules/openapi-generator/src/main/resources/kotlin-client/enum_class.mustache index 88d6c278ea2..4a6a7acfa31 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-client/enum_class.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-client/enum_class.mustache @@ -15,14 +15,14 @@ import kotlinx.serialization.Serializable {{/multiplatform}} {{#multiplatform}} import kotlinx.serialization.* -import kotlinx.serialization.internal.CommonEnumSerializer {{/multiplatform}} /** * {{{description}}} * Values: {{#allowableValues}}{{#enumVars}}{{&name}}{{^-last}},{{/-last}}{{/enumVars}}{{/allowableValues}} */ -{{#multiplatform}}@Serializable(with = {{classname}}.Serializer::class){{/multiplatform}}{{#kotlinx_serialization}}@Serializable(with = {{classname}}.Serializer::class){{/kotlinx_serialization}} + +{{#multiplatform}}@Serializable{{/multiplatform}}{{#kotlinx_serialization}}@Serializable{{/kotlinx_serialization}} {{#nonPublicApi}}internal {{/nonPublicApi}}enum class {{classname}}(val value: {{{dataType}}}) { {{#allowableValues}}{{#enumVars}} @@ -40,6 +40,9 @@ import kotlinx.serialization.internal.CommonEnumSerializer @SerialName(value = {{^isString}}"{{/isString}}{{{value}}}{{^isString}}"{{/isString}}) {{/kotlinx_serialization}} {{/multiplatform}} + {{#multiplatform}} + @SerialName(value = {{^isString}}"{{/isString}}{{{value}}}{{^isString}}"{{/isString}}) + {{/multiplatform}} {{#isArray}} {{#isList}} {{&name}}(listOf({{{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 61677c22aff..ef1b0517e78 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 @@ -8,10 +8,10 @@ package {{packageName}}.infrastructure * NOTE: Headers is a Map because rfc2616 defines * multi-valued headers as csv-only. */ -{{#nonPublicApi}}internal {{/nonPublicApi}}data class RequestConfig( +{{#nonPublicApi}}internal {{/nonPublicApi}}data class RequestConfig( val method: RequestMethod, val path: String, val headers: MutableMap = mutableMapOf(), val query: MutableMap> = mutableMapOf(), - val body: kotlin.Any? = null + val body: T? = null ) \ No newline at end of file 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 beef3fc2bf3..31b83578e7e 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 @@ -60,6 +60,7 @@ import java.util.concurrent.atomic.AtomicLong .add(LocalDateAdapter()) .add(UUIDAdapter()) .add(ByteArrayAdapter()) + .add(URIAdapter()) {{^moshiCodeGen}} .add(KotlinJsonAdapterFactory()) {{/moshiCodeGen}} @@ -104,8 +105,8 @@ import java.util.concurrent.atomic.AtomicLong contextual(AtomicInteger::class, AtomicIntegerAdapter) contextual(AtomicLong::class, AtomicLongAdapter) contextual(AtomicBoolean::class, AtomicBooleanAdapter) - contextual(URI::class, UriAdapter) - contextual(URL::class, UrlAdapter) + contextual(URI::class, URIAdapter) + contextual(URL::class, URLAdapter) contextual(StringBuilder::class, StringBuilderAdapter) } diff --git a/modules/openapi-generator/src/main/resources/kotlin-client/jvm-common/infrastructure/URIAdapter.kt.mustache b/modules/openapi-generator/src/main/resources/kotlin-client/jvm-common/infrastructure/URIAdapter.kt.mustache index 0225ccf549b..c9582955553 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-client/jvm-common/infrastructure/URIAdapter.kt.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-client/jvm-common/infrastructure/URIAdapter.kt.mustache @@ -1,5 +1,6 @@ package {{packageName}}.infrastructure +{{#kotlinx_serialization}} import kotlinx.serialization.KSerializer import kotlinx.serialization.Serializer import kotlinx.serialization.encoding.Decoder @@ -7,10 +8,25 @@ import kotlinx.serialization.encoding.Encoder import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor import kotlinx.serialization.descriptors.PrimitiveKind import kotlinx.serialization.descriptors.SerialDescriptor +{{/kotlinx_serialization}} +{{#moshi}} +import com.squareup.moshi.FromJson +import com.squareup.moshi.ToJson +{{/moshi}} import java.net.URI +{{#moshi}} +{{#nonPublicApi}}internal {{/nonPublicApi}}class URIAdapter { + @ToJson + fun toJson(uri: URI) = uri.toString() + + @FromJson + fun fromJson(s: String): URI = URI.create(s) +} +{{/moshi}} +{{#kotlinx_serialization}} @Serializer(forClass = URI::class) -object UriAdapter : KSerializer { +object URIAdapter : KSerializer { override fun serialize(encoder: Encoder, value: URI) { encoder.encodeString(value.toASCIIString()) } @@ -18,4 +34,5 @@ object UriAdapter : KSerializer { override fun deserialize(decoder: Decoder): URI = URI(decoder.decodeString()) override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("URI", PrimitiveKind.STRING) -} \ No newline at end of file +} +{{/kotlinx_serialization}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/kotlin-client/jvm-common/infrastructure/URLAdapter.kt.mustache b/modules/openapi-generator/src/main/resources/kotlin-client/jvm-common/infrastructure/URLAdapter.kt.mustache index 7105c43b72b..eaebad52cc8 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-client/jvm-common/infrastructure/URLAdapter.kt.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-client/jvm-common/infrastructure/URLAdapter.kt.mustache @@ -10,7 +10,7 @@ import kotlinx.serialization.descriptors.SerialDescriptor import java.net.URL @Serializer(forClass = URL::class) -object UrlAdapter : KSerializer { +object URLAdapter : KSerializer { override fun serialize(encoder: Encoder, value: URL) { encoder.encodeString(value.toExternalForm()) } diff --git a/modules/openapi-generator/src/main/resources/kotlin-client/jvm-common/infrastructure/UUIDAdapter.kt.mustache b/modules/openapi-generator/src/main/resources/kotlin-client/jvm-common/infrastructure/UUIDAdapter.kt.mustache index 9781ff529cc..ea903c36ca9 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-client/jvm-common/infrastructure/UUIDAdapter.kt.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-client/jvm-common/infrastructure/UUIDAdapter.kt.mustache @@ -21,7 +21,7 @@ import java.util.UUID fun toJson(uuid: UUID) = uuid.toString() @FromJson - fun fromJson(s: String) = UUID.fromString(s) + fun fromJson(s: String): UUID = UUID.fromString(s) } {{/moshi}} {{#kotlinx_serialization}} 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 7745b52249a..dd97f0ae30f 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 @@ -41,9 +41,12 @@ import {{packageName}}.infrastructure.toMultiValue @Deprecated(message = "This operation is deprecated.") {{/isDeprecated}} {{^doNotUseRxAndCoroutines}}{{#useCoroutines}}suspend {{/useCoroutines}}{{/doNotUseRxAndCoroutines}}fun {{operationId}}({{#allParams}}{{{paramName}}}: {{{dataType}}}{{^required}}?{{/required}}{{^-last}}, {{/-last}}{{/allParams}}) : {{#returnType}}{{{returnType}}}{{#nullableReturnType}}?{{/nullableReturnType}}{{/returnType}}{{^returnType}}Unit{{/returnType}} { + {{#isDeprecated}} + @Suppress("DEPRECATION") + {{/isDeprecated}} val localVariableConfig = {{operationId}}RequestConfig({{#allParams}}{{{paramName}}} = {{{paramName}}}{{^-last}}, {{/-last}}{{/allParams}}) - val localVarResponse = request<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Any?{{/returnType}}>( + val localVarResponse = request<{{#hasBodyParam}}{{#bodyParams}}{{{dataType}}}{{/bodyParams}}{{/hasBodyParam}}{{^hasBodyParam}}{{^hasFormParams}}Unit{{/hasFormParams}}{{#hasFormParams}}Map{{/hasFormParams}}{{/hasBodyParam}}, {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Unit{{/returnType}}>( localVariableConfig ) @@ -71,8 +74,8 @@ import {{packageName}}.infrastructure.toMultiValue {{#isDeprecated}} @Deprecated(message = "This operation is deprecated.") {{/isDeprecated}} - fun {{operationId}}RequestConfig({{#allParams}}{{{paramName}}}: {{{dataType}}}{{^required}}?{{/required}}{{^-last}}, {{/-last}}{{/allParams}}) : RequestConfig { - val localVariableBody: kotlin.Any? = {{#hasBodyParam}}{{#bodyParams}}{{{paramName}}}{{/bodyParams}}{{/hasBodyParam}}{{^hasBodyParam}}{{^hasFormParams}}null{{/hasFormParams}}{{#hasFormParams}}mapOf({{#formParams}}"{{{baseName}}}" to {{{paramName}}}{{^-last}}, {{/-last}}{{/formParams}}){{/hasFormParams}}{{/hasBodyParam}} + fun {{operationId}}RequestConfig({{#allParams}}{{{paramName}}}: {{{dataType}}}{{^required}}?{{/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 {{{paramName}}}{{^-last}}, {{/-last}}{{/formParams}}){{/hasFormParams}}{{/hasBodyParam}} val localVariableQuery: MultiValueMap = {{^hasQueryParams}}mutableMapOf() {{/hasQueryParams}}{{#hasQueryParams}}mutableMapOf>() .apply { @@ -99,16 +102,14 @@ import {{packageName}}.infrastructure.toMultiValue {{#headerParams}} {{{paramName}}}{{^required}}?{{/required}}.apply { localVariableHeaders["{{baseName}}"] = {{#isContainer}}this.joinToString(separator = collectionDelimiter("{{collectionFormat}}")){{/isContainer}}{{^isContainer}}this.toString(){{/isContainer}} } {{/headerParams}} - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.{{httpMethod}}, path = "{{path}}"{{#pathParams}}.replace("{"+"{{baseName}}"+"}", "${{{paramName}}}"){{/pathParams}}, query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } {{/operation}} 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 aa5a275a9f3..64ab00cf9b6 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 @@ -1,6 +1,13 @@ package {{packageName}}.infrastructure +{{#supportAndroidApiLevel25AndBelow}} +import android.os.Build +{{/supportAndroidApiLevel25AndBelow}} +{{#hasAuthMethods}} +{{#isBasicBasic}} import okhttp3.Credentials +{{/isBasicBasic}} +{{/hasAuthMethods}} import okhttp3.OkHttpClient import okhttp3.RequestBody {{#jvm-okhttp3}} @@ -24,12 +31,10 @@ import okhttp3.MediaType.Companion.toMediaTypeOrNull import okhttp3.Request import okhttp3.Headers import okhttp3.MultipartBody -import java.io.File import java.io.BufferedWriter +import java.io.File import java.io.FileWriter import java.net.URLConnection -import java.nio.file.Files -import java.util.Date {{^threetenbp}} import java.time.LocalDate import java.time.LocalDateTime @@ -37,6 +42,12 @@ import java.time.LocalTime import java.time.OffsetDateTime import java.time.OffsetTime {{/threetenbp}} +import java.util.Date +import java.util.Locale +{{#kotlinx_serialization}} +import kotlinx.serialization.decodeFromString +import kotlinx.serialization.encodeToString +{{/kotlinx_serialization}} {{#threetenbp}} import org.threeten.bp.LocalDate import org.threeten.bp.LocalDateTime @@ -84,14 +95,10 @@ import org.threeten.bp.OffsetTime protected inline fun requestBody(content: T, mediaType: String = JsonMediaType): RequestBody = when { {{#jvm-okhttp3}} - content is File -> RequestBody.create( - MediaType.parse(mediaType), content - ) + content is File -> RequestBody.create(MediaType.parse(mediaType), content) {{/jvm-okhttp3}} {{#jvm-okhttp4}} - content is File -> content.asRequestBody( - mediaType.toMediaTypeOrNull() - ) + content is File -> content.asRequestBody(mediaType.toMediaTypeOrNull()) {{/jvm-okhttp4}} mediaType == FormDataMediaType -> { MultipartBody.Builder() @@ -152,12 +159,12 @@ import org.threeten.bp.OffsetTime MediaType.parse(mediaType), Serializer.jacksonObjectMapper.writeValueAsString(content) {{/jackson}} {{#kotlinx_serialization}} - MediaType.parse(mediaType), Serializer.jvmJson.decodeFromString(content) + MediaType.parse(mediaType), Serializer.jvmJson.encodeToString(content) {{/kotlinx_serialization}} ) {{/jvm-okhttp3}} {{#jvm-okhttp4}} - mediaType == JsonMediaType -> {{#moshi}}Serializer.moshi.adapter(T::class.java).toJson(content){{/moshi}}{{#gson}}Serializer.gson.toJson(content, T::class.java){{/gson}}{{#jackson}}Serializer.jacksonObjectMapper.writeValueAsString(content){{/jackson}}{{#kotlinx_serialization}}Serializer.jvmJson.decodeFromString(content){{/kotlinx_serialization}}.toRequestBody( + mediaType == JsonMediaType -> {{#moshi}}Serializer.moshi.adapter(T::class.java).toJson(content){{/moshi}}{{#gson}}Serializer.gson.toJson(content, T::class.java){{/gson}}{{#jackson}}Serializer.jacksonObjectMapper.writeValueAsString(content){{/jackson}}{{#kotlinx_serialization}}Serializer.jvmJson.encodeToString(content){{/kotlinx_serialization}}.toRequestBody( mediaType.toMediaTypeOrNull() ) {{/jvm-okhttp4}} @@ -176,7 +183,17 @@ import org.threeten.bp.OffsetTime } if (T::class.java == File::class.java) { // return tempfile - val f = Files.createTempFile("tmp.{{packageName}}", null).toFile() + {{^supportAndroidApiLevel25AndBelow}} + val f = java.nio.file.Files.createTempFile("tmp.{{packageName}}", null).toFile() + {{/supportAndroidApiLevel25AndBelow}} + {{#supportAndroidApiLevel25AndBelow}} + val f = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { + java.nio.file.Files.createTempFile("tmp.net.medicineone.teleconsultationandroid.openapi.openapicommon", null).toFile() + } else { + @Suppress("DEPRECATION") + createTempFile("tmp.net.medicineone.teleconsultationandroid.openapi.openapicommon", null) + } + {{/supportAndroidApiLevel25AndBelow}} f.deleteOnExit() val out = BufferedWriter(FileWriter(f)) out.write(bodyContent) @@ -184,13 +201,13 @@ import org.threeten.bp.OffsetTime return f as T } return when(mediaType) { - JsonMediaType -> {{#moshi}}Serializer.moshi.adapter(T::class.java).fromJson(bodyContent){{/moshi}}{{#gson}}Serializer.gson.fromJson(bodyContent, T::class.java){{/gson}}{{#jackson}}Serializer.jacksonObjectMapper.readValue(bodyContent, T::class.java){{/jackson}} + JsonMediaType -> {{#moshi}}Serializer.moshi.adapter(T::class.java).fromJson(bodyContent){{/moshi}}{{#gson}}Serializer.gson.fromJson(bodyContent, T::class.java){{/gson}}{{#jackson}}Serializer.jacksonObjectMapper.readValue(bodyContent, T::class.java){{/jackson}}{{#kotlinx_serialization}}Serializer.jvmJson.decodeFromString(bodyContent){{/kotlinx_serialization}} else -> throw UnsupportedOperationException("responseBody currently only supports JSON body.") } } {{#hasAuthMethods}} - protected fun updateAuthParams(requestConfig: RequestConfig) { + protected fun updateAuthParams(requestConfig: RequestConfig) { {{#authMethods}} {{#isApiKey}} {{#isKeyInHeader}} @@ -247,7 +264,7 @@ import org.threeten.bp.OffsetTime } {{/hasAuthMethods}} - protected inline fun request(requestConfig: RequestConfig): ApiInfrastructureResponse { + protected inline fun request(requestConfig: RequestConfig): ApiInfrastructureResponse { {{#jvm-okhttp3}} val httpUrl = HttpUrl.parse(baseUrl) ?: throw IllegalStateException("baseUrl is invalid.") {{/jvm-okhttp3}} @@ -288,7 +305,7 @@ import org.threeten.bp.OffsetTime } // TODO: support multiple contentType options here. - val contentType = (headers[ContentType] as String).substringBefore(";").toLowerCase() + val contentType = (headers[ContentType] as String).substringBefore(";").lowercase(Locale.getDefault()) val request = when (requestConfig.method) { RequestMethod.DELETE -> Request.Builder().url(url).delete(requestBody(requestConfig.body, contentType)) @@ -303,57 +320,46 @@ import org.threeten.bp.OffsetTime }.build() val response = client.newCall(request).execute() - val accept = response.header(ContentType)?.substringBefore(";")?.toLowerCase() + val accept = response.header(ContentType)?.substringBefore(";")?.lowercase(Locale.getDefault()) // TODO: handle specific mapping types. e.g. Map> - when { - response.isRedirect -> return Redirection( - response.code{{#jvm-okhttp3}}(){{/jvm-okhttp3}}, - response.headers{{#jvm-okhttp3}}(){{/jvm-okhttp3}}.toMultimap() + return when { + response.isRedirect -> Redirection( + response.code{{#jvm-okhttp3}}(){{/jvm-okhttp3}}, + response.headers{{#jvm-okhttp3}}(){{/jvm-okhttp3}}.toMultimap() ) - response.isInformational -> return Informational( - response.message{{#jvm-okhttp3}}(){{/jvm-okhttp3}}, - response.code{{#jvm-okhttp3}}(){{/jvm-okhttp3}}, - response.headers{{#jvm-okhttp3}}(){{/jvm-okhttp3}}.toMultimap() + response.isInformational -> Informational( + response.message{{#jvm-okhttp3}}(){{/jvm-okhttp3}}, + response.code{{#jvm-okhttp3}}(){{/jvm-okhttp3}}, + response.headers{{#jvm-okhttp3}}(){{/jvm-okhttp3}}.toMultimap() ) - response.isSuccessful -> return Success( - responseBody(response.body{{#jvm-okhttp3}}(){{/jvm-okhttp3}}, accept), - response.code{{#jvm-okhttp3}}(){{/jvm-okhttp3}}, - response.headers{{#jvm-okhttp3}}(){{/jvm-okhttp3}}.toMultimap() + response.isSuccessful -> Success( + responseBody(response.body{{#jvm-okhttp3}}(){{/jvm-okhttp3}}, accept), + response.code{{#jvm-okhttp3}}(){{/jvm-okhttp3}}, + response.headers{{#jvm-okhttp3}}(){{/jvm-okhttp3}}.toMultimap() ) - response.isClientError -> return ClientError( - response.message{{#jvm-okhttp3}}(){{/jvm-okhttp3}}, - response.body{{#jvm-okhttp3}}(){{/jvm-okhttp3}}?.string(), - response.code{{#jvm-okhttp3}}(){{/jvm-okhttp3}}, - response.headers{{#jvm-okhttp3}}(){{/jvm-okhttp3}}.toMultimap() + response.isClientError -> ClientError( + response.message{{#jvm-okhttp3}}(){{/jvm-okhttp3}}, + response.body{{#jvm-okhttp3}}(){{/jvm-okhttp3}}?.string(), + response.code{{#jvm-okhttp3}}(){{/jvm-okhttp3}}, + response.headers{{#jvm-okhttp3}}(){{/jvm-okhttp3}}.toMultimap() ) - else -> return ServerError( - response.message{{#jvm-okhttp3}}(){{/jvm-okhttp3}}, - response.body{{#jvm-okhttp3}}(){{/jvm-okhttp3}}?.string(), - response.code{{#jvm-okhttp3}}(){{/jvm-okhttp3}}, - response.headers{{#jvm-okhttp3}}(){{/jvm-okhttp3}}.toMultimap() + else -> ServerError( + response.message{{#jvm-okhttp3}}(){{/jvm-okhttp3}}, + response.body{{#jvm-okhttp3}}(){{/jvm-okhttp3}}?.string(), + response.code{{#jvm-okhttp3}}(){{/jvm-okhttp3}}, + response.headers{{#jvm-okhttp3}}(){{/jvm-okhttp3}}.toMultimap() ) } } - protected fun parameterToString(value: Any?): String { - when (value) { - null -> { - return "" - } - is Array<*> -> { - return toMultiValue(value, "csv").toString() - } - is Iterable<*> -> { - return toMultiValue(value, "csv").toString() - } - is OffsetDateTime, is OffsetTime, is LocalDateTime, is LocalDate, is LocalTime, is Date -> { - return parseDateToQueryString(value) - } - else -> { - return value.toString() - } - } + 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, is Date -> + parseDateToQueryString(value) + else -> value.toString() } protected inline fun parseDateToQueryString(value : T): String { diff --git a/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-okhttp/infrastructure/ApplicationDelegates.kt.mustache b/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-okhttp/infrastructure/ApplicationDelegates.kt.mustache deleted file mode 100644 index 63112263176..00000000000 --- a/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-okhttp/infrastructure/ApplicationDelegates.kt.mustache +++ /dev/null @@ -1,29 +0,0 @@ -package {{packageName}}.infrastructure - -import kotlin.properties.ReadWriteProperty -import kotlin.reflect.KProperty - -{{#nonPublicApi}}internal {{/nonPublicApi}}object ApplicationDelegates { - /** - * Provides a property delegate, allowing the property to be set once and only once. - * - * If unset (no default value), a get on the property will throw [IllegalStateException]. - */ - fun setOnce(defaultValue: T? = null) : ReadWriteProperty = SetOnce(defaultValue) - - private class SetOnce(defaultValue: T? = null) : ReadWriteProperty { - private var isSet = false - private var value: T? = defaultValue - - override fun getValue(thisRef: Any?, property: KProperty<*>): T { - return value ?: throw IllegalStateException("${property.name} not initialized") - } - - override fun setValue(thisRef: Any?, property: KProperty<*>, value: T) = synchronized(this) { - if (!isSet) { - this.value = value - isSet = true - } - } - } -} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-retrofit2/auth/OAuthOkHttpClient.kt.mustache b/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-retrofit2/auth/OAuthOkHttpClient.kt.mustache index 106b0581994..5c30002e94b 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-retrofit2/auth/OAuthOkHttpClient.kt.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-retrofit2/auth/OAuthOkHttpClient.kt.mustache @@ -13,14 +13,13 @@ 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 + private var client: OkHttpClient = OkHttpClient() ) : HttpClient { - constructor() : this(OkHttpClient()) - @Throws(OAuthSystemException::class, OAuthProblemException::class) override fun execute( request: OAuthClientRequest, @@ -39,7 +38,7 @@ class OAuthOkHttpClient( } } - val body: RequestBody? = if (request.body != null) RequestBody.create(mediaType, request.body) else null + val body: RequestBody? = if (request.body != null) request.body.toRequestBody(mediaType) else null requestBuilder.method(requestMethod, body) try { @@ -48,6 +47,7 @@ class OAuthOkHttpClient( response.body?.string(), response.body?.contentType()?.toString(), response.code, + response.headers.toMultimap(), responseClass) } catch (e: IOException) { throw OAuthSystemException(e) diff --git a/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-retrofit2/headerParams.mustache b/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-retrofit2/headerParams.mustache index aa5a8e34673..f546244307b 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-retrofit2/headerParams.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-retrofit2/headerParams.mustache @@ -1 +1 @@ -{{#isHeaderParam}}@Header("{{baseName}}") {{{paramName}}}: {{{dataType}}}{{/isHeaderParam}} \ No newline at end of file +{{#isHeaderParam}}@Header("{{baseName}}") {{{paramName}}}: {{{dataType}}}{{#required}}{{#defaultValue}} = {{{defaultValue}}}{{/defaultValue}}{{/required}}{{^required}}?{{#defaultValue}} = {{{defaultValue}}}{{/defaultValue}}{{^defaultValue}} = null{{/defaultValue}}{{/required}}{{/isHeaderParam}} \ No newline at end of file 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 ea19748fbfb..2d64978b0c2 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 @@ -21,6 +21,7 @@ import {{packageName}}.auth.HttpBearerAuth {{/authMethods}} {{/hasAuthMethods}} +import okhttp3.Call import okhttp3.Interceptor import okhttp3.OkHttpClient import retrofit2.Retrofit @@ -56,7 +57,7 @@ import okhttp3.MediaType.Companion.toMediaType private var baseUrl: String = defaultBasePath, private val okHttpClientBuilder: OkHttpClient.Builder? = null{{^kotlinx_serialization}}, private val serializerBuilder: {{#gson}}Gson{{/gson}}{{#moshi}}Moshi.{{/moshi}}Builder = Serializer.{{#gson}}gson{{/gson}}{{#moshi}}moshi{{/moshi}}Builder{{/kotlinx_serialization}}, - private val okHttpClient : OkHttpClient? = null, + private val callFactory : Call.Factory? = null, private val converterFactory: Converter.Factory? = null, ) { private val apiAuthorizations = mutableMapOf() @@ -303,8 +304,8 @@ import okhttp3.MediaType.Companion.toMediaType } fun createService(serviceClass: Class): S { - val usedClient = this.okHttpClient ?: clientBuilder.build() - return retrofitBuilder.client(usedClient).build().create(serviceClass) + val usedCallFactory = this.callFactory ?: clientBuilder.build() + return retrofitBuilder.callFactory(usedCallFactory).build().create(serviceClass) } private fun normalizeBaseUrl() { diff --git a/modules/openapi-generator/src/main/resources/kotlin-client/libraries/multiplatform/api.mustache b/modules/openapi-generator/src/main/resources/kotlin-client/libraries/multiplatform/api.mustache index e51da4590b8..232dda06db3 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-client/libraries/multiplatform/api.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-client/libraries/multiplatform/api.mustache @@ -6,28 +6,20 @@ package {{apiPackage}} import {{packageName}}.infrastructure.* import io.ktor.client.request.forms.formData -import kotlinx.serialization.UnstableDefault import io.ktor.client.engine.HttpClientEngine import io.ktor.client.features.json.serializer.KotlinxSerializer import kotlinx.serialization.json.Json -import kotlinx.serialization.json.JsonConfiguration import io.ktor.http.ParametersBuilder import kotlinx.serialization.* -import kotlinx.serialization.internal.StringDescriptor +import kotlinx.serialization.descriptors.* +import kotlinx.serialization.encoding.* {{#operations}} -{{#nonPublicApi}}internal {{/nonPublicApi}}class {{classname}} @UseExperimental(UnstableDefault::class) constructor( - baseUrl: kotlin.String = "{{{basePath}}}", +{{#nonPublicApi}}internal {{/nonPublicApi}}class {{classname}}( + baseUrl: String = ApiClient.BASE_URL, httpClientEngine: HttpClientEngine? = null, - serializer: KotlinxSerializer -) : ApiClient(baseUrl, httpClientEngine, serializer) { - - @UseExperimental(UnstableDefault::class) - constructor( - baseUrl: kotlin.String = "{{{basePath}}}", - httpClientEngine: HttpClientEngine? = null, - jsonConfiguration: JsonConfiguration = JsonConfiguration.Default - ) : this(baseUrl, httpClientEngine, KotlinxSerializer(Json(jsonConfiguration))) + jsonSerializer: Json = ApiClient.JSON_DEFAULT +) : ApiClient(baseUrl, httpClientEngine, jsonSerializer) { {{#operation}} /** @@ -76,7 +68,7 @@ import kotlinx.serialization.internal.StringDescriptor {{{paramName}}}?.apply { localVariableHeaders["{{baseName}}"] = {{#isContainer}}this.joinToString(separator = collectionDelimiter("{{collectionFormat}}")){{/isContainer}}{{^isContainer}}this.toString(){{/isContainer}} } {{/headerParams}} - val localVariableConfig = RequestConfig( + val localVariableConfig = RequestConfig( RequestMethod.{{httpMethod}}, "{{path}}"{{#pathParams}}.replace("{" + "{{baseName}}" + "}", "${{{paramName}}}"){{/pathParams}}, query = localVariableQuery, @@ -103,23 +95,5 @@ import kotlinx.serialization.internal.StringDescriptor {{/isMap}} {{/operation}} - - {{#nonPublicApi}}internal {{/nonPublicApi}}companion object { - internal fun setMappers(serializer: KotlinxSerializer) { - {{#operation}} - {{#hasBodyParam}} - {{#bodyParam}} - {{#isArray}}serializer.setMapper({{operationIdCamelCase}}Request::class, {{operationIdCamelCase}}Request.serializer()){{/isArray}}{{#isMap}}serializer.setMapper({{operationIdCamelCase}}Request::class, {{operationIdCamelCase}}Request.serializer()){{/isMap}} - {{/bodyParam}} - {{/hasBodyParam}} - {{#isArray}} - serializer.setMapper({{operationIdCamelCase}}Response::class, {{operationIdCamelCase}}Response.serializer()) - {{/isArray}} - {{#isMap}} - serializer.setMapper({{operationIdCamelCase}}Response::class, {{operationIdCamelCase}}Response.serializer()) - {{/isMap}} - {{/operation}} - } - } } {{/operations}} 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 new file mode 100644 index 00000000000..c6fb465777f --- /dev/null +++ b/modules/openapi-generator/src/main/resources/kotlin-client/libraries/multiplatform/build.gradle.kts.mustache @@ -0,0 +1,95 @@ +import org.jetbrains.kotlin.gradle.plugin.mpp.KotlinNativeTarget + +plugins { + kotlin("multiplatform") version "1.5.10" // kotlin_version + kotlin("plugin.serialization") version "1.5.10" // kotlin_version +} + +group = "{{groupId}}" +version = "{{artifactVersion}}" + +val kotlin_version = "1.5.10" +val coroutines_version = "1.5.0" +val serialization_version = "1.2.1" +val ktor_version = "1.6.0" + +repositories { + mavenCentral() +} + +kotlin { + jvm() + ios { binaries { framework { freeCompilerArgs += "-Xobjc-generics" } } } + js { + browser() + nodejs() + } + + sourceSets { + val commonMain by getting { + 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-json:$ktor_version") + api("io.ktor:ktor-client-serialization:$ktor_version") + } + } + + val commonTest by getting { + dependencies { + implementation(kotlin("test")) + implementation("io.ktor:ktor-client-mock:$ktor_version") + } + } + + val jvmMain by getting { + dependencies { + implementation(kotlin("stdlib-jdk7")) + } + } + + val jvmTest by getting { + dependencies { + implementation(kotlin("test-junit")) + } + } + + val iosMain by getting { + dependencies { + api("io.ktor:ktor-client-ios:$ktor_version") + } + } + + val iosTest by getting + + val jsMain by getting { + dependencies { + api("io.ktor:ktor-client-js:$ktor_version") + } + } + + val jsTest by getting + + all { + languageSettings.apply { + useExperimentalAnnotation("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) + } + } + } +} diff --git a/modules/openapi-generator/src/main/resources/kotlin-client/libraries/multiplatform/build.gradle.mustache b/modules/openapi-generator/src/main/resources/kotlin-client/libraries/multiplatform/build.gradle.mustache deleted file mode 100644 index dfc6736dc6d..00000000000 --- a/modules/openapi-generator/src/main/resources/kotlin-client/libraries/multiplatform/build.gradle.mustache +++ /dev/null @@ -1,161 +0,0 @@ -apply plugin: 'kotlin-multiplatform' -apply plugin: 'kotlinx-serialization' - -group '{{groupId}}' -version '{{artifactVersion}}' - -ext { - kotlin_version = '1.3.50' - kotlinx_version = '1.1.0' - coroutines_version = '1.3.1' - serialization_version = '0.12.0' - ktor_version = '1.2.4' -} - -buildscript { - repositories { - jcenter() - } - dependencies { - classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.3.50" // $kotlin_version - classpath "org.jetbrains.kotlin:kotlin-serialization:1.3.50" // $kotlin_version - } -} - -repositories { - jcenter() -} - -kotlin { - jvm() - iosArm64() { binaries { framework { freeCompilerArgs.add("-Xobjc-generics") } } } - iosX64() { binaries { framework { freeCompilerArgs.add("-Xobjc-generics") } } } - js() - - sourceSets { - commonMain { - dependencies { - implementation "org.jetbrains.kotlin:kotlin-stdlib-common:$kotlin_version" - implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core-common:$coroutines_version" - implementation "org.jetbrains.kotlinx:kotlinx-serialization-runtime-common:$serialization_version" - api "io.ktor:ktor-client-core:$ktor_version" - api "io.ktor:ktor-client-json:$ktor_version" - api "io.ktor:ktor-client-serialization:$ktor_version" - } - } - - commonTest { - dependencies { - implementation "org.jetbrains.kotlin:kotlin-test-common" - implementation "org.jetbrains.kotlin:kotlin-test-annotations-common" - implementation "io.ktor:ktor-client-mock:$ktor_version" - } - } - - jvmMain { - dependsOn commonMain - dependencies { - implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version" - implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:$coroutines_version" - implementation "org.jetbrains.kotlinx:kotlinx-serialization-runtime:$serialization_version" - api "io.ktor:ktor-client-core-jvm:$ktor_version" - api "io.ktor:ktor-client-json-jvm:$ktor_version" - api "io.ktor:ktor-client-serialization-jvm:$ktor_version" - } - } - - jvmTest { - dependsOn commonTest - dependencies { - implementation "org.jetbrains.kotlin:kotlin-test" - implementation "org.jetbrains.kotlin:kotlin-test-junit" - implementation "io.ktor:ktor-client-mock-jvm:$ktor_version" - } - } - - iosMain { - dependsOn commonMain - dependencies { - implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core-native:$coroutines_version" - implementation "org.jetbrains.kotlinx:kotlinx-serialization-runtime-native:$serialization_version" - api "io.ktor:ktor-client-ios:$ktor_version" - } - } - - iosTest { - dependsOn commonTest - dependencies { - implementation "io.ktor:ktor-client-mock-native:$ktor_version" - } - } - - iosArm64().compilations.main.defaultSourceSet { - dependsOn iosMain - dependencies { - api "io.ktor:ktor-client-ios-iosarm64:$ktor_version" - api "io.ktor:ktor-client-json-iosarm64:$ktor_version" - api "io.ktor:ktor-client-serialization-iosarm64:$ktor_version" - } - } - - iosArm64().compilations.test.defaultSourceSet { - dependsOn iosTest - } - - iosX64().compilations.main.defaultSourceSet { - dependsOn iosMain - dependencies { - api "io.ktor:ktor-client-ios-iosx64:$ktor_version" - api "io.ktor:ktor-client-json-iosx64:$ktor_version" - api "io.ktor:ktor-client-serialization-iosx64:$ktor_version" - } - } - - jsMain { - dependsOn commonMain - dependencies { - implementation "org.jetbrains.kotlin:kotlin-stdlib-js:$kotlin_version" - implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core-js:$coroutines_version" - implementation "org.jetbrains.kotlinx:kotlinx-serialization-runtime-js:$serialization_version" - api "io.ktor:ktor-client-js:$ktor_version" - api "io.ktor:ktor-client-json-js:$ktor_version" - api "io.ktor:ktor-client-serialization-js:$ktor_version" - } - } - - jsTest { - dependsOn commonTest - dependencies { - implementation "io.ktor:ktor-client-mock-js:$ktor_version" - implementation "io.ktor:ktor-client-js:$ktor_version" - implementation "io.ktor:ktor-client-json:$ktor_version" - implementation "io.ktor:ktor-client-serialization-js:$ktor_version" - } - } - - iosX64().compilations.test.defaultSourceSet { - dependsOn iosTest - } - - all { - languageSettings { - useExperimentalAnnotation('kotlin.Experimental') - } - } - } -} - -task iosTest { - def device = project.findProperty("device")?.toString() ?: "iPhone 8" - dependsOn 'linkDebugTestIosX64' - group = JavaBasePlugin.VERIFICATION_GROUP - description = "Execute unit tests on ${device} simulator" - doLast { - def binary = kotlin.targets.iosX64.binaries.getTest('DEBUG') - exec { commandLine 'xcrun', 'simctl', 'spawn', device, binary.outputFile } - } -} - -configurations { // workaround for https://youtrack.jetbrains.com/issue/KT-27170 - compileClasspath -} 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 91185a97a56..27b6162f121 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 @@ -2,24 +2,21 @@ package {{packageName}}.infrastructure import io.ktor.client.HttpClient import io.ktor.client.HttpClientConfig -import io.ktor.client.call.call import io.ktor.client.engine.HttpClientEngine import io.ktor.client.features.json.JsonFeature import io.ktor.client.features.json.JsonSerializer import io.ktor.client.features.json.serializer.KotlinxSerializer -import io.ktor.client.request.accept +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.response.HttpResponse +import io.ktor.client.statement.HttpResponse import io.ktor.client.utils.EmptyContent import io.ktor.http.* import io.ktor.http.content.OutgoingContent import io.ktor.http.content.PartData -import kotlinx.serialization.UnstableDefault import kotlinx.serialization.json.Json -import kotlinx.serialization.json.JsonConfiguration import {{apiPackage}}.* import {{modelPackage}}.* @@ -28,17 +25,11 @@ import {{packageName}}.auth.* {{#nonPublicApi}}internal {{/nonPublicApi}}open class ApiClient( private val baseUrl: String, httpClientEngine: HttpClientEngine?, - serializer: KotlinxSerializer) { - - @UseExperimental(UnstableDefault::class) - constructor( - baseUrl: String, - httpClientEngine: HttpClientEngine?, - jsonConfiguration: JsonConfiguration) : - this(baseUrl, httpClientEngine, KotlinxSerializer(Json(jsonConfiguration))) + private val json: Json +) { private val serializer: JsonSerializer by lazy { - serializer.apply { setMappers(this) }.ignoreOutgoingContent() + KotlinxSerializer(json).ignoreOutgoingContent() } private val client: HttpClient by lazy { @@ -60,16 +51,9 @@ import {{packageName}}.auth.* {{/hasAuthMethods}} {{#nonPublicApi}}internal {{/nonPublicApi}}companion object { + const val BASE_URL = "{{{basePath}}}" + val JSON_DEFAULT = Json { ignoreUnknownKeys = true } protected val UNSAFE_HEADERS = listOf(HttpHeaders.ContentType) - - private fun setMappers(serializer: KotlinxSerializer) { - {{#apiInfo}}{{#apis}} - {{classname}}.setMappers(serializer) - {{/apis}}{{/apiInfo}} - {{#models}} - {{#model}}{{^isAlias}}serializer.setMapper({{modelPackage}}.{{classname}}::class, {{modelPackage}}.{{classname}}.{{#isEnum}}Serializer{{/isEnum}}{{^isEnum}}serializer(){{/isEnum}}){{/isAlias}}{{/model}} - {{/models}} - } } /** @@ -140,26 +124,26 @@ import {{packageName}}.auth.* auth.bearerToken = bearerToken } - protected suspend fun multipartFormRequest(requestConfig: RequestConfig, body: kotlin.collections.List?, authNames: kotlin.collections.List): HttpResponse { + 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 { + 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 { + protected suspend fun jsonRequest(requestConfig: RequestConfig, body: Any? = null, authNames: kotlin.collections.List): HttpResponse { val contentType = (requestConfig.headers[HttpHeaders.ContentType]?.let { ContentType.parse(it) } ?: ContentType.Application.Json) return if (body != null) request(requestConfig, serializer.write(body, contentType), authNames) else request(requestConfig, authNames = authNames) } - protected suspend fun request(requestConfig: RequestConfig, body: OutgoingContent = EmptyContent, authNames: kotlin.collections.List): HttpResponse { - requestConfig.updateForAuth(authNames) + protected suspend fun request(requestConfig: RequestConfig, body: OutgoingContent = EmptyContent, authNames: kotlin.collections.List): HttpResponse { + requestConfig.updateForAuth(authNames) val headers = requestConfig.headers - return client.call { + return client.request { this.url { this.takeFrom(URLBuilder(baseUrl)) appendPath(requestConfig.path.trimStart('/').split('/')) @@ -174,10 +158,10 @@ import {{packageName}}.auth.* if (requestConfig.method in listOf(RequestMethod.PUT, RequestMethod.POST, RequestMethod.PATCH)) this.body = body - }.response + } } - private fun RequestConfig.updateForAuth(authNames: kotlin.collections.List) { + 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) 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 168cfc993c3..c3122bd2a59 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 @@ -1,13 +1,14 @@ package {{packageName}}.infrastructure import kotlinx.serialization.* -import kotlinx.serialization.internal.StringDescriptor +import kotlinx.serialization.descriptors.* +import kotlinx.serialization.encoding.* @Serializable class Base64ByteArray(val value: ByteArray) { @Serializer(Base64ByteArray::class) companion object : KSerializer { - override val descriptor = StringDescriptor.withName("Base64ByteArray") + 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()) } 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 b85013e647b..e882220ade6 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 @@ -1,6 +1,6 @@ package {{packageName}}.infrastructure -import kotlinx.io.core.* +import io.ktor.utils.io.core.* import kotlin.experimental.and private val digits = "0123456789abcdef".toCharArray() @@ -32,7 +32,7 @@ internal fun hex(bytes: ByteArray): String { result[resultIndex++] = digits[b and 0x0f] } - return String(result) + return result.concatToString() } /** diff --git a/modules/openapi-generator/src/main/resources/kotlin-client/libraries/multiplatform/infrastructure/HttpResponse.kt.mustache b/modules/openapi-generator/src/main/resources/kotlin-client/libraries/multiplatform/infrastructure/HttpResponse.kt.mustache index 87f27a5cf56..12d26567461 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-client/libraries/multiplatform/infrastructure/HttpResponse.kt.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-client/libraries/multiplatform/infrastructure/HttpResponse.kt.mustache @@ -5,7 +5,7 @@ import io.ktor.client.call.typeInfo import io.ktor.http.Headers import io.ktor.http.isSuccess -{{#nonPublicApi}}internal {{/nonPublicApi}}open class HttpResponse(val response: io.ktor.client.response.HttpResponse, val provider: BodyProvider) { +{{#nonPublicApi}}internal {{/nonPublicApi}}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() @@ -22,29 +22,29 @@ import io.ktor.http.isSuccess } {{#nonPublicApi}}internal {{/nonPublicApi}}interface BodyProvider { - suspend fun body(response: io.ktor.client.response.HttpResponse): T - suspend fun typedBody(response: io.ktor.client.response.HttpResponse, type: TypeInfo): V + suspend fun body(response: io.ktor.client.statement.HttpResponse): T + suspend fun typedBody(response: io.ktor.client.statement.HttpResponse, type: TypeInfo): V } {{#nonPublicApi}}internal {{/nonPublicApi}}class TypedBodyProvider(private val type: TypeInfo) : BodyProvider { @Suppress("UNCHECKED_CAST") - override suspend fun body(response: io.ktor.client.response.HttpResponse): T = + override suspend fun body(response: io.ktor.client.statement.HttpResponse): T = response.call.receive(type) as T @Suppress("UNCHECKED_CAST") - override suspend fun typedBody(response: io.ktor.client.response.HttpResponse, type: TypeInfo): V = + override suspend fun typedBody(response: io.ktor.client.statement.HttpResponse, type: TypeInfo): V = response.call.receive(type) as V } {{#nonPublicApi}}internal {{/nonPublicApi}}class MappedBodyProvider(private val provider: BodyProvider, private val block: S.() -> T) : BodyProvider { - override suspend fun body(response: io.ktor.client.response.HttpResponse): T = + override suspend fun body(response: io.ktor.client.statement.HttpResponse): T = block(provider.body(response)) - override suspend fun typedBody(response: io.ktor.client.response.HttpResponse, type: TypeInfo): V = + override suspend fun typedBody(response: io.ktor.client.statement.HttpResponse, type: TypeInfo): V = provider.typedBody(response, type) } -{{#nonPublicApi}}internal {{/nonPublicApi}}inline fun io.ktor.client.response.HttpResponse.wrap(): HttpResponse = +{{#nonPublicApi}}internal {{/nonPublicApi}}inline fun io.ktor.client.statement.HttpResponse.wrap(): HttpResponse = HttpResponse(this, TypedBodyProvider(typeInfo())) {{#nonPublicApi}}internal {{/nonPublicApi}}fun HttpResponse.map(block: T.() -> V): HttpResponse = 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 c23ac3ec000..d77a0bcbb48 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 @@ -1,13 +1,14 @@ package {{packageName}}.infrastructure import kotlinx.serialization.* -import kotlinx.serialization.internal.StringDescriptor +import kotlinx.serialization.descriptors.* +import kotlinx.serialization.encoding.* @Serializable class OctetByteArray(val value: ByteArray) { @Serializer(OctetByteArray::class) companion object : KSerializer { - override val descriptor = StringDescriptor.withName("OctetByteArray") + 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())) } 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 a44a242cbd2..f3b0464445e 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 @@ -2,9 +2,9 @@ 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> = {{#bodyParam}}{{baseType}}{{/bodyParam}}.serializer().list - override val descriptor = StringDescriptor.withName("{{operationIdCamelCase}}Request") - override fun serialize(encoder: Encoder, obj: {{operationIdCamelCase}}Request) = serializer.serialize(encoder, obj.value) - override fun deserialize(decoder: Decoder) = {{operationIdCamelCase}}Request(serializer.deserialize(decoder)) + private val serializer: KSerializer> = serializer>() + override val descriptor = serializer.descriptor + override fun serialize(encoder: Encoder, obj: {{operationIdCamelCase}}Request) = serializer.serialize(encoder, obj.value) + override fun deserialize(decoder: Decoder) = {{operationIdCamelCase}}Request(serializer.deserialize(decoder)) } } \ No newline at end of file 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 5dc6864aae8..a287882728d 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 @@ -2,9 +2,9 @@ private class {{operationIdCamelCase}}Request(val value: Map) { @Serializer({{operationIdCamelCase}}Request::class) {{#nonPublicApi}}internal {{/nonPublicApi}}companion object : KSerializer<{{operationIdCamelCase}}Request> { - private val serializer: KSerializer> = (kotlin.String.serializer() to {{#bodyParam}}{{baseType}}{{/bodyParam}}.serializer()).map - override val descriptor = StringDescriptor.withName("{{operationIdCamelCase}}Request") - override fun serialize(encoder: Encoder, obj: {{operationIdCamelCase}}Request) = serializer.serialize(encoder, obj.value) - override fun deserialize(decoder: Decoder) = {{operationIdCamelCase}}Request(serializer.deserialize(decoder)) + private val serializer: KSerializer> = serializer>() + override val descriptor = serializer.descriptor + override fun serialize(encoder: Encoder, obj: {{operationIdCamelCase}}Request) = serializer.serialize(encoder, obj.value) + override fun deserialize(decoder: Decoder) = {{operationIdCamelCase}}Request(serializer.deserialize(decoder)) } } \ No newline at end of file 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 a4e70a219ca..227d6a351f2 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 @@ -2,9 +2,9 @@ private class {{operationIdCamelCase}}Response(val value: List<{{returnBaseType}}>) { @Serializer({{operationIdCamelCase}}Response::class) {{#nonPublicApi}}internal {{/nonPublicApi}}companion object : KSerializer<{{operationIdCamelCase}}Response> { - private val serializer: KSerializer> = {{returnBaseType}}.serializer().list - override val descriptor = StringDescriptor.withName("{{operationIdCamelCase}}Response") - override fun serialize(encoder: Encoder, obj: {{operationIdCamelCase}}Response) = serializer.serialize(encoder, obj.value) - override fun deserialize(decoder: Decoder) = {{operationIdCamelCase}}Response(serializer.deserialize(decoder)) + private val serializer: KSerializer> = serializer>() + override val descriptor = serializer.descriptor + override fun serialize(encoder: Encoder, obj: {{operationIdCamelCase}}Response) = serializer.serialize(encoder, obj.value) + override fun deserialize(decoder: Decoder) = {{operationIdCamelCase}}Response(serializer.deserialize(decoder)) } } \ No newline at end of file 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 8253dc1f1a1..a6bdd6c166a 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 @@ -2,9 +2,9 @@ private class {{operationIdCamelCase}}Response(val value: Map) { @Serializer({{operationIdCamelCase}}Response::class) {{#nonPublicApi}}internal {{/nonPublicApi}}companion object : KSerializer<{{operationIdCamelCase}}Response> { - private val serializer: KSerializer> = (kotlin.String.serializer() to {{returnBaseType}}.serializer()).map - override val descriptor = StringDescriptor.withName("{{operationIdCamelCase}}Response") - override fun serialize(encoder: Encoder, obj: {{operationIdCamelCase}}Response) = serializer.serialize(encoder, obj.value) - override fun deserialize(decoder: Decoder) = {{operationIdCamelCase}}Response(serializer.deserialize(decoder)) + private val serializer: KSerializer> = serializer>() + override val descriptor = serializer.descriptor + override fun serialize(encoder: Encoder, obj: {{operationIdCamelCase}}Response) = serializer.serialize(encoder, obj.value) + override fun deserialize(decoder: Decoder) = {{operationIdCamelCase}}Response(serializer.deserialize(decoder)) } } \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/kotlin-client/libraries/multiplatform/settings.gradle.kts.mustache b/modules/openapi-generator/src/main/resources/kotlin-client/libraries/multiplatform/settings.gradle.kts.mustache new file mode 100644 index 00000000000..bf286c5e8c2 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/kotlin-client/libraries/multiplatform/settings.gradle.kts.mustache @@ -0,0 +1,2 @@ +enableFeaturePreview("GRADLE_METADATA") +rootProject.name = "{{artifactId}}" \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/kotlin-server/libraries/ktor/AppMain.kt.mustache b/modules/openapi-generator/src/main/resources/kotlin-server/libraries/ktor/AppMain.kt.mustache index 1556c44ae58..1dc57ad3b38 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-server/libraries/ktor/AppMain.kt.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-server/libraries/ktor/AppMain.kt.mustache @@ -1,61 +1,47 @@ package {{packageName}} +{{#featureMetrics}} import com.codahale.metrics.Slf4jReporter +{{/featureMetrics}} +import io.ktor.application.* +import io.ktor.features.* +import io.ktor.gson.* +import io.ktor.http.* +{{#featureLocations}} +import io.ktor.locations.* +{{/featureLocations}} +{{#featureMetrics}} +import io.ktor.metrics.dropwizard.* +import java.util.concurrent.TimeUnit +{{/featureMetrics}} +import io.ktor.routing.* +import io.ktor.util.* +{{#hasAuthMethods}} import com.typesafe.config.ConfigFactory -import io.ktor.application.Application -import io.ktor.application.ApplicationStopping -import io.ktor.application.install -import io.ktor.application.log +import io.ktor.auth.* import io.ktor.client.HttpClient import io.ktor.client.engine.apache.Apache import io.ktor.config.HoconApplicationConfig -{{#featureAutoHead}} -import io.ktor.features.AutoHeadResponse -{{/featureAutoHead}} -{{#featureCompression}} -import io.ktor.features.Compression -{{/featureCompression}} -{{#featureCORS}} -import io.ktor.features.CORS -{{/featureCORS}} -{{#featureConditionalHeaders}} -import io.ktor.features.ConditionalHeaders -{{/featureConditionalHeaders}} -import io.ktor.features.ContentNegotiation -import io.ktor.features.DefaultHeaders -{{#featureHSTS}} -import io.ktor.features.HSTS -{{/featureHSTS}} -import io.ktor.gson.GsonConverter -import io.ktor.http.ContentType -{{#featureLocations}} -import io.ktor.locations.KtorExperimentalLocationsAPI -import io.ktor.locations.Locations -{{/featureLocations}} -import io.ktor.routing.Routing -import java.util.concurrent.TimeUnit -{{#hasAuthMethods}} -import io.ktor.auth.Authentication -import io.ktor.auth.oauth -import io.ktor.metrics.dropwizard.DropwizardMetrics -import org.openapitools.server.infrastructure.ApiKeyCredential -import org.openapitools.server.infrastructure.ApiPrincipal -import org.openapitools.server.infrastructure.apiKeyAuth +import org.openapitools.server.infrastructure.* {{/hasAuthMethods}} {{#generateApis}}{{#apiInfo}}{{#apis}}import {{apiPackage}}.{{classname}} {{/apis}}{{/apiInfo}}{{/generateApis}} +{{#hasAuthMethods}} internal val settings = HoconApplicationConfig(ConfigFactory.defaultApplication(HTTP::class.java.classLoader)) object HTTP { val client = HttpClient(Apache) } +{{/hasAuthMethods}} +@KtorExperimentalAPI {{#featureLocations}} @KtorExperimentalLocationsAPI {{/featureLocations}} fun Application.main() { install(DefaultHeaders) + {{#featureMetrics}} install(DropwizardMetrics) { val reporter = Slf4jReporter.forRegistry(registry) .outputTo(log) @@ -64,27 +50,28 @@ fun Application.main() { .build() reporter.start(10, TimeUnit.SECONDS) } + {{/featureMetrics}} {{#generateApis}} install(ContentNegotiation) { register(ContentType.Application.Json, GsonConverter()) } {{#featureAutoHead}} - install(AutoHeadResponse) // see http://ktor.io/features/autoheadresponse.html + install(AutoHeadResponse) // see https://ktor.io/docs/autoheadresponse.html {{/featureAutoHead}} {{#featureConditionalHeaders}} - install(ConditionalHeaders) // see http://ktor.io/features/conditional-headers.html + install(ConditionalHeaders) // see https://ktor.io/docs/conditional-headers.html {{/featureConditionalHeaders}} - {{#featureHSTS}} - install(HSTS, ApplicationHstsConfiguration()) // see http://ktor.io/features/hsts.html - {{/featureHSTS}} - {{#featureCORS}} - install(CORS, ApplicationCORSConfiguration()) // see http://ktor.io/features/cors.html - {{/featureCORS}} {{#featureCompression}} - install(Compression, ApplicationCompressionConfiguration()) // see http://ktor.io/features/compression.html + install(Compression, ApplicationCompressionConfiguration()) // see https://ktor.io/docs/compression.html {{/featureCompression}} + {{#featureCORS}} + install(CORS, ApplicationCORSConfiguration()) // see https://ktor.io/docs/cors.html + {{/featureCORS}} + {{#featureHSTS}} + install(HSTS, ApplicationHstsConfiguration()) // see https://ktor.io/docs/hsts.html + {{/featureHSTS}} {{#featureLocations}} - install(Locations) // see http://ktor.io/features/locations.html + install(Locations) // see https://ktor.io/docs/features-locations.html {{/featureLocations}} {{#hasAuthMethods}} install(Authentication) { @@ -140,8 +127,4 @@ fun Application.main() { } {{/generateApis}} - - environment.monitor.subscribe(ApplicationStopping) { - HTTP.client.close() - } } diff --git a/modules/openapi-generator/src/main/resources/kotlin-server/libraries/ktor/Configuration.kt.mustache b/modules/openapi-generator/src/main/resources/kotlin-server/libraries/ktor/Configuration.kt.mustache index a8956ec5905..76a07ce208f 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-server/libraries/ktor/Configuration.kt.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-server/libraries/ktor/Configuration.kt.mustache @@ -1,16 +1,14 @@ package {{packageName}} // Use this file to hold package-level internal functions that return receiver object passed to the `install` method. -import io.ktor.auth.OAuthServerSettings -import io.ktor.features.Compression -import io.ktor.features.HSTS -import io.ktor.features.deflate -import io.ktor.features.gzip -import io.ktor.features.minimumSize -import io.ktor.http.HttpMethod +import io.ktor.auth.* +import io.ktor.features.* +import io.ktor.http.* +import io.ktor.util.* +import java.time.Duration import java.util.concurrent.TimeUnit - {{#featureCORS}} + /** * Application block for [CORS] configuration. * @@ -33,8 +31,8 @@ internal fun ApplicationCORSConfiguration(): CORS.Configuration.() -> Unit { } } {{/featureCORS}} - {{#featureHSTS}} + /** * Application block for [HSTS] configuration. * @@ -54,8 +52,8 @@ internal fun ApplicationHstsConfiguration(): HSTS.Configuration.() -> Unit { } } {{/featureHSTS}} - {{#featureCompression}} + /** * Application block for [Compression] configuration. * @@ -99,8 +97,8 @@ val ApplicationAuthProviders: Map = listOflicenseInfo}} package {{packageName}} -import io.ktor.locations.KtorExperimentalLocationsAPI -import io.ktor.locations.Location +import io.ktor.locations.* import {{packageName}}.models.* {{#imports}}import {{import}} {{/imports}} {{#apiInfo}} +@KtorExperimentalLocationsAPI object Paths { {{#apis}} {{#operations}} {{#operation}} - /** - * {{summary}} + /**{{#summary}} + * {{summary}}{{/summary}} * {{#unescapedNotes}}{{.}}{{/unescapedNotes}} {{#allParams}}* @param {{paramName}} {{description}} {{^required}}(optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}} {{/allParams}}*/ - @KtorExperimentalLocationsAPI + {{#hasParams}} @Location("{{path}}") class {{operationId}}({{#allParams}}val {{paramName}}: {{{dataType}}}{{^required}}? = null{{/required}}{{#required}}{{#isNullable}}?{{/isNullable}}{{/required}}{{^-last}}, {{/-last}}{{/allParams}}) + {{/hasParams}} + {{^hasParams}} + @Location("{{path}}") object {{operationId}} + {{/hasParams}} {{/operation}} {{/operations}} diff --git a/modules/openapi-generator/src/main/resources/kotlin-server/libraries/ktor/README.mustache b/modules/openapi-generator/src/main/resources/kotlin-server/libraries/ktor/README.mustache index f12148e1d39..2763aa259aa 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-server/libraries/ktor/README.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-server/libraries/ktor/README.mustache @@ -8,8 +8,8 @@ Generated by OpenAPI Generator {{generatorVersion}}{{^hideGenerationTimestamp}} ## Requires -* Kotlin 1.4.31 -* Gradle 6.8.2 +* Kotlin 1.4.32 +* Gradle 6.9 ## Build diff --git a/modules/openapi-generator/src/main/resources/kotlin-server/libraries/ktor/api.mustache b/modules/openapi-generator/src/main/resources/kotlin-server/libraries/ktor/api.mustache index a3d8c124e81..ba7eccdee56 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-server/libraries/ktor/api.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-server/libraries/ktor/api.mustache @@ -2,50 +2,27 @@ package {{apiPackage}} import com.google.gson.Gson -import io.ktor.application.call -import io.ktor.auth.UserIdPrincipal -import io.ktor.auth.authentication -import io.ktor.auth.authenticate -import io.ktor.auth.OAuthAccessTokenResponse -import io.ktor.auth.OAuthServerSettings -import io.ktor.http.ContentType -import io.ktor.http.HttpStatusCode -import io.ktor.response.respond -import io.ktor.response.respondText -import io.ktor.routing.Route +import io.ktor.application.* +import io.ktor.auth.* +import io.ktor.http.* +import io.ktor.response.* {{#featureLocations}} import {{packageName}}.Paths -import io.ktor.locations.KtorExperimentalLocationsAPI -import io.ktor.locations.delete -import io.ktor.locations.get -import io.ktor.locations.post -import io.ktor.locations.put -import io.ktor.locations.options -import io.ktor.locations.head +import io.ktor.locations.* {{/featureLocations}} -{{^featureLocations}} -import io.ktor.routing.delete -import io.ktor.routing.get -import io.ktor.routing.post -import io.ktor.routing.put -import io.ktor.routing.options -import io.ktor.routing.head -import io.ktor.routing.route -{{/featureLocations}} - +import io.ktor.routing.* import {{packageName}}.infrastructure.ApiPrincipal - - {{#imports}}import {{import}} {{/imports}} {{#operations}} - {{#featureLocations}} +{{#featureLocations}} @KtorExperimentalLocationsAPI - {{/featureLocations}} +{{/featureLocations}} fun Route.{{classname}}() { val gson = Gson() val empty = mutableMapOf() + {{#operation}} {{#hasAuthMethods}} {{#authMethods}} diff --git a/modules/openapi-generator/src/main/resources/kotlin-server/libraries/ktor/build.gradle.mustache b/modules/openapi-generator/src/main/resources/kotlin-server/libraries/ktor/build.gradle.mustache index 173686fdf88..8d8948d689c 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-server/libraries/ktor/build.gradle.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-server/libraries/ktor/build.gradle.mustache @@ -1,37 +1,35 @@ -group '{{groupId}}' -version '{{artifactVersion}}' +group "{{groupId}}" +version "{{artifactVersion}}" wrapper { - gradleVersion = '6.8.2' + gradleVersion = "6.9" distributionUrl = "https://services.gradle.org/distributions/gradle-$gradleVersion-all.zip" } buildscript { - ext.kotlin_version = '1.4.31' - ext.ktor_version = '1.5.2' - ext.shadow_version = '2.0.3' + ext.kotlin_version = "1.4.32" + ext.ktor_version = "1.5.4" + ext.shadow_version = "6.1.0" repositories { maven { url "https://repo1.maven.org/maven2" } - maven { - url = "https://plugins.gradle.org/m2/" - } + maven { url "https://plugins.gradle.org/m2/" } } dependencies { - classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" - classpath "com.github.jengelman.gradle.plugins:shadow:$shadow_version" + classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version") + classpath("com.github.jengelman.gradle.plugins:shadow:$shadow_version") } } -apply plugin: 'java' -apply plugin: 'kotlin' -apply plugin: 'application' +apply plugin: "java" +apply plugin: "kotlin" +apply plugin: "application" mainClassName = "io.ktor.server.netty.DevelopmentEngine" -// Initialization order with shadow 2.0.1 and Gradle 6.8.2 is weird. +// Initialization order with shadow 2.0.1 and Gradle 6.9 is weird. // See https://github.com/johnrengelman/shadow/issues/336#issuecomment-355402508 -apply plugin: 'com.github.johnrengelman.shadow' +apply plugin: "com.github.johnrengelman.shadow" sourceCompatibility = 1.8 @@ -44,28 +42,36 @@ compileTestKotlin { } shadowJar { - baseName = '{{artifactId}}' + baseName = "{{artifactId}}" classifier = null version = null } repositories { - maven { url "https://repo1.maven.org/maven2" } - maven { url "https://dl.bintray.com/kotlin/ktor" } - maven { url "https://dl.bintray.com/kotlin/kotlinx" } + maven { setUrl("https://repo1.maven.org/maven2") } + maven { setUrl("https://dl.bintray.com/kotlin/ktor") } + maven { setUrl("https://dl.bintray.com/kotlin/kotlinx") } } dependencies { - compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version" - compile "io.ktor:ktor-server-netty:$ktor_version" - compile "io.ktor:ktor-metrics:$ktor_version" - compile "io.ktor:ktor-auth:$ktor_version" + implementation("org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version") + implementation("ch.qos.logback:logback-classic:1.2.1") +{{#hasAuthMethods}} + implementation("com.typesafe:config:1.4.1") +{{/hasAuthMethods}} + implementation("io.ktor:ktor-auth:$ktor_version") +{{#hasAuthMethods}} + implementation("io.ktor:ktor-client-apache:$ktor_version") +{{/hasAuthMethods}} + implementation("io.ktor:ktor-gson:$ktor_version") {{#featureLocations}} - compile "io.ktor:ktor-locations:$ktor_version" + implementation("io.ktor:ktor-locations:$ktor_version") {{/featureLocations}} - compile "io.ktor:ktor-gson:$ktor_version" - compile "io.ktor:ktor-client-core:$ktor_version" - compile "io.ktor:ktor-client-apache:$ktor_version" - compile "ch.qos.logback:logback-classic:1.2.1" - testCompile group: 'junit', name: 'junit', version: '4.13' +{{#featureMetrics}} + implementation("io.dropwizard.metrics:metrics-core:4.1.18") + implementation("io.ktor:ktor-metrics:$ktor_version") +{{/featureMetrics}} + implementation("io.ktor:ktor-server-netty:$ktor_version") + + testImplementation("junit:junit:4.13.2") } diff --git a/modules/openapi-generator/src/main/resources/php-mezzio-ph-modern/Factory.php.mustache b/modules/openapi-generator/src/main/resources/php-mezzio-ph-modern/Factory.php.mustache new file mode 100644 index 00000000000..c517b693604 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/php-mezzio-ph-modern/Factory.php.mustache @@ -0,0 +1,53 @@ +get(EmitterInterface::class), + $container->get(ServerRequestInterface::class), + static fn(\Throwable $error): ResponseInterface => $errorMiddleware->handleError($error) + ); + $application = new Application( + $container->get(MiddlewareFactory::class), + $pipeline, + $container->get(RouteCollector::class), + $runner + ); + $application->pipe($errorMiddleware); + $application->pipe(RouteMiddleware::class); + $application->pipe(MethodNotAllowedMiddleware::class); + $application->pipe(DispatchMiddleware::class); + $application->pipe(NotFoundHandler::class); + + return $application; + } + + protected static function getErrorMiddleware(ContainerInterface $container): Middleware\InternalServerError + { + return $container->get(Middleware\InternalServerError::class); + } +} diff --git a/modules/openapi-generator/src/main/resources/php-mezzio-ph-modern/InternalServerError.php.mustache b/modules/openapi-generator/src/main/resources/php-mezzio-ph-modern/InternalServerError.php.mustache new file mode 100644 index 00000000000..54f4d66a56d --- /dev/null +++ b/modules/openapi-generator/src/main/resources/php-mezzio-ph-modern/InternalServerError.php.mustache @@ -0,0 +1,45 @@ +handle($request); + ErrorHandler::stop(true); + } + catch (\Throwable $error) { + $result = $this->handleError($error); + } + return $result; + } + + public function handleError(\Throwable $error): ResponseInterface + { + \error_log((string)$error); + return $this->generateEmptyResponse()->withStatus(500, 'Internal server error'); + } + + protected function generateEmptyResponse(): ResponseInterface + { + return ($this->responseGenerator)(); + } +} diff --git a/modules/openapi-generator/src/main/resources/php-mezzio-ph-modern/README.md.mustache b/modules/openapi-generator/src/main/resources/php-mezzio-ph-modern/README.md.mustache new file mode 100644 index 00000000000..fd66369b261 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/php-mezzio-ph-modern/README.md.mustache @@ -0,0 +1,34 @@ +# OpenAPI generated server + +Generated by the [OpenAPI Generator](https://openapi-generator.tech) project. + +## Overview +This server stub aims to provide light, yet comprehensive structure for your API project using: + +- PHP: >=8.0 +- [Laminas Mezzio](https://docs.mezzio.dev/mezzio/): >=3.3 +- [Path Handler](https://github.com/Articus/PathHandler): >=0.7 + +## How to use +All you have to do to start development is: + +- install dependencies via [Composer](https://getcomposer.org/) (small note: [ext-yaml](https://pecl.php.net/package/yaml) is used only for configuration parsing, so if you want to drop this dependency, simply adjust `./application/container.php`) +- create cache folder: `mkdir -p ./data/cache` (you will need it later for configuration and metadata caches - check comments in `./application/config.yml`) +- start PHP development server: `php -S 0.0.0.0:8080 -t ./public` (or any other SAPI you prefer, just make sure that you configure webroot to `./public` and rewrites to `./public/index.php`) + +After that you should be able to call all methods from your API spec. Most of the negative scenarios should be handled: + +- `404 Not found` for unknown routes +- `406 Not acceptable` for invalid `Accept` header +- `415 Unsupported media type` for invalid `Content-Type` header +- `400 Malformed JSON` for unparsable JSON body +- `422 Unprocessable entity` for parsable JSON body that fails validation + +But for obvious reason you will not get any `200 OK`, only `501 Not implemented`. So your next steps are: + +- check all TODOs left in the stub code where generator was not smart enough and could not guarantee correct implementation +- implement your API security mechanism (either special attribute or separate middleware) - generator does not do anything about it yet +- implement your handlers - the most tricky part :) + +## Enjoy! +Hopefully this stub will reduce the amount of boilerplate code you have to write manually. If you have any suggestions or questions about `php-mezzio-ph` generator, feel free to create issue either in [Path Handler repository](https://github.com/Articus/PathHandler/issues) or in [OpenAPI Generator repository](https://openapi-generator.tech/issues). diff --git a/modules/openapi-generator/src/main/resources/php-mezzio-ph-modern/api.mustache b/modules/openapi-generator/src/main/resources/php-mezzio-ph-modern/api.mustache new file mode 100644 index 00000000000..fdba51f5e00 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/php-mezzio-ph-modern/api.mustache @@ -0,0 +1,73 @@ + {{internal.ze-ph.queryDataType}}::class, + "objectAttr" => "queryData", + "source" => PHAttribute\Transfer::SOURCE_GET + ])] +{{/internal.ze-ph.hasQueryData}} +{{/vendorExtensions}} +{{#bodyParam}} +{{#consumes}} + // TODO check if consumer is valid, if it has correct priority and if it can be moved to class annotation + #[PHA\Consumer("{{{mediaType}}}", PHConsumer\Json::class)] +{{/consumes}} +{{^isPrimitiveType}} + #[PHA\Attribute(PHAttribute\Transfer::class, ["type" => {{dataType}}::class, "objectAttr" => "bodyData"])] +{{/isPrimitiveType}} +{{/bodyParam}} +{{#produces}} + // TODO check if producer is valid, if it has correct priority and if it can be moved to class annotation + #[PHA\Producer("{{{mediaType}}}", PHProducer\Transfer::class)] +{{/produces}} + public function {{operationId}}(ServerRequestInterface $request){{#returnType}}: {{returnType}}{{/returnType}} + { + //TODO implement method +{{#vendorExtensions}} +{{#internal.ze-ph.hasQueryData}} + /** @var {{internal.ze-ph.queryDataType}} $queryData */ + $queryData = $request->getAttribute("queryData"); +{{/internal.ze-ph.hasQueryData}} +{{/vendorExtensions}} +{{#bodyParam}} +{{^isPrimitiveType}} + /** @var {{dataType}} $bodyData */ + $bodyData = $request->getAttribute("bodyData"); +{{/isPrimitiveType}} +{{/bodyParam}} + throw new PHException\HttpCode(501, "Not implemented"); + } +{{/operation}} +} +{{/operations}} diff --git a/samples/openapi3/server/petstore/php-mezzio-ph/application/config/app.yml b/modules/openapi-generator/src/main/resources/php-mezzio-ph-modern/app.yml.mustache similarity index 100% rename from samples/openapi3/server/petstore/php-mezzio-ph/application/config/app.yml rename to modules/openapi-generator/src/main/resources/php-mezzio-ph-modern/app.yml.mustache diff --git a/modules/openapi-generator/src/main/resources/php-mezzio-ph-modern/composer.json.mustache b/modules/openapi-generator/src/main/resources/php-mezzio-ph-modern/composer.json.mustache new file mode 100644 index 00000000000..787d5fb97f2 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/php-mezzio-ph-modern/composer.json.mustache @@ -0,0 +1,26 @@ +{ + "name": "{{#lambda.lowercase}}{{gitUserId}}/{{gitRepoId}}{{/lambda.lowercase}}", + "description": "{{description}}", + "license": "unlicense", + "version": "{{artifactVersion}}", + "type": "project", + "require": { + "php": "^8.0", + "ext-yaml": "^2.2", + "mezzio/mezzio": "^3.3", + "laminas/laminas-diactoros": "^2.5", + "articus/path-handler": "^0.7", + "articus/data-transfer": "^0.5", + "articus/openapi-generator-common": "^0.2", + "psr/simple-cache": "^1.0", + "laminas/laminas-config": "^3.4", + "laminas/laminas-stdlib": "^3.3", + "laminas/laminas-validator": "^2.14", + "nikic/fast-route": "^1.3" + }, + "autoload": { + "psr-4": { + "": "src/" + } + } +} \ No newline at end of file diff --git a/samples/openapi3/server/petstore/php-mezzio-ph/application/config.yml b/modules/openapi-generator/src/main/resources/php-mezzio-ph-modern/config.yml similarity index 68% rename from samples/openapi3/server/petstore/php-mezzio-ph/application/config.yml rename to modules/openapi-generator/src/main/resources/php-mezzio-ph-modern/config.yml index 1f106812353..58056552c5b 100644 --- a/samples/openapi3/server/petstore/php-mezzio-ph/application/config.yml +++ b/modules/openapi-generator/src/main/resources/php-mezzio-ph-modern/config.yml @@ -9,12 +9,13 @@ # router: # cache: # directory: ./data/cache/PathHandler -# #Enable handler metadata cache -# metadata: -# cache: -# directory: ./data/cache/PathHandler + +#Enable handler metadata cache +#Articus\PathHandler\MetadataProvider\PhpAttribute: +# cache: +# directory: ./data/cache/PathHandler #Enable data transfer metadata cache for DTOs -#Articus\DataTransfer\MetadataProvider\Annotation: +#Articus\DataTransfer\MetadataProvider\PhpAttribute: # cache: # directory: ./data/cache/DataTransfer diff --git a/samples/openapi3/server/petstore/php-mezzio-ph/application/container.php b/modules/openapi-generator/src/main/resources/php-mezzio-ph-modern/container.php similarity index 91% rename from samples/openapi3/server/petstore/php-mezzio-ph/application/container.php rename to modules/openapi-generator/src/main/resources/php-mezzio-ph-modern/container.php index b9638c5584b..9c54fafcfec 100644 --- a/samples/openapi3/server/petstore/php-mezzio-ph/application/container.php +++ b/modules/openapi-generator/src/main/resources/php-mezzio-ph-modern/container.php @@ -6,9 +6,6 @@ use Laminas\Config\Factory as ConfigFactory; //Use Composer autoload that includes code both from ../src and ../vendor require __DIR__ . '/../vendor/autoload.php'; -//Register Doctrine annotation autoload -\Doctrine\Common\Annotations\AnnotationRegistry::registerLoader('class_exists'); - //Path to file for caching full configuration const CONFIG_CACHE_PATH = __DIR__ . '/../data/cache/config.php'; diff --git a/modules/openapi-generator/src/main/resources/php-mezzio-ph-modern/data_transfer.yml.mustache b/modules/openapi-generator/src/main/resources/php-mezzio-ph-modern/data_transfer.yml.mustache new file mode 100644 index 00000000000..7bdd139bb9f --- /dev/null +++ b/modules/openapi-generator/src/main/resources/php-mezzio-ph-modern/data_transfer.yml.mustache @@ -0,0 +1,34 @@ +dependencies: + factories: + Articus\DataTransfer\Service: Articus\DataTransfer\Factory + Articus\DataTransfer\MetadataProvider\PhpAttribute: Articus\DataTransfer\MetadataProvider\Factory\PhpAttribute + Articus\DataTransfer\Strategy\PluginManager: Articus\DataTransfer\Strategy\Factory\PluginManager + Articus\DataTransfer\Validator\PluginManager: Articus\DataTransfer\Validator\Factory\PluginManager + Laminas\Validator\ValidatorPluginManager: Laminas\Validator\ValidatorPluginManagerFactory + aliases: + Articus\DataTransfer\ClassMetadataProviderInterface: Articus\DataTransfer\MetadataProvider\PhpAttribute + Articus\DataTransfer\FieldMetadataProviderInterface: Articus\DataTransfer\MetadataProvider\PhpAttribute + +Articus\DataTransfer\Strategy\PluginManager: + invokables: + QueryStringScalar: OpenAPIGenerator\Common\Strategy\QueryStringScalar + QueryStringScalarArray: OpenAPIGenerator\Common\Strategy\QueryStringScalarArray + factories: + Date: OpenAPIGenerator\Common\Strategy\Factory\MutableDate + DateTime: OpenAPIGenerator\Common\Strategy\Factory\MutableDateTime + ObjectList: OpenAPIGenerator\Common\Strategy\Factory\NoArgObjectList + ObjectMap: OpenAPIGenerator\Common\Strategy\Factory\NoArgObjectMap + ScalarList: OpenAPIGenerator\Common\Strategy\Factory\ScalarList + ScalarMap: OpenAPIGenerator\Common\Strategy\Factory\ScalarMap + +Articus\DataTransfer\Validator\PluginManager: + invokables: + Scalar: OpenAPIGenerator\Common\Validator\Scalar + QueryStringScalar: OpenAPIGenerator\Common\Validator\QueryStringScalar + QueryStringScalarArray: OpenAPIGenerator\Common\Validator\QueryStringScalarArray + abstract_factories: + - Articus\DataTransfer\Validator\Factory\Laminas + +validators: + invokables: + Count: Laminas\Validator\IsCountable diff --git a/samples/openapi3/server/petstore/php-mezzio-ph/.gitignore b/modules/openapi-generator/src/main/resources/php-mezzio-ph-modern/gitignore similarity index 100% rename from samples/openapi3/server/petstore/php-mezzio-ph/.gitignore rename to modules/openapi-generator/src/main/resources/php-mezzio-ph-modern/gitignore diff --git a/samples/openapi3/server/petstore/php-mezzio-ph/public/index.php b/modules/openapi-generator/src/main/resources/php-mezzio-ph-modern/index.php similarity index 100% rename from samples/openapi3/server/petstore/php-mezzio-ph/public/index.php rename to modules/openapi-generator/src/main/resources/php-mezzio-ph-modern/index.php diff --git a/modules/openapi-generator/src/main/resources/php-mezzio-ph-modern/list_item_type.mustache b/modules/openapi-generator/src/main/resources/php-mezzio-ph-modern/list_item_type.mustache new file mode 100644 index 00000000000..25467661433 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/php-mezzio-ph-modern/list_item_type.mustache @@ -0,0 +1,8 @@ +{{#items +}}{{^isContainer +}}{{#isPrimitiveType}}"{{dataType}}"{{/isPrimitiveType +}}{{^isPrimitiveType}}{{dataType}}::class{{/isPrimitiveType +}}{{/isContainer +}}{{#isContainer +}}{{dataType}}::class{{/isContainer +}}{{/items}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/php-mezzio-ph-modern/map_item_type.mustache b/modules/openapi-generator/src/main/resources/php-mezzio-ph-modern/map_item_type.mustache new file mode 100644 index 00000000000..a58e19beca5 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/php-mezzio-ph-modern/map_item_type.mustache @@ -0,0 +1,8 @@ +{{#additionalProperties +}}{{^isContainer +}}{{#isPrimitiveType}}"{{dataType}}"{{/isPrimitiveType +}}{{^isPrimitiveType}}{{dataType}}::class{{/isPrimitiveType +}}{{/isContainer +}}{{#isContainer +}}{{dataType}}::class{{/isContainer +}}{{/additionalProperties}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/php-mezzio-ph-modern/model.mustache b/modules/openapi-generator/src/main/resources/php-mezzio-ph-modern/model.mustache new file mode 100644 index 00000000000..4d73c185945 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/php-mezzio-ph-modern/model.mustache @@ -0,0 +1,13 @@ +model_container}}{{/internal.ze-ph.fromContainer +}}{{^internal.ze-ph.fromContainer}}{{>model_object}}{{/internal.ze-ph.fromContainer +}}{{/vendorExtensions +}}{{^vendorExtensions}}{{>model_object}}{{/vendorExtensions +}}{{/model}}{{/models}} diff --git a/modules/openapi-generator/src/main/resources/php-mezzio-ph-modern/model_container.mustache b/modules/openapi-generator/src/main/resources/php-mezzio-ph-modern/model_container.mustache new file mode 100644 index 00000000000..543194c798b --- /dev/null +++ b/modules/openapi-generator/src/main/resources/php-mezzio-ph-modern/model_container.mustache @@ -0,0 +1,57 @@ +{{#vars +}}{{#isArray +}}#[DTA\Strategy("{{#isPrimitiveType}}ScalarList{{/isPrimitiveType}}{{^isPrimitiveType}}ObjectList{{/isPrimitiveType}}", ["type" => {{>list_item_type}}])] +{{#minItems}}{{^maxItems +}}#[DTA\Validator("Count", ["min" => {{minItems}}], blocker: true)] +{{/maxItems}}{{/minItems +}}{{^minItems}}{{#maxItems +}}#[DTA\Validator("Count", ["max" => {{maxItems}}], blocker: true)] +{{/maxItems}}{{/minItems +}}{{#minItems}}{{#maxItems +}}#[DTA\Validator("Count", ["min" => {{minItems}}, "max" => {{maxItems}}], blocker: true)] +{{/maxItems}}{{/minItems +}}#[DTA\Validator("Collection", ["validators" => [ +{{#isPrimitiveType +}} ["name" => "Scalar", "options" => ["type" => {{>list_item_type}}]] +{{/isPrimitiveType +}}{{#isDate +}} ["name" => "Date"] +{{/isDate +}}{{#isDateTime +}} ["name" => "Date", "options" => ["format" => \DateTime::RFC3339]] +{{/isDateTime +}}{{^isPrimitiveType}}{{^isDate}}{{^isDateTime +}} ["name" => "TypeCompliant", "options" => ["type" => {{>list_item_type}}]] +{{/isDateTime}}{{/isDate}}{{/isPrimitiveType +}}]])] +{{/isArray +}}{{#isMap +}}#[DTA\Strategy("{{#isPrimitiveType}}ScalarMap{{/isPrimitiveType}}{{^isPrimitiveType}}ObjectMap{{/isPrimitiveType}}", ["type" => {{>map_item_type}}])] +{{#minProperties}}{{^maxProperties +}}#[DTA\Validator("Count", ["min" => {{minProperties}}], blocker: true)] +{{/maxProperties}}{{/minProperties +}}{{^minProperties}}{{#maxProperties +}}#[DTA\Validator("Count", ["max" => {{maxProperties}}], blocker: true)] +{{/maxProperties}}{{/minProperties +}}{{#minProperties}}{{#maxProperties +}}#[DTA\Validator("Count", ["min" => {{minProperties}}, "max" => {{maxProperties}}], blocker: true)] +{{/maxProperties}}{{/minProperties +}}#[DTA\Validator("Collection", ["validators" => [ +{{#isPrimitiveType +}} ["name" => "Scalar", "options" => ["type" => {{>map_item_type}}]] +{{/isPrimitiveType +}}{{#isDate +}} ["name" => "Date"] +{{/isDate +}}{{#isDateTime +}} ["name" => "Date", "options" => ["format" => \DateTime::RFC3339]] +{{/isDateTime +}}{{^isPrimitiveType}}{{^isDate}}{{^isDateTime +}} ["name" => "TypeCompliant", "options" => ["type" => {{>map_item_type}}]] +{{/isDateTime}}{{/isDate}}{{/isPrimitiveType +}}]])] +{{/isMap +}}{{/vars +}}class {{classname}} extends \ArrayObject +{ +} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/php-mezzio-ph-modern/model_normal_var.mustache b/modules/openapi-generator/src/main/resources/php-mezzio-ph-modern/model_normal_var.mustache new file mode 100644 index 00000000000..6e215f7fc63 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/php-mezzio-ph-modern/model_normal_var.mustache @@ -0,0 +1,45 @@ +{{#isContainer +}} #[DTA\Strategy("Object", ["type" => {{internal.ze-ph.containerDataType}}::class])] + #[DTA\Validator("TypeCompliant", ["type" => {{internal.ze-ph.containerDataType}}::class])] +{{/isContainer +}}{{^isContainer +}}{{#isPrimitiveType +}} #[DTA\Validator("Scalar", ["type" => "{{dataType}}"])] +{{/isPrimitiveType +}}{{#isDate +}} #[DTA\Strategy("Date")] + #[DTA\Validator("Date")] +{{/isDate +}}{{#isDateTime +}} #[DTA\Strategy("DateTime")] + #[DTA\Validator("Date", ["format" => \DateTime::RFC3339])] +{{/isDateTime +}}{{^isPrimitiveType +}}{{^isDate +}}{{^isDateTime +}} #[DTA\Strategy("Object", ["type" => {{dataType}}::class])] + #[DTA\Validator("TypeCompliant", ["type" => {{dataType}}::class])] +{{/isDateTime +}}{{/isDate +}}{{/isPrimitiveType +}}{{/isContainer +}}{{#hasValidation +}}{{#minLength}}{{#maxLength +}} #[DTA\Validator("StringLength", ["min" => {{minLength}}, "max" => {{maxLength}}])] +{{/maxLength}}{{/minLength +}}{{^minLength}}{{#maxLength +}} #[DTA\Validator("StringLength", ["max" => {{maxLength}}])] +{{/maxLength}}{{/minLength +}}{{#minLength}}{{^maxLength +}} #[DTA\Validator("StringLength", ["min" => {{minLength}}])] +{{/maxLength}}{{/minLength +}}{{#minimum +}} #[DTA\Validator("GreaterThan", ["min" => {{minimum}}{{^exclusiveMinimum}}, "inclusive" => true{{/exclusiveMinimum}}])] +{{/minimum +}}{{#maximum +}} #[DTA\Validator("LessThan", ["max" => {{maximum}}{{^exclusiveMaximum}}, "inclusive" => true{{/exclusiveMaximum}}])] +{{/maximum +}}{{#pattern +}} #[DTA\Validator("Regex", ["pattern" => "{{{pattern}}}"])] +{{/pattern +}}{{/hasValidation}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/php-mezzio-ph-modern/model_object.mustache b/modules/openapi-generator/src/main/resources/php-mezzio-ph-modern/model_object.mustache new file mode 100644 index 00000000000..253d551e3c7 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/php-mezzio-ph-modern/model_object.mustache @@ -0,0 +1,23 @@ +{{#description +}}/** + * {{description}} + */ +{{/description +}}class {{classname}} +{ +{{#vars +}}{{#description +}} /** + * {{description}} + */ +{{/description +}} #[DTA\Data(field: "{{baseName}}"{{^required}}, nullable: true{{/required}})] +{{#vendorExtensions +}}{{#internal.ze-ph.fromQuery}}{{>model_query_var}}{{/internal.ze-ph.fromQuery +}}{{^internal.ze-ph.fromQuery}}{{>model_normal_var}}{{/internal.ze-ph.fromQuery +}}{{/vendorExtensions +}}{{^vendorExtensions}}{{>model_normal_var}}{{/vendorExtensions +}} public {{dataType}}|null ${{name}} = null; + +{{/vars +}}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/php-mezzio-ph-modern/model_query_var.mustache b/modules/openapi-generator/src/main/resources/php-mezzio-ph-modern/model_query_var.mustache new file mode 100644 index 00000000000..f2e6525b9b9 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/php-mezzio-ph-modern/model_query_var.mustache @@ -0,0 +1,51 @@ +{{#isArray +}}{{#isPrimitiveType +}} #[DTA\Strategy("QueryStringScalarArray", ["type" => {{>list_item_type}}, "format" => "{{internal.ze-ph.collectionFormat}}"])] + #[DTA\Validator("QueryStringScalarArray", ["type" => {{>list_item_type}}, "format" => "{{internal.ze-ph.collectionFormat}}"{{#minItems}}, "min_items" => {{minItems}}{{/minItems}}{{#maxItems}}, "max_items" => {{maxItems}}{{/maxItems}}])] +{{/isPrimitiveType +}}{{^isPrimitiveType +}} // TODO add validator(s) and strategy for list of {{>list_item_type}} and collection format {{internal.ze-ph.collectionFormat}} inside query string +{{/isPrimitiveType +}}{{/isArray +}}{{#isMap +}} // TODO add validator(s) and strategy for map of {{>map_item_type}} and collection format {{internal.ze-ph.collectionFormat}} inside query string +{{/isMap +}}{{^isContainer +}}{{#isPrimitiveType +}} #[DTA\Strategy("QueryStringScalar", ["type" => "{{dataType}}"])] + #[DTA\Validator("QueryStringScalar", ["type" => "{{dataType}}"])] +{{/isPrimitiveType +}}{{#isDate +}} #[DTA\Strategy("Date")] + #[DTA\Validator("Date")] +{{/isDate +}}{{#isDateTime +}} #[DTA\Strategy("DateTime")] + #[DTA\Validator("Date", ["format" => \DateTime::RFC3339])] +{{/isDateTime +}}{{^isPrimitiveType +}}{{^isDate}}{{^isDateTime +}} // TODO add validator(s) and strategy for {{dataType}} inside query string +{{/isDateTime}}{{/isDate +}}{{/isPrimitiveType +}}{{/isContainer +}}{{#hasValidation +}}{{#minLength}}{{#maxLength +}} #[DTA\Validator("StringLength", ["min" => {{minLength}}, "max" => {{maxLength}}])] +{{/maxLength}}{{/minLength +}}{{^minLength}}{{#maxLength +}} #[DTA\Validator("StringLength", ["max" => {{maxLength}}])] +{{/maxLength}}{{/minLength +}}{{#minLength}}{{^maxLength +}} #[DTA\Validator("StringLength", ["min" => {{minLength}}])] +{{/maxLength}}{{/minLength +}}{{#minimum +}} #[DTA\Validator("GreaterThan", ["min" => {{minimum}}{{^exclusiveMinimum}}, "inclusive" => true{{/exclusiveMinimum}}])] +{{/minimum +}}{{#maximum +}} #[DTA\Validator("LessThan", ["max" => {{maximum}}{{^exclusiveMaximum}}, "inclusive" => true{{/exclusiveMaximum}}])] +{{/maximum +}}{{#pattern +}} #[DTA\Validator("Regex", ["pattern" => "{{{pattern}}}"])] +{{/pattern +}}{{/hasValidation}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/php-mezzio-ph-modern/path_handler.yml.mustache b/modules/openapi-generator/src/main/resources/php-mezzio-ph-modern/path_handler.yml.mustache new file mode 100644 index 00000000000..a9739a17216 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/php-mezzio-ph-modern/path_handler.yml.mustache @@ -0,0 +1,44 @@ +dependencies: + factories: + Mezzio\Router\RouterInterface: Articus\PathHandler\RouteInjectionFactory + Articus\PathHandler\MetadataProviderInterface: Articus\PathHandler\MetadataProvider\Factory\PhpAttribute + Articus\PathHandler\Handler\PluginManager: Articus\PathHandler\Handler\Factory\PluginManager + Articus\PathHandler\Consumer\PluginManager: Articus\PathHandler\Consumer\Factory\PluginManager + Articus\PathHandler\Attribute\PluginManager: Articus\PathHandler\Attribute\Factory\PluginManager + Articus\PathHandler\Producer\PluginManager: Articus\PathHandler\Producer\Factory\PluginManager + +Articus\PathHandler\RouteInjectionFactory: + paths: + '{{basePathWithoutHost}}': +{{#apiInfo}} +{{#apis}} +{{#operations}} + - {{package}}\{{classname}} +{{/operations}} +{{/apis}} +{{/apiInfo}} + +Articus\PathHandler\Handler\PluginManager: + abstract_factories: + - Laminas\ServiceManager\AbstractFactory\ConfigAbstractFactory + +#Articus\PathHandler\Consumer\PluginManager: +# factories: +# invokables: + +#Articus\PathHandler\Attribute\PluginManager: +# factories: +# invokables: + +#Articus\PathHandler\Producer\PluginManager: +# factories: +# invokables: + +Laminas\ServiceManager\AbstractFactory\ConfigAbstractFactory: +{{#apiInfo}} +{{#apis}} +{{#operations}} + {{package}}\{{classname}}: [] +{{/operations}} +{{/apis}} +{{/apiInfo}} diff --git a/modules/openapi-generator/src/main/resources/php-mezzio-ph/Factory.php.mustache b/modules/openapi-generator/src/main/resources/php-mezzio-ph/Factory.php.mustache index 68787c5fd6c..bee7ad98a78 100644 --- a/modules/openapi-generator/src/main/resources/php-mezzio-ph/Factory.php.mustache +++ b/modules/openapi-generator/src/main/resources/php-mezzio-ph/Factory.php.mustache @@ -23,20 +23,13 @@ class Factory implements FactoryInterface { public function __invoke(ContainerInterface $container, $requestedName, array $options = null): Application { - $errorMiddleware = $container->get(Middleware\InternalServerError::class); - if (!($errorMiddleware instanceof Middleware\InternalServerError)) { - throw new \LogicException(\sprintf( - 'Invalid error middleware: expecting %s, not %s.', - Middleware\InternalServerError::class, - \is_object($errorMiddleware) ? \get_class($errorMiddleware) : \gettype($errorMiddleware) - )); - } + $errorMiddleware = self::getErrorMiddleware($container); $pipeline = new MiddlewarePipe(); $runner = new RequestHandlerRunner( $pipeline, $container->get(EmitterInterface::class), $container->get(ServerRequestInterface::class), - function(\Throwable $error) use ($errorMiddleware) : ResponseInterface + static function(\Throwable $error) use ($errorMiddleware) : ResponseInterface { return $errorMiddleware->handleError($error); } @@ -55,4 +48,9 @@ class Factory implements FactoryInterface return $application; } + + protected static function getErrorMiddleware(ContainerInterface $container): Middleware\InternalServerError + { + return $container->get(Middleware\InternalServerError::class); + } } diff --git a/modules/openapi-generator/src/main/resources/php-mezzio-ph/README.md.mustache b/modules/openapi-generator/src/main/resources/php-mezzio-ph/README.md.mustache index 584fd156879..a8047005901 100644 --- a/modules/openapi-generator/src/main/resources/php-mezzio-ph/README.md.mustache +++ b/modules/openapi-generator/src/main/resources/php-mezzio-ph/README.md.mustache @@ -5,9 +5,9 @@ Generated by the [OpenAPI Generator](https://openapi-generator.tech) project. ## Overview This server stub aims to provide light, yet comprehensive structure for your API project using: -- PHP: >=7.2 +- PHP: >=7.3 - [Laminas Mezzio](https://docs.mezzio.dev/mezzio/): >=3.2 -- [Path Handler](https://github.com/Articus/PathHandler): >=0.6 +- [Path Handler](https://github.com/Articus/PathHandler): >=0.7 ## How to use All you have to do to start development is: diff --git a/modules/openapi-generator/src/main/resources/php-mezzio-ph/api.mustache b/modules/openapi-generator/src/main/resources/php-mezzio-ph/api.mustache index d44e206de6f..ec0d1df137b 100644 --- a/modules/openapi-generator/src/main/resources/php-mezzio-ph/api.mustache +++ b/modules/openapi-generator/src/main/resources/php-mezzio-ph/api.mustache @@ -43,13 +43,7 @@ class {{classname}} * @PHA\Consumer(name=PHConsumer\Json::class, mediaRange="{{{mediaType}}}") {{/consumes}} {{^isPrimitiveType}} -{{#isContainer}} - * TODO check if attribute is valid and can handle your container type - * @PHA\Attribute(name=PHAttribute\Transfer::class, options={"type":"{{{dataType}}}","objectAttr":"bodyData"}) -{{/isContainer}} -{{^isContainer}} - * @PHA\Attribute(name=PHAttribute\Transfer::class, options={"type":{{{dataType}}}::class,"objectAttr":"bodyData"}) -{{/isContainer}} + * @PHA\Attribute(name=PHAttribute\Transfer::class, options={"type":{{dataType}}::class,"objectAttr":"bodyData"}) {{/isPrimitiveType}} {{/bodyParam}} {{#produces}} @@ -61,13 +55,10 @@ class {{classname}} * @throws PHException\HttpCode 501 if the method is not implemented {{#returnType}} * -{{#returnContainer}} - * TODO check if generated return container type is valid -{{/returnContainer}} - * @return {{{returnType}}} + * @return {{returnType}} {{/returnType}} */ - public function {{operationId}}(ServerRequestInterface $request){{#returnType}}: {{#returnContainer}}array{{/returnContainer}}{{^returnContainer}}{{returnType}}{{/returnContainer}}{{/returnType}} + public function {{operationId}}(ServerRequestInterface $request){{#returnType}}: {{returnType}}{{/returnType}} { //TODO implement method {{#vendorExtensions}} @@ -78,7 +69,7 @@ class {{classname}} {{/vendorExtensions}} {{#bodyParam}} {{^isPrimitiveType}} - /** @var {{{dataType}}} $bodyData */ + /** @var {{dataType}} $bodyData */ $bodyData = $request->getAttribute("bodyData"); {{/isPrimitiveType}} {{/bodyParam}} diff --git a/modules/openapi-generator/src/main/resources/php-mezzio-ph/composer.json.mustache b/modules/openapi-generator/src/main/resources/php-mezzio-ph/composer.json.mustache index a768982234a..de46c4b20ea 100644 --- a/modules/openapi-generator/src/main/resources/php-mezzio-ph/composer.json.mustache +++ b/modules/openapi-generator/src/main/resources/php-mezzio-ph/composer.json.mustache @@ -5,13 +5,13 @@ "version": "{{artifactVersion}}", "type": "project", "require": { - "php": "^7.2", + "php": "^7.3 || ^8.0", "ext-yaml": "^2.0", "mezzio/mezzio": "^3.2", "laminas/laminas-diactoros": "^2.1", - "articus/path-handler": "^0.6", - "articus/data-transfer": "^0.4", - "articus/openapi-generator-common": "^0.1", + "articus/path-handler": "^0.7", + "articus/data-transfer": "^0.5", + "articus/openapi-generator-common": "^0.2", "doctrine/annotations": "^1.10", "psr/simple-cache": "^1.0", "laminas/laminas-config": "^3.4", diff --git a/modules/openapi-generator/src/main/resources/php-mezzio-ph/config.yml b/modules/openapi-generator/src/main/resources/php-mezzio-ph/config.yml index 1f106812353..71371becf21 100644 --- a/modules/openapi-generator/src/main/resources/php-mezzio-ph/config.yml +++ b/modules/openapi-generator/src/main/resources/php-mezzio-ph/config.yml @@ -9,10 +9,11 @@ # router: # cache: # directory: ./data/cache/PathHandler -# #Enable handler metadata cache -# metadata: -# cache: -# directory: ./data/cache/PathHandler + +#Enable handler metadata cache +#Articus\PathHandler\MetadataProvider\Annotation: +# cache: +# directory: ./data/cache/PathHandler #Enable data transfer metadata cache for DTOs #Articus\DataTransfer\MetadataProvider\Annotation: diff --git a/modules/openapi-generator/src/main/resources/php-mezzio-ph/data_transfer.yml.mustache b/modules/openapi-generator/src/main/resources/php-mezzio-ph/data_transfer.yml.mustache index c5174147c23..548c898fb9c 100644 --- a/modules/openapi-generator/src/main/resources/php-mezzio-ph/data_transfer.yml.mustache +++ b/modules/openapi-generator/src/main/resources/php-mezzio-ph/data_transfer.yml.mustache @@ -16,6 +16,10 @@ Articus\DataTransfer\Strategy\PluginManager: factories: Date: OpenAPIGenerator\Common\Strategy\Factory\MutableDate DateTime: OpenAPIGenerator\Common\Strategy\Factory\MutableDateTime + ObjectList: OpenAPIGenerator\Common\Strategy\Factory\NoArgObjectList + ObjectMap: OpenAPIGenerator\Common\Strategy\Factory\NoArgObjectMap + ScalarList: OpenAPIGenerator\Common\Strategy\Factory\ScalarList + ScalarMap: OpenAPIGenerator\Common\Strategy\Factory\ScalarMap Articus\DataTransfer\Validator\PluginManager: invokables: @@ -24,3 +28,7 @@ Articus\DataTransfer\Validator\PluginManager: QueryStringScalarArray: OpenAPIGenerator\Common\Validator\QueryStringScalarArray abstract_factories: - Articus\DataTransfer\Validator\Factory\Laminas + +validators: + invokables: + Count: Laminas\Validator\IsCountable diff --git a/modules/openapi-generator/src/main/resources/php-mezzio-ph/list_item_type.mustache b/modules/openapi-generator/src/main/resources/php-mezzio-ph/list_item_type.mustache new file mode 100644 index 00000000000..25467661433 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/php-mezzio-ph/list_item_type.mustache @@ -0,0 +1,8 @@ +{{#items +}}{{^isContainer +}}{{#isPrimitiveType}}"{{dataType}}"{{/isPrimitiveType +}}{{^isPrimitiveType}}{{dataType}}::class{{/isPrimitiveType +}}{{/isContainer +}}{{#isContainer +}}{{dataType}}::class{{/isContainer +}}{{/items}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/php-mezzio-ph/map_item_type.mustache b/modules/openapi-generator/src/main/resources/php-mezzio-ph/map_item_type.mustache new file mode 100644 index 00000000000..a58e19beca5 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/php-mezzio-ph/map_item_type.mustache @@ -0,0 +1,8 @@ +{{#additionalProperties +}}{{^isContainer +}}{{#isPrimitiveType}}"{{dataType}}"{{/isPrimitiveType +}}{{^isPrimitiveType}}{{dataType}}::class{{/isPrimitiveType +}}{{/isContainer +}}{{#isContainer +}}{{dataType}}::class{{/isContainer +}}{{/additionalProperties}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/php-mezzio-ph/model.mustache b/modules/openapi-generator/src/main/resources/php-mezzio-ph/model.mustache index 57f70bfc767..fd2a8cc6208 100644 --- a/modules/openapi-generator/src/main/resources/php-mezzio-ph/model.mustache +++ b/modules/openapi-generator/src/main/resources/php-mezzio-ph/model.mustache @@ -5,23 +5,9 @@ namespace {{package}}; use Articus\DataTransfer\Annotation as DTA; -/** -{{#description}} - * {{description}} -{{/description}} - */ -class {{classname}} -{ -{{#vars}} - /** -{{#description}} - * {{description}} -{{/description}} - * @DTA\Data(field="{{baseName}}"{{^required}}, nullable=true{{/required}}){{#vendorExtensions}}{{#internal.ze-ph.fromQuery}} -{{>model_query_var}}{{/internal.ze-ph.fromQuery}}{{/vendorExtensions}}{{#vendorExtensions}}{{^internal.ze-ph.fromQuery}} -{{>model_normal_var}}{{/internal.ze-ph.fromQuery}}{{/vendorExtensions}}{{^vendorExtensions}} -{{>model_normal_var}}{{/vendorExtensions}} * @var {{dataType}}|null - */ - public ${{name}}; -{{/vars}} -}{{/model}}{{/models}} +{{#vendorExtensions +}}{{#internal.ze-ph.fromContainer}}{{>model_container}}{{/internal.ze-ph.fromContainer +}}{{^internal.ze-ph.fromContainer}}{{>model_object}}{{/internal.ze-ph.fromContainer +}}{{/vendorExtensions +}}{{^vendorExtensions}}{{>model_object}}{{/vendorExtensions +}}{{/model}}{{/models}} diff --git a/modules/openapi-generator/src/main/resources/php-mezzio-ph/model_container.mustache b/modules/openapi-generator/src/main/resources/php-mezzio-ph/model_container.mustache new file mode 100644 index 00000000000..bbecf5ed190 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/php-mezzio-ph/model_container.mustache @@ -0,0 +1,59 @@ +/** +{{#vars +}}{{#isArray +}} * @DTA\Strategy(name="{{#isPrimitiveType}}ScalarList{{/isPrimitiveType}}{{^isPrimitiveType}}ObjectList{{/isPrimitiveType}}", options={"type":{{>list_item_type}}}) +{{#minItems}}{{^maxItems +}} * @DTA\Validator(name="Count", options={"min":{{minItems}}}, blocker=true) +{{/maxItems}}{{/minItems +}}{{^minItems}}{{#maxItems +}} * @DTA\Validator(name="Count", options={"max":{{maxItems}}}, blocker=true) +{{/maxItems}}{{/minItems +}}{{#minItems}}{{#maxItems +}} * @DTA\Validator(name="Count", options={"min":{{minItems}},"max":{{maxItems}}}, blocker=true) +{{/maxItems}}{{/minItems +}} * @DTA\Validator(name="Collection", options={"validators":{ +{{#isPrimitiveType +}} * {"name":"Scalar", "options":{"type":{{>list_item_type}}}} +{{/isPrimitiveType +}}{{#isDate +}} * {"name":"Date"} +{{/isDate +}}{{#isDateTime +}} * {"name":"Date", "options":{"format": \DateTime::RFC3339}} +{{/isDateTime +}}{{^isPrimitiveType}}{{^isDate}}{{^isDateTime +}} * {"name":"TypeCompliant", "options":{"type":{{>list_item_type}}}} +{{/isDateTime}}{{/isDate}}{{/isPrimitiveType +}} * }}) +{{/isArray +}}{{#isMap +}} * @DTA\Strategy(name="{{#isPrimitiveType}}ScalarMap{{/isPrimitiveType}}{{^isPrimitiveType}}ObjectMap{{/isPrimitiveType}}", options={"type":{{>map_item_type}}}) +{{#minProperties}}{{^maxProperties +}} * @DTA\Validator(name="Count", options={"min":{{minProperties}}}, blocker=true) +{{/maxProperties}}{{/minProperties +}}{{^minProperties}}{{#maxProperties +}} * @DTA\Validator(name="Count", options={"max":{{maxProperties}}}, blocker=true) +{{/maxProperties}}{{/minProperties +}}{{#minProperties}}{{#maxProperties +}} * @DTA\Validator(name="Count", options={"min":{{minProperties}},"max":{{maxProperties}}}, blocker=true) +{{/maxProperties}}{{/minProperties +}} * @DTA\Validator(name="Collection", options={"validators":{ +{{#isPrimitiveType +}} * {"name":"Scalar", "options":{"type":{{>map_item_type}}}} +{{/isPrimitiveType +}}{{#isDate +}} * {"name":"Date"} +{{/isDate +}}{{#isDateTime +}} * {"name":"Date", "options":{"format": \DateTime::RFC3339}} +{{/isDateTime +}}{{^isPrimitiveType}}{{^isDate}}{{^isDateTime +}} * {"name":"TypeCompliant", "options":{"type":{{>map_item_type}}}} +{{/isDateTime}}{{/isDate}}{{/isPrimitiveType +}} * }}) +{{/isMap +}}{{/vars +}} */ +class {{classname}} extends \ArrayObject +{ +} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/php-mezzio-ph/model_normal_var.mustache b/modules/openapi-generator/src/main/resources/php-mezzio-ph/model_normal_var.mustache index 33c6e46337a..fe568901f9b 100644 --- a/modules/openapi-generator/src/main/resources/php-mezzio-ph/model_normal_var.mustache +++ b/modules/openapi-generator/src/main/resources/php-mezzio-ph/model_normal_var.mustache @@ -1,64 +1,45 @@ -{{^isPrimitiveType}} -{{^isContainer}} -{{^isDate}} -{{^isDateTime}} - * @DTA\Strategy(name="Object", options={"type":{{dataType}}::class}) - * @DTA\Validator(name="TypeCompliant", options={"type":{{dataType}}::class}) -{{/isDateTime}} -{{/isDate}} -{{#isDate}} - * @DTA\Strategy(name="Date") +{{#isContainer +}} * @DTA\Strategy(name="Object", options={"type":{{internal.ze-ph.containerDataType}}::class}) + * @DTA\Validator(name="TypeCompliant", options={"type":{{internal.ze-ph.containerDataType}}::class}) +{{/isContainer +}}{{^isContainer +}}{{#isPrimitiveType +}} * @DTA\Validator(name="Scalar", options={"type":"{{dataType}}"}) +{{/isPrimitiveType +}}{{#isDate +}} * @DTA\Strategy(name="Date") * @DTA\Validator(name="Date") -{{/isDate}} -{{#isDateTime}} - * @DTA\Strategy(name="DateTime") +{{/isDate +}}{{#isDateTime +}} * @DTA\Strategy(name="DateTime") * @DTA\Validator(name="Date", options={"format": \DateTime::RFC3339}) -{{/isDateTime}} -{{/isContainer}} -{{#isContainer}} - * TODO check validator and strategy are correct and can handle container item type - * @DTA\Strategy(name="ObjectArray", options={"type":{{#items}}{{dataType}}{{/items}}::class}) - * @DTA\Validator(name="Collection", options={"validators":{ - * {"name":"TypeCompliant", "options":{"type":{{#items}}{{dataType}}{{/items}}::class}} - * }}) -{{/isContainer}} -{{/isPrimitiveType}} -{{#isPrimitiveType}} -{{#isContainer}} -{{#items}} - * TODO check validator and strategy are correct and can handle container item type - * @DTA\Validator(name="Collection", options={"validators":{ - * {"name":"Scalar", "options":{"type":"{{dataType}}"}} - * }}) -{{/items}} -{{/isContainer}} -{{^isContainer}} - * @DTA\Validator(name="Scalar", options={"type":"{{dataType}}"}) -{{/isContainer}} -{{/isPrimitiveType}} -{{#hasValidation}} -{{#minLength}} -{{#maxLength}} - * @DTA\Validator(name="StringLength", options={"min":{{minLength}}, "max":{{maxLength}}}) -{{/maxLength}} -{{/minLength}} -{{^minLength}} -{{#maxLength}} - * @DTA\Validator(name="StringLength", options={"max":{{maxLength}}}) -{{/maxLength}} -{{/minLength}} -{{#minLength}} -{{^maxLength}} - * @DTA\Validator(name="StringLength", options={"min":{{minLength}}}) -{{/maxLength}} -{{/minLength}} -{{#minimum}} - * @DTA\Validator(name="GreaterThan", options={"min":{{minimum}}{{^exclusiveMinimum}}, "inclusive":true{{/exclusiveMinimum}}}) -{{/minimum}} -{{#maximum}} - * @DTA\Validator(name="LessThan", options={"max":{{maximum}}{{^exclusiveMaximum}}, "inclusive":true{{/exclusiveMaximum}}}) -{{/maximum}} -{{#pattern}} - * @DTA\Validator(name="Regex", options={"pattern":"{{{pattern}}}"}) -{{/pattern}} -{{/hasValidation}} \ No newline at end of file +{{/isDateTime +}}{{^isPrimitiveType +}}{{^isDate +}}{{^isDateTime +}} * @DTA\Strategy(name="Object", options={"type":{{dataType}}::class}) + * @DTA\Validator(name="TypeCompliant", options={"type":{{dataType}}::class}) +{{/isDateTime +}}{{/isDate +}}{{/isPrimitiveType +}}{{/isContainer +}}{{#hasValidation +}}{{#minLength}}{{#maxLength +}} * @DTA\Validator(name="StringLength", options={"min":{{minLength}}, "max":{{maxLength}}}) +{{/maxLength}}{{/minLength +}}{{^minLength}}{{#maxLength +}} * @DTA\Validator(name="StringLength", options={"max":{{maxLength}}}) +{{/maxLength}}{{/minLength +}}{{#minLength}}{{^maxLength +}} * @DTA\Validator(name="StringLength", options={"min":{{minLength}}}) +{{/maxLength}}{{/minLength +}}{{#minimum +}} * @DTA\Validator(name="GreaterThan", options={"min":{{minimum}}{{^exclusiveMinimum}}, "inclusive":true{{/exclusiveMinimum}}}) +{{/minimum +}}{{#maximum +}} * @DTA\Validator(name="LessThan", options={"max":{{maximum}}{{^exclusiveMaximum}}, "inclusive":true{{/exclusiveMaximum}}}) +{{/maximum +}}{{#pattern +}} * @DTA\Validator(name="Regex", options={"pattern":"{{{pattern}}}"}) +{{/pattern +}}{{/hasValidation}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/php-mezzio-ph/model_object.mustache b/modules/openapi-generator/src/main/resources/php-mezzio-ph/model_object.mustache new file mode 100644 index 00000000000..2e7d61fde45 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/php-mezzio-ph/model_object.mustache @@ -0,0 +1,24 @@ +/** +{{#description +}} * {{description}} +{{/description +}} */ +class {{classname}} +{ +{{#vars +}} /** +{{#description +}} * {{description}} +{{/description +}} * @DTA\Data(field="{{baseName}}"{{^required}}, nullable=true{{/required}}) +{{#vendorExtensions +}}{{#internal.ze-ph.fromQuery}}{{>model_query_var}}{{/internal.ze-ph.fromQuery +}}{{^internal.ze-ph.fromQuery}}{{>model_normal_var}}{{/internal.ze-ph.fromQuery +}}{{/vendorExtensions +}}{{^vendorExtensions}}{{>model_normal_var}}{{/vendorExtensions +}} * @var {{dataType}}|null + */ + public ${{name}}; + +{{/vars +}}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/php-mezzio-ph/model_query_var.mustache b/modules/openapi-generator/src/main/resources/php-mezzio-ph/model_query_var.mustache index 27f0a72c955..deaf0e37049 100644 --- a/modules/openapi-generator/src/main/resources/php-mezzio-ph/model_query_var.mustache +++ b/modules/openapi-generator/src/main/resources/php-mezzio-ph/model_query_var.mustache @@ -1,52 +1,51 @@ -{{^isPrimitiveType}} -{{^isContainer}} -{{#isDate}} - * @DTA\Strategy(name="Date") - * @DTA\Validator(name="Date") -{{/isDate}} -{{#isDateTime}} - * @DTA\Strategy(name="DateTime") - * @DTA\Validator(name="Date", options={"format": \DateTime::RFC3339}) -{{/isDateTime}} -{{/isContainer}} -{{#isContainer}} - * TODO add validator(s) and strategy for {{dataType}} and collection format {{internal.ze-ph.collectionFormat}} -{{/isContainer}} -{{/isPrimitiveType}} -{{#isPrimitiveType}} -{{#isContainer}} - * TODO check validator and strategy are correct and can handle container item type - * @DTA\Strategy(name="QueryStringScalarArray", options={"type":"{{#items}}{{dataType}}{{/items}}", "format":"{{internal.ze-ph.collectionFormat}}"}) - * @DTA\Validator(name="QueryStringScalarArray", options={"type":"{{#items}}{{dataType}}{{/items}}", "format":"{{internal.ze-ph.collectionFormat}}"{{#minItems}}, "min_items":{{minItems}}{{/minItems}}{{#maxItems}}, "max_items":{{maxItems}}{{/maxItems}}}) -{{/isContainer}} -{{^isContainer}} - * @DTA\Strategy(name="QueryStringScalar", options={"type":"{{dataType}}"}) +{{#isArray +}}{{#isPrimitiveType +}} * @DTA\Strategy(name="QueryStringScalarArray", options={"type":{{>list_item_type}}, "format":"{{internal.ze-ph.collectionFormat}}"}) + * @DTA\Validator(name="QueryStringScalarArray", options={"type":{{>list_item_type}}, "format":"{{internal.ze-ph.collectionFormat}}"{{#minItems}}, "min_items":{{minItems}}{{/minItems}}{{#maxItems}}, "max_items":{{maxItems}}{{/maxItems}}}) +{{/isPrimitiveType +}}{{^isPrimitiveType +}} * TODO add validator(s) and strategy for list of {{>list_item_type}} and collection format {{internal.ze-ph.collectionFormat}} inside query string +{{/isPrimitiveType +}}{{/isArray +}}{{#isMap +}} * TODO add validator(s) and strategy for map of {{>map_item_type}} and collection format {{internal.ze-ph.collectionFormat}} inside query string +{{/isMap +}}{{^isContainer +}}{{#isPrimitiveType +}} * @DTA\Strategy(name="QueryStringScalar", options={"type":"{{dataType}}"}) * @DTA\Validator(name="QueryStringScalar", options={"type":"{{dataType}}"}) -{{/isContainer}} -{{/isPrimitiveType}} -{{#hasValidation}} -{{#minLength}} -{{#maxLength}} - * @DTA\Validator(name="StringLength", options={"min":{{minLength}}, "max":{{maxLength}}}) -{{/maxLength}} -{{/minLength}} -{{^minLength}} -{{#maxLength}} - * @DTA\Validator(name="StringLength", options={"max":{{maxLength}}}) -{{/maxLength}} -{{/minLength}} -{{#minLength}} -{{^maxLength}} - * @DTA\Validator(name="StringLength", options={"min":{{minLength}}}) -{{/maxLength}} -{{/minLength}} -{{#minimum}} - * @DTA\Validator(name="GreaterThan", options={"min":{{minimum}}{{^exclusiveMinimum}}, "inclusive":true{{/exclusiveMinimum}}}) -{{/minimum}} -{{#maximum}} - * @DTA\Validator(name="LessThan", options={"max":{{maximum}}{{^exclusiveMaximum}}, "inclusive":true{{/exclusiveMaximum}}}) -{{/maximum}} -{{#pattern}} - * @DTA\Validator(name="Regex", options={"pattern":"{{{pattern}}}"}) -{{/pattern}} -{{/hasValidation}} \ No newline at end of file +{{/isPrimitiveType +}}{{#isDate +}} * @DTA\Strategy(name="Date") + * @DTA\Validator(name="Date") +{{/isDate +}}{{#isDateTime +}} * @DTA\Strategy(name="DateTime") + * @DTA\Validator(name="Date", options={"format": \DateTime::RFC3339}) +{{/isDateTime +}}{{^isPrimitiveType +}}{{^isDate}}{{^isDateTime +}} * TODO add validator(s) and strategy for {{dataType}} inside query string +{{/isDateTime}}{{/isDate +}}{{/isPrimitiveType +}}{{/isContainer +}}{{#hasValidation +}}{{#minLength}}{{#maxLength +}} * @DTA\Validator(name="StringLength", options={"min":{{minLength}}, "max":{{maxLength}}}) +{{/maxLength}}{{/minLength +}}{{^minLength}}{{#maxLength +}} * @DTA\Validator(name="StringLength", options={"max":{{maxLength}}}) +{{/maxLength}}{{/minLength +}}{{#minLength}}{{^maxLength +}} * @DTA\Validator(name="StringLength", options={"min":{{minLength}}}) +{{/maxLength}}{{/minLength +}}{{#minimum +}} * @DTA\Validator(name="GreaterThan", options={"min":{{minimum}}{{^exclusiveMinimum}}, "inclusive":true{{/exclusiveMinimum}}}) +{{/minimum +}}{{#maximum +}} * @DTA\Validator(name="LessThan", options={"max":{{maximum}}{{^exclusiveMaximum}}, "inclusive":true{{/exclusiveMaximum}}}) +{{/maximum +}}{{#pattern +}} * @DTA\Validator(name="Regex", options={"pattern":"{{{pattern}}}"}) +{{/pattern +}}{{/hasValidation}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/php-mezzio-ph/path_handler.yml.mustache b/modules/openapi-generator/src/main/resources/php-mezzio-ph/path_handler.yml.mustache index dd01611f359..1f9167a0fa4 100644 --- a/modules/openapi-generator/src/main/resources/php-mezzio-ph/path_handler.yml.mustache +++ b/modules/openapi-generator/src/main/resources/php-mezzio-ph/path_handler.yml.mustache @@ -1,8 +1,13 @@ dependencies: factories: - Mezzio\Router\RouterInterface: Articus\PathHandler\RouteInjection\Factory + Mezzio\Router\RouterInterface: Articus\PathHandler\RouteInjectionFactory + Articus\PathHandler\MetadataProviderInterface: Articus\PathHandler\MetadataProvider\Factory\Annotation + Articus\PathHandler\Handler\PluginManager: Articus\PathHandler\Handler\Factory\PluginManager + Articus\PathHandler\Consumer\PluginManager: Articus\PathHandler\Consumer\Factory\PluginManager + Articus\PathHandler\Attribute\PluginManager: Articus\PathHandler\Attribute\Factory\PluginManager + Articus\PathHandler\Producer\PluginManager: Articus\PathHandler\Producer\Factory\PluginManager -Articus\PathHandler\RouteInjection\Factory: +Articus\PathHandler\RouteInjectionFactory: paths: '{{basePathWithoutHost}}': {{#apiInfo}} @@ -12,18 +17,22 @@ Articus\PathHandler\RouteInjection\Factory: {{/operations}} {{/apis}} {{/apiInfo}} - handlers: - abstract_factories: - - Laminas\ServiceManager\AbstractFactory\ConfigAbstractFactory -# consumers: -# factories: -# invokables: -# attributes: -# factories: -# invokables: -# producers: -# factories: -# invokables: + +Articus\PathHandler\Handler\PluginManager: + abstract_factories: + - Laminas\ServiceManager\AbstractFactory\ConfigAbstractFactory + +#Articus\PathHandler\Consumer\PluginManager: +# factories: +# invokables: + +#Articus\PathHandler\Attribute\PluginManager: +# factories: +# invokables: + +#Articus\PathHandler\Producer\PluginManager: +# factories: +# invokables: Laminas\ServiceManager\AbstractFactory\ConfigAbstractFactory: {{#apiInfo}} diff --git a/modules/openapi-generator/src/main/resources/powershell/api.mustache b/modules/openapi-generator/src/main/resources/powershell/api.mustache index f5840636bf6..14a18de62e0 100644 --- a/modules/openapi-generator/src/main/resources/powershell/api.mustache +++ b/modules/openapi-generator/src/main/resources/powershell/api.mustache @@ -90,7 +90,7 @@ function {{{vendorExtensions.x-powershell-method-name}}} { if (!$) { throw "Error! The required parameter `` missing when calling ." } - $LocalVarUri = $LocalVarUri.replace('{}', $) + $LocalVarUri = $LocalVarUri.replace('{}', [System.Web.HTTPUtility]::UrlEncode($)) <={{ }}=> 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 b17371ad1e3..7d45f071b1e 100644 --- a/modules/openapi-generator/src/main/resources/powershell/api_client.mustache +++ b/modules/openapi-generator/src/main/resources/powershell/api_client.mustache @@ -211,6 +211,10 @@ function DeserializeResponse { [string[]]$ContentTypes ) + If ($ContentTypes -eq $null) { + $ContentTypes = [string[]]@() + } + If ([string]::IsNullOrEmpty($ReturnType) -and $ContentTypes.Count -eq 0) { # void response return $Response } Elseif ($ReturnType -match '\[\]$') { # array diff --git a/modules/openapi-generator/src/main/resources/powershell/api_doc.mustache b/modules/openapi-generator/src/main/resources/powershell/api_doc.mustache index 7903ec98afe..2f5ec53c9e2 100644 --- a/modules/openapi-generator/src/main/resources/powershell/api_doc.mustache +++ b/modules/openapi-generator/src/main/resources/powershell/api_doc.mustache @@ -56,14 +56,29 @@ Set-ConfigurationHttpSigning $httpSigningParams {{/authMethods}} {{/hasAuthMethods}} {{#allParams}} +{{^isArray}} +{{#isModel}} +{{{vendorExtensions.x-powershell-example}}} # {{{dataType}}} | {{{description}}}{{^required}} (optional){{/required}}{{#defaultValue}} (default to {{{.}}}){{/defaultValue}} +{{/isModel}} +{{^isModel}} ${{paramName}} = {{{vendorExtensions.x-powershell-example}}} # {{{dataType}}} | {{{description}}}{{^required}} (optional){{/required}}{{#defaultValue}} (default to {{{.}}}){{/defaultValue}} +{{/isModel}} +{{/isArray}} +{{#isArray}} +{{#items.isModel}} +{{{vendorExtensions.x-powershell-example}}} # {{{dataType}}} | {{{description}}}{{^required}} (optional){{/required}}{{#defaultValue}} (default to {{{.}}}){{/defaultValue}} +{{/items.isModel}} +{{^items.isModel}} +${{paramName}} = {{{vendorExtensions.x-powershell-example}}} # {{{dataType}}} | {{{description}}}{{^required}} (optional){{/required}}{{#defaultValue}} (default to {{{.}}}){{/defaultValue}} +{{/items.isModel}} +{{/isArray}} {{/allParams}} {{#summary}} # {{{.}}} {{/summary}} try { - $Result = {{{vendorExtensions.x-powershell-method-name}}}{{#allParams}} -{{paramName}} ${{paramName}}{{/allParams}} + $Result = {{{vendorExtensions.x-powershell-method-name}}}{{#allParams}} -{{paramName}} ${{paramName}}{{/allParams}} } catch { Write-Host ("Exception occured when calling {{{vendorExtensions.x-powershell-method-name}}}: {0}" -f ($_.ErrorDetails | ConvertFrom-Json)) Write-Host ("Response headers: {0}" -f ($_.Exception.Response.Headers | ConvertTo-Json)) diff --git a/modules/openapi-generator/src/main/resources/python-fastapi/.flake8.mustache b/modules/openapi-generator/src/main/resources/python-fastapi/.flake8.mustache new file mode 100644 index 00000000000..9e008c5bb19 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python-fastapi/.flake8.mustache @@ -0,0 +1,3 @@ +[flake8] +max-line-length = 88 +exclude = .git,__pycache__,__init__.py,.mypy_cache,.pytest_cache,.venv diff --git a/modules/openapi-generator/src/main/resources/python-fastapi/Dockerfile.mustache b/modules/openapi-generator/src/main/resources/python-fastapi/Dockerfile.mustache new file mode 100644 index 00000000000..b66458eb417 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python-fastapi/Dockerfile.mustache @@ -0,0 +1,30 @@ +FROM python:3.7 AS builder + +WORKDIR /usr/src/app + +RUN python3 -m venv /venv +ENV PATH="/venv/bin:$PATH" + +RUN pip install --upgrade pip + +COPY . . +RUN pip install --no-cache-dir . + + +FROM python:3.7 AS test_runner +WORKDIR /tmp +COPY --from=builder /venv /venv +COPY --from=builder /usr/src/app/tests tests +ENV PATH=/venv/bin:$PATH + +# install test dependencies +RUN pip install pytest + +# run tests +RUN pytest tests + + +FROM python:3.7 AS service +WORKDIR /root/app/site-packages +COPY --from=test_runner /venv /venv +ENV PATH=/venv/bin:$PATH diff --git a/modules/openapi-generator/src/main/resources/python-fastapi/README.mustache b/modules/openapi-generator/src/main/resources/python-fastapi/README.mustache new file mode 100644 index 00000000000..c426a965f0f --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python-fastapi/README.mustache @@ -0,0 +1,41 @@ +# OpenAPI generated FastAPI server + +This Python package is automatically generated by the [OpenAPI Generator](https://openapi-generator.tech) project: + +- API version: {{appVersion}} +{{^hideGenerationTimestamp}} +- Build date: {{generatedDate}} +{{/hideGenerationTimestamp}} +- Build package: {{generatorClass}} + +## Requirements. + +Python >= 3.7 + +## Installation & Usage + +To run the server, please execute the following from the root directory: + +```bash +pip3 install -r requirements.txt +uvicorn main:app --host 0.0.0.0 --port {{serverPort}} +``` + +and open your browser at `http://localhost:{{serverPort}}/docs/` to see the docs. + +## Running with Docker + +To run the server on a Docker container, please execute the following from the root directory: + +```bash +docker-compose up --build +``` + +## Tests + +To run the tests: + +```bash +pip3 install pytest +PYTHONPATH=src pytest tests +``` diff --git a/modules/openapi-generator/src/main/resources/python-fastapi/__init__.mustache b/modules/openapi-generator/src/main/resources/python-fastapi/__init__.mustache new file mode 100644 index 00000000000..e69de29bb2d diff --git a/modules/openapi-generator/src/main/resources/python-fastapi/api.mustache b/modules/openapi-generator/src/main/resources/python-fastapi/api.mustache new file mode 100644 index 00000000000..04b95fb104a --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python-fastapi/api.mustache @@ -0,0 +1,64 @@ +# coding: utf-8 + +from typing import Dict, List # noqa: F401 + +from fastapi import ( # noqa: F401 + APIRouter, + Body, + Cookie, + Depends, + Form, + Header, + Path, + Query, + Response, + Security, + status, +) + +from {{modelPackage}}.extra_models import TokenModel # noqa: F401 +{{#imports}} +{{import}} +{{/imports}} +{{#securityImports.0}}from {{packageName}}.security_api import {{#securityImports}}get_token_{{.}}{{^-last}}, {{/-last}}{{/securityImports}}{{/securityImports.0}} + +router = APIRouter() + + +{{#operations}} +{{#operation}} +@router.{{#lambda.lowercase}}{{httpMethod}}{{/lambda.lowercase}}( + "{{path}}", + responses={ + {{#responses}} + {{code}}: {{=<% %>=}}{<%#dataType%>"model": <%dataType%>, "description": "<%message%>"<%/dataType%><%^dataType%>"description": "<%message%>"<%/dataType%>}<%={{ }}=%>, + {{/responses}} + }, + tags=[{{#tags}}"{{name}}"{{^-last}},{{/-last}}{{/tags}}], + {{#summary}} + summary="{{summary}}", + {{/summary}} + {{#description}} + description = "{{description}}", + {{/description}} +) +async def {{operationId}}( + {{#allParams}} + {{>endpoint_argument_definition}}, + {{/allParams}} + {{#hasAuthMethods}} + {{#authMethods}} + token_{{name}}: TokenModel = Security( + get_token_{{name}}{{#isOAuth}}, scopes=[{{#scopes}}"{{scope}}"{{^-last}}, {{/-last}}{{/scopes}}]{{/isOAuth}} + ), + {{/authMethods}} + {{/hasAuthMethods}} +) -> {{#returnType}}{{.}}{{/returnType}}{{^returnType}}None{{/returnType}}: + {{#notes}}"""{{.}}""" + ...{{/notes}}{{^notes}}...{{/notes}} +{{^-last}} + + +{{/-last}} +{{/operation}} +{{/operations}} diff --git a/modules/openapi-generator/src/main/resources/python-fastapi/api_test.mustache b/modules/openapi-generator/src/main/resources/python-fastapi/api_test.mustache new file mode 100644 index 00000000000..5a81aa32c60 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python-fastapi/api_test.mustache @@ -0,0 +1,54 @@ +# coding: utf-8 + +from fastapi.testclient import TestClient + +{{#vendorExtensions.x-skip-test}} +import pytest +{{/vendorExtensions.x-skip-test}} + +{{#imports}}{{import}} # noqa: F401 +{{/imports}} + +{{#operations}} +{{#operation}} + +{{#vendorExtensions.x-skip-test}} +@pytest.mark.skip("{{reason}}") +{{/vendorExtensions.x-skip-test}} +def test_{{operationId}}(client: TestClient): + """Test case for {{{operationId}}} + + {{{summary}}} + """ + {{#bodyParam}} + {{paramName}} = {{#isContainer}}[{{/isContainer}}{{{example}}}{{#isContainer}}]{{/isContainer}} + {{/bodyParam}} + {{#queryParams}} + {{#-first}}params = [{{/-first}}("{{paramName}}", {{{example}}}){{^-last}}, {{/-last}}{{#-last}}]{{/-last}}{{/queryParams}} + headers = {{=<% %>=}}{<%#headerParams%><%={{ }}=%> + "{{paramName}}": {{{example}}},{{/headerParams}}{{#authMethods}} + {{#isOAuth}}"Authorization": "Bearer special-key",{{/isOAuth}}{{#isApiKey}}"{{name}}": "special-key",{{/isApiKey}}{{#isBasicBasic}}"Authorization": "BasicZm9vOmJhcg==",{{/isBasicBasic}}{{#isBasicBearer}}"Authorization": "Bearer special-key",{{/isBasicBearer}}{{/authMethods}} + } + {{#formParams}} + {{#-first}} + data = { + {{/-first}} + "{{paramName}}": {{{example}}}{{^-last}},{{/-last}} + {{#-last}} + } + {{/-last}} + {{/formParams}} + response = client.request( + "{{httpMethod}}", + "{{{path}}}"{{#pathParams}}{{#-first}}.format({{/-first}}{{baseName}}={{{example}}}{{^-last}}, {{/-last}}{{#-last}}){{/-last}}{{/pathParams}}, + headers=headers,{{#bodyParam}} + json={{paramName}},{{/bodyParam}}{{#formParams}}{{#-first}} + data=data,{{/-first}}{{/formParams}}{{#queryParams}}{{#-first}} + params=params,{{/-first}}{{/queryParams}} + ) + + # uncomment below to assert the status code of the HTTP response + #assert response.status_code == 200 + +{{/operation}} +{{/operations}} diff --git a/modules/openapi-generator/src/main/resources/python-fastapi/conftest.mustache b/modules/openapi-generator/src/main/resources/python-fastapi/conftest.mustache new file mode 100644 index 00000000000..e096833deba --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python-fastapi/conftest.mustache @@ -0,0 +1,17 @@ +import pytest +from fastapi import FastAPI +from fastapi.testclient import TestClient + +from {{packageName}}.main import app as application + + +@pytest.fixture +def app() -> FastAPI: + application.dependency_overrides = {} + + return application + + +@pytest.fixture +def client(app) -> TestClient: + return TestClient(app) diff --git a/modules/openapi-generator/src/main/resources/python-fastapi/docker-compose.mustache b/modules/openapi-generator/src/main/resources/python-fastapi/docker-compose.mustache new file mode 100644 index 00000000000..b4ffa002917 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python-fastapi/docker-compose.mustache @@ -0,0 +1,9 @@ +version: '3.6' +services: + service: + build: + context: . + target: service + ports: + - "{{serverPort}}:{{serverPort}}" + command: uvicorn {{packageName}}.main:app --host 0.0.0.0 --port {{serverPort}} 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 new file mode 100644 index 00000000000..c4bace9973d --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python-fastapi/endpoint_argument_definition.mustache @@ -0,0 +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}}{{^defaultValue}}None{{/defaultValue}}, description="{{description}}"{{#isLong}}{{#minimum}}, ge={{minimum}}{{/minimum}}{{#maximum}}, le={{maximum}}{{/maximum}}{{/isLong}}{{#isInteger}}{{#minimum}}, ge={{minimum}}{{/minimum}}{{#maximum}}, le={{maximum}}{{/maximum}}{{/isInteger}}{{#pattern}}, regex=r"{{pattern}}"{{/pattern}}{{#minLength}}, min_length={{minLength}}{{/minLength}}{{#maxLength}}, max_length={{maxLength}}{{/maxLength}}) \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/python-fastapi/extra_models.mustache b/modules/openapi-generator/src/main/resources/python-fastapi/extra_models.mustache new file mode 100644 index 00000000000..a3a283fb842 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python-fastapi/extra_models.mustache @@ -0,0 +1,8 @@ +# coding: utf-8 + +from pydantic import BaseModel + +class TokenModel(BaseModel): + """Defines a token model.""" + + sub: str diff --git a/modules/openapi-generator/src/main/resources/python-fastapi/gitignore.mustache b/modules/openapi-generator/src/main/resources/python-fastapi/gitignore.mustache new file mode 100644 index 00000000000..a81c8ee1219 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python-fastapi/gitignore.mustache @@ -0,0 +1,138 @@ +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# 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/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py,cover +.hypothesis/ +.pytest_cache/ +cover/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +.pybuilder/ +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +# For a library or package, you might want to ignore these files since the code is +# intended to run in multiple environments; otherwise, check them in: +# .python-version + +# pipenv +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if having platform-specific dependencies or dependencies +# having no cross-platform support, pipenv may install dependencies that don't work, or not +# install all needed dependencies. +#Pipfile.lock + +# PEP 582; used by e.g. github.com/David-OConnor/pyflow +__pypackages__/ + +# Celery stuff +celerybeat-schedule +celerybeat.pid + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ + +# pytype static type analyzer +.pytype/ + +# Cython debug symbols +cython_debug/ diff --git a/modules/openapi-generator/src/main/resources/python-fastapi/main.mustache b/modules/openapi-generator/src/main/resources/python-fastapi/main.mustache new file mode 100644 index 00000000000..7112b271978 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python-fastapi/main.mustache @@ -0,0 +1,23 @@ +# coding: utf-8 + +{{>partial_header}} + +from fastapi import FastAPI + +{{#apiInfo}} +{{#apis}} +from {{apiPackage}}.{{classFilename}} import router as {{classname}}Router +{{/apis}} +{{/apiInfo}} + +app = FastAPI( + title="{{appName}}", + description="{{appDescription}}", + version="{{appVersion}}", +) + +{{#apiInfo}} +{{#apis}} +app.include_router({{classname}}Router) +{{/apis}} +{{/apiInfo}} diff --git a/modules/openapi-generator/src/main/resources/python-fastapi/model.mustache b/modules/openapi-generator/src/main/resources/python-fastapi/model.mustache new file mode 100644 index 00000000000..65d40b93482 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python-fastapi/model.mustache @@ -0,0 +1,76 @@ +# coding: utf-8 + +from __future__ import annotations +from datetime import date, datetime # noqa: F401 + +import re # noqa: F401 +from typing import Any, Dict, List, Optional # noqa: F401 + +from pydantic import AnyUrl, BaseModel, EmailStr, validator # noqa: F401 +{{#models}} +{{#model}} +{{#pyImports}} +{{import}} +{{/pyImports}} +{{/model}} +{{/models}} + + +{{#models}} +{{#model}} +class {{classname}}(BaseModel): + """NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + + Do not edit the class manually. + + {{classname}} - a model defined in OpenAPI + + {{#vars}} + {{name}}: The {{name}} of this {{classname}}{{^required}} [Optional]{{/required}}. + {{/vars}} + """ + +{{#vars}} + {{name}}: {{#required}}{{>model_field_type}}{{/required}}{{^required}}Optional[{{>model_field_type}}] = None{{/required}} +{{/vars}} +{{#vars}} +{{#maximum}} + + @validator("{{name}}") + def {{name}}_max(cls, value): + assert value <= {{maximum}} + return value +{{/maximum}} +{{#minimum}} + + @validator("{{name}}") + def {{name}}_min(cls, value): + assert value >= {{minimum}} + return value +{{/minimum}} +{{#minLength}} + + @validator("{{name}}") + def {{name}}_min_length(cls, value): + assert len(value) >= {{minLength}} + return value +{{/minLength}} +{{#maxLength}} + + @validator("{{name}}") + def {{name}}_max_length(cls, value): + assert len(value) <= {{maxLength}} + return value +{{/maxLength}} +{{#pattern}} + + @validator("{{name}}") + def {{name}}_pattern(cls, value): + assert value is not None and re.match(r"{{pattern}}", value) + return value +{{/pattern}} +{{/vars}} +{{/model}} +{{/models}} + +{{classname}}.update_forward_refs() diff --git a/modules/openapi-generator/src/main/resources/python-fastapi/model_field_type.mustache b/modules/openapi-generator/src/main/resources/python-fastapi/model_field_type.mustache new file mode 100644 index 00000000000..a27dc7e87fe --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python-fastapi/model_field_type.mustache @@ -0,0 +1 @@ +{{#isEmail}}EmailStr{{/isEmail}}{{#isUri}}AnyUrl{{/isUri}}{{#isFreeFormObject}}Dict[str, Any]{{/isFreeFormObject}}{{^isEmail}}{{^isUri}}{{^isFreeFormObject}}{{dataType}}{{/isFreeFormObject}}{{/isUri}}{{/isEmail}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/python-fastapi/openapi.mustache b/modules/openapi-generator/src/main/resources/python-fastapi/openapi.mustache new file mode 100644 index 00000000000..51ebafb0187 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python-fastapi/openapi.mustache @@ -0,0 +1 @@ +{{{openapi-yaml}}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/python-fastapi/param_type.mustache b/modules/openapi-generator/src/main/resources/python-fastapi/param_type.mustache new file mode 100644 index 00000000000..d97c018015f --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python-fastapi/param_type.mustache @@ -0,0 +1 @@ +{{#isString}}str{{/isString}}{{#isInteger}}int{{/isInteger}}{{#isLong}}int{{/isLong}}{{#isFloat}}float{{/isFloat}}{{#isDouble}}float{{/isDouble}}{{#isByteArray}}str{{/isByteArray}}{{#isBinary}}str{{/isBinary}}{{#isBoolean}}bool{{/isBoolean}}{{#isDate}}str{{/isDate}}{{#isDateTime}}str{{/isDateTime}}{{#isModel}}{{dataType}}{{/isModel}}{{#isContainer}}{{dataType}}{{/isContainer}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/python-fastapi/partial_header.mustache b/modules/openapi-generator/src/main/resources/python-fastapi/partial_header.mustache new file mode 100644 index 00000000000..62e28acde9b --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python-fastapi/partial_header.mustache @@ -0,0 +1,17 @@ +""" +{{#appName}} + {{{appName}}} +{{/appName}} + +{{#appDescription}} + {{{appDescription}}} +{{/appDescription}} + + {{#version}} + The version of the OpenAPI document: {{{version}}} + {{/version}} + {{#infoEmail}} + Contact: {{{infoEmail}}} + {{/infoEmail}} + Generated by: https://openapi-generator.tech +""" diff --git a/modules/openapi-generator/src/main/resources/python-fastapi/pyproject_toml.mustache b/modules/openapi-generator/src/main/resources/python-fastapi/pyproject_toml.mustache new file mode 100644 index 00000000000..c2826df3020 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python-fastapi/pyproject_toml.mustache @@ -0,0 +1,30 @@ +[build-system] +requires = ["setuptools", "wheel"] +build-backend = "setuptools.build_meta" + +[tool.black] +line-length = 88 +exclude = ''' +( + /( + \.eggs # exclude a few common directories in the + | \.git # root of the project + | \.hg + | \.mypy_cache + | \.tox + | \.venv + | _build + | buck-out + | build + | dist + )/ +) +''' + +[tool.isort] +profile = "black" +skip = [ + '.eggs', '.git', '.hg', '.mypy_cache', '.nox', '.pants.d', '.tox', + '.venv', '_build', 'buck-out', 'build', 'dist', 'node_modules', 'venv', +] +skip_gitignore = true diff --git a/modules/openapi-generator/src/main/resources/python-fastapi/requirements.mustache b/modules/openapi-generator/src/main/resources/python-fastapi/requirements.mustache new file mode 100644 index 00000000000..ce66f96d42c --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python-fastapi/requirements.mustache @@ -0,0 +1,36 @@ +aiofiles==0.5.0 +aniso8601==7.0.0 +async-exit-stack==1.0.1 +async-generator==1.10 +certifi==2020.12.5 +chardet==4.0.0 +click==7.1.2 +dnspython==2.1.0 +email-validator==1.1.2 +fastapi==0.65.1 +graphene==2.1.8 +graphql-core==2.3.2 +graphql-relay==2.0.1 +h11==0.12.0 +httptools==0.1.2 +idna==2.10 +itsdangerous==1.1.0 +Jinja2==2.11.3 +MarkupSafe==2.0.1 +orjson==3.5.2 +promise==2.3 +pydantic==1.8.2 +python-dotenv==0.17.1 +python-multipart==0.0.5 +PyYAML==5.4.1 +requests==2.25.1 +Rx==1.6.1 +six==1.16.0 +starlette==0.14.2 +typing-extensions==3.10.0.0 +ujson==4.0.2 +urllib3==1.26.4 +uvicorn==0.13.4 +uvloop==0.14.0 +watchgod==0.7 +websockets==8.1 diff --git a/modules/openapi-generator/src/main/resources/python-fastapi/security_api.mustache b/modules/openapi-generator/src/main/resources/python-fastapi/security_api.mustache new file mode 100644 index 00000000000..4fda1a8f91d --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python-fastapi/security_api.mustache @@ -0,0 +1,157 @@ +# coding: utf-8 + +from typing import List + +from fastapi import Depends, Security # noqa: F401 +from fastapi.openapi.models import OAuthFlowImplicit, OAuthFlows # noqa: F401 +from fastapi.security import ( # noqa: F401 + HTTPAuthorizationCredentials, + HTTPBasic, + HTTPBasicCredentials, + HTTPBearer, + OAuth2, + OAuth2AuthorizationCodeBearer, + OAuth2PasswordBearer, + SecurityScopes, +) +from fastapi.security.api_key import APIKeyCookie, APIKeyHeader, APIKeyQuery # noqa: F401 + +from {{modelPackage}}.extra_models import TokenModel + +{{#authMethods}} +{{#isOAuth}} +{{#isPassword}} +oauth2_password = OAuth2PasswordBearer( + tokenUrl="{{tokenUrl}}", + scopes={ +{{#scopes}} + "{{scope}}": "{{description}}", +{{/scopes}} + } +) +{{/isPassword}} +{{#isCode}} +oauth2_code = OAuth2AuthorizationCodeBearer( + authorizationUrl="{{authorizationUrl}}", + tokenUrl="{{tokenUrl}}", + refreshUrl="{{refreshUrl}}", + scopes={ +{{#scopes}} + "{{scope}}": "{{description}}", +{{/scopes}} + } +) +{{/isCode}} +{{#isImplicit}} +oauth2_implicit = OAuth2( + flows=OAuthFlows( + implicit=OAuthFlowImplicit( + authorizationUrl="{{authorizationUrl}}", + scopes={ +{{#scopes}} + "{{scope}}": "{{description}}", +{{/scopes}} + } + ) + ) +) +{{/isImplicit}} + + +def get_token_{{name}}( + security_scopes: SecurityScopes, token: str = Depends(oauth2_{{#isPassword}}password{{/isPassword}}{{#isCode}}code{{/isCode}}{{#isImplicit}}implicit{{/isImplicit}}) +) -> TokenModel: + """ + Validate and decode token. + + :param token Token provided by Authorization header + :type token: str + :return: Decoded token information or None if token is invalid + :rtype: TokenModel | None + """ + + ... + + +def validate_scope_{{name}}( + required_scopes: SecurityScopes, token_scopes: List[str] +) -> bool: + """ + 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 False + +{{/isOAuth}} +{{#isApiKey}} + +def get_token_{{name}}( + {{#isKeyInHeader}}token_api_key_header: str = Security( + APIKeyHeader(name="{{keyParamName}}", auto_error=False) + ),{{/isKeyInHeader}}{{#isKeyInCookie}} + token_api_key_cookie: str = Security( + APIKeyCookie(name="{{keyParamName}}", auto_error=False) + ),{{/isKeyInCookie}}{{#isKeyInQuery}} + token_api_key_query: str = Security( + APIKeyQuery(name="{{keyParamName}}", auto_error=False) + ),{{/isKeyInQuery}} +) -> TokenModel: + """ + Check and retrieve authentication information from api_key. + + {{#isKeyInHeader}}:param token_api_key_header API key provided by Authorization[{{keyParamName}}] header{{/isKeyInHeader}} + {{#isKeyInCookie}}:param token_api_key_cookie API key provided by Authorization[{{keyParamName}}] cookie{{/isKeyInCookie}} + {{#isKeyInQuery}}:param token_api_key_query API key provided by [{{keyParamName}}] query{{/isKeyInQuery}} + :type token_api_key_{{#isKeyInHeader}}header{{/isKeyInHeader}}{{#isKeyInCookie}}cookie{{/isKeyInCookie}}{{#isKeyInQuery}}query{{/isKeyInQuery}}: str + :return: Information attached to provided api_key or None if api_key is invalid or does not allow access to called API + :rtype: TokenModel | None + """ + + ... + +{{/isApiKey}} +{{#isBasicBasic}} + +basic_auth = HTTPBasic() + + +def get_token_{{name}}( + credentials: HTTPBasicCredentials = Depends(basic_auth) +) -> TokenModel: + """ + Check and retrieve authentication information from basic auth. + + :param credentials Credentials provided by Authorization header + :type credentials: HTTPBasicCredentials + :rtype: TokenModel | None + """ + + ... + +{{/isBasicBasic}} +{{#isBasicBearer}} + +bearer_auth = HTTPBearer() + + +def get_token_{{name}}(credentials: HTTPAuthorizationCredentials = Depends(bearer_auth)) -> TokenModel: + """ + Check and retrieve authentication information from custom bearer token. + + :param credentials Credentials provided by Authorization header + :type credentials: HTTPAuthorizationCredentials + :return: Decoded token information or None if token is invalid + :rtype: TokenModel | None + """ + + ... + +{{/isBasicBearer}} +{{/authMethods}} diff --git a/modules/openapi-generator/src/main/resources/python-fastapi/setup_cfg.mustache b/modules/openapi-generator/src/main/resources/python-fastapi/setup_cfg.mustache new file mode 100644 index 00000000000..2934cb8fc53 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python-fastapi/setup_cfg.mustache @@ -0,0 +1,23 @@ +[metadata] +name = {{packageName}} +version = {{appVersion}} +description = {{appDescription}} +long_description = file: README.md +keywords = OpenAPI {{appName}} +python_requires = >= 3.7.* +classifiers = + Operating System :: OS Independent + Programming Language :: Python :: 3 + Programming Language :: Python :: 3.7 + +[options] +install_requires = + fastapi[all] +setup_requires = + setuptools +package_dir= + =src +packages=find_namespace: + +[options.packages.find] +where=src diff --git a/modules/openapi-generator/src/main/resources/python/api.mustache b/modules/openapi-generator/src/main/resources/python/api.mustache index 37339fc5115..4be68cdf12b 100644 --- a/modules/openapi-generator/src/main/resources/python/api.mustache +++ b/modules/openapi-generator/src/main/resources/python/api.mustache @@ -80,8 +80,8 @@ class {{classname}}(object): _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. - _request_timeout (float/tuple): timeout setting for this request. If one - number provided, it will be total request timeout. It can also + _request_timeout (int/float/tuple): timeout setting for this request. If + one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking 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 8d6395a4c2e..31d9e48354a 100644 --- a/modules/openapi-generator/src/main/resources/python/api_client.mustache +++ b/modules/openapi-generator/src/main/resources/python/api_client.mustache @@ -127,7 +127,7 @@ class ApiClient(object): _return_http_data_only: typing.Optional[bool] = None, collection_formats: typing.Optional[typing.Dict[str, str]] = None, _preload_content: bool = True, - _request_timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + _request_timeout: typing.Optional[typing.Union[int, float, typing.Tuple]] = None, _host: typing.Optional[str] = None, _check_type: typing.Optional[bool] = None ): @@ -359,7 +359,7 @@ class ApiClient(object): _return_http_data_only: typing.Optional[bool] = None, collection_formats: typing.Optional[typing.Dict[str, str]] = None, _preload_content: bool = True, - _request_timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + _request_timeout: typing.Optional[typing.Union[int, float, typing.Tuple]] = None, _host: typing.Optional[str] = None, _check_type: typing.Optional[bool] = None ): @@ -695,7 +695,7 @@ class Endpoint(object): 'async_req': (bool,), '_host_index': (none_type, int), '_preload_content': (bool,), - '_request_timeout': (none_type, int, (int,), [int]), + '_request_timeout': (none_type, float, (float,), [float], int, (int,), [int]), '_return_http_data_only': (bool,), '_check_input_type': (bool,), '_check_return_type': (bool,) diff --git a/modules/openapi-generator/src/main/resources/python/model_utils.mustache b/modules/openapi-generator/src/main/resources/python/model_utils.mustache index 73e6e7d555b..4615a34ec33 100644 --- a/modules/openapi-generator/src/main/resources/python/model_utils.mustache +++ b/modules/openapi-generator/src/main/resources/python/model_utils.mustache @@ -39,7 +39,7 @@ def convert_js_args_to_python_args(fn): class cached_property(object): # this caches the result of the function call for fn with no inputs - # use this as a decorator on fuction methods that you want converted + # use this as a decorator on function methods that you want converted # into cached properties result_key = '_results' @@ -1335,12 +1335,20 @@ def model_to_dict(model_instance, serialize=True): model_instances = [model_instance] if model_instance._composed_schemas: model_instances.extend(model_instance._composed_instances) + seen_json_attribute_names = set() + used_fallback_python_attribute_names = set() + py_to_json_map = {} for model_instance in model_instances: for attr, value in model_instance._data_store.items(): if serialize: # we use get here because additional property key names do not # exist in attribute_map - attr = model_instance.attribute_map.get(attr, attr) + try: + attr = model_instance.attribute_map[attr] + py_to_json_map.update(model_instance.attribute_map) + seen_json_attribute_names.add(attr) + except KeyError: + used_fallback_python_attribute_names.add(attr) if isinstance(value, list): if not value: # empty list or None @@ -1368,6 +1376,16 @@ def model_to_dict(model_instance, serialize=True): result[attr] = model_to_dict(value, serialize=serialize) else: result[attr] = value + if serialize: + for python_key in used_fallback_python_attribute_names: + json_key = py_to_json_map.get(python_key) + if json_key is None: + continue + if python_key == json_key: + continue + json_key_assigned_no_need_for_python_key = json_key in seen_json_attribute_names + if json_key_assigned_no_need_for_python_key: + del result[python_key] return result diff --git a/modules/openapi-generator/src/main/resources/python/rest.mustache b/modules/openapi-generator/src/main/resources/python/rest.mustache index 9e733864895..21c8d5b44c0 100644 --- a/modules/openapi-generator/src/main/resources/python/rest.mustache +++ b/modules/openapi-generator/src/main/resources/python/rest.mustache @@ -129,15 +129,15 @@ class RESTClientObject(object): timeout = urllib3.Timeout( connect=_request_timeout[0], read=_request_timeout[1]) - if 'Content-Type' not in headers: - headers['Content-Type'] = 'application/json' - try: # For `POST`, `PUT`, `PATCH`, `OPTIONS`, `DELETE` if method in ['POST', 'PUT', 'PATCH', 'OPTIONS', 'DELETE']: + # Only set a default Content-Type for POST, PUT, PATCH and OPTIONS requests + if (method != 'DELETE') and ('Content-Type' not in headers): + headers['Content-Type'] = 'application/json' if query_params: url += '?' + urlencode(query_params) - if re.search('json', headers['Content-Type'], re.IGNORECASE): + if ('Content-Type' not in headers) or (re.search('json', headers['Content-Type'], re.IGNORECASE)): request_body = None if body is not None: request_body = json.dumps(body) diff --git a/modules/openapi-generator/src/main/resources/r/model.mustache b/modules/openapi-generator/src/main/resources/r/model.mustache index 1b853ec3730..28b7ce9145b 100644 --- a/modules/openapi-generator/src/main/resources/r/model.mustache +++ b/modules/openapi-generator/src/main/resources/r/model.mustache @@ -47,6 +47,9 @@ {{#isString}} stopifnot(is.character(`{{baseName}}`), length(`{{baseName}}`) == 1) {{/isString}} + {{#isBoolean}} + stopifnot(is.logical(`{{baseName}}`), length(`{{baseName}}`) == 1) + {{/isBoolean}} {{#isDate}} stopifnot(is.character(`{{baseName}}`), length(`{{baseName}}`) == 1) {{/isDate}} @@ -88,6 +91,9 @@ {{#isString}} stopifnot(is.character(`{{baseName}}`), length(`{{baseName}}`) == 1) {{/isString}} + {{#isBoolean}} + stopifnot(is.logical(`{{baseName}}`), length(`{{baseName}}`) == 1) + {{/isBoolean}} {{#isDate}} stopifnot(is.character(`{{baseName}}`), length(`{{baseName}}`) == 1) {{/isDate}} @@ -185,7 +191,7 @@ {{/isArray}} {{#isMap}} {{#isPrimitiveType}} - {{#isNumeric}}%d{{/isNumeric}}{{^isNumeric}}"%s"{{/isNumeric}} + {{#isNumeric}}%d{{/isNumeric}}{{^isNumeric}}{{^isBoolean}}"{{/isBoolean}}%s{{^isBoolean}}"{{/isBoolean}}{{/isNumeric}} {{/isPrimitiveType}} {{^isPrimitiveType}}%s {{/isPrimitiveType}} @@ -193,7 +199,7 @@ {{/isContainer}} {{^isContainer}} {{#isPrimitiveType}} - {{#isNumeric}}%d{{/isNumeric}}{{^isNumeric}}"%s"{{/isNumeric}} + {{#isNumeric}}%d{{/isNumeric}}{{^isNumeric}}{{^isBoolean}}"{{/isBoolean}}%s{{^isBoolean}}"{{/isBoolean}}{{/isNumeric}} {{/isPrimitiveType}} {{^isPrimitiveType}}%s {{/isPrimitiveType}} @@ -218,7 +224,7 @@ {{/isContainer}} {{^isContainer}} {{#isPrimitiveType}} - self$`{{baseName}}` + {{#isBoolean}}tolower({{/isBoolean}}self$`{{baseName}}`{{#isBoolean}}){{/isBoolean}} {{/isPrimitiveType}} {{^isPrimitiveType}} jsonlite::toJSON(self$`{{baseName}}`$toJSON(), auto_unbox=TRUE, digits = NA) @@ -253,4 +259,3 @@ {{/isEnum}} {{/model}} {{/models}} - 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 8ff7ce8d99e..6dd9d1e3823 100644 --- a/modules/openapi-generator/src/main/resources/rust/reqwest/api.mustache +++ b/modules/openapi-generator/src/main/resources/rust/reqwest/api.mustache @@ -94,7 +94,7 @@ pub {{#supportAsync}}async {{/supportAsync}}fn {{{operationId}}}(configuration: let local_var_client = &configuration.client; let local_var_uri_str = format!("{}{{{path}}}", configuration.base_path{{#pathParams}}, {{{baseName}}}={{#isString}}crate::apis::urlencode({{/isString}}{{{paramName}}}{{^required}}.unwrap(){{/required}}{{#required}}{{#isNullable}}.unwrap(){{/isNullable}}{{/required}}{{#isArray}}.join(",").as_ref(){{/isArray}}{{#isString}}){{/isString}}{{/pathParams}}); - let mut local_var_req_builder = local_var_client.{{{httpMethod}}}(local_var_uri_str.as_str()); + let mut local_var_req_builder = local_var_client.request(reqwest::Method::{{{httpMethod}}}, local_var_uri_str.as_str()); {{#queryParams}} {{#required}} diff --git a/modules/openapi-generator/src/main/resources/swift5/APIHelper.mustache b/modules/openapi-generator/src/main/resources/swift5/APIHelper.mustache index 94dc810006a..e535c7df4c4 100644 --- a/modules/openapi-generator/src/main/resources/swift5/APIHelper.mustache +++ b/modules/openapi-generator/src/main/resources/swift5/APIHelper.mustache @@ -4,7 +4,8 @@ // https://openapi-generator.tech // -import Foundation +import Foundation{{#useVapor}} +import Vapor{{/useVapor}} {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} struct APIHelper { {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} static func rejectNil(_ source: [String: Any?]) -> [String: Any]? { diff --git a/modules/openapi-generator/src/main/resources/swift5/APIs.mustache b/modules/openapi-generator/src/main/resources/swift5/APIs.mustache index 42bdf74007f..f931988cf9f 100644 --- a/modules/openapi-generator/src/main/resources/swift5/APIs.mustache +++ b/modules/openapi-generator/src/main/resources/swift5/APIs.mustache @@ -5,15 +5,26 @@ // import Foundation +{{#useVapor}} +import Vapor +{{/useVapor}} -{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} class {{projectName}}API { +@available(*, deprecated, renamed: "{{projectName}}") +{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} typealias {{projectName}}API = {{projectName}} + +{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} class {{projectName}} { {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} static var basePath = "{{{basePath}}}" - {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} static var credential: URLCredential? - {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} static var customHeaders: [String: String] = [:]{{#useAlamofire}} + {{#useVapor}} + {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} static var customHeaders: HTTPHeaders = [:] + {{/useVapor}} + {{^useVapor}} + {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} static var customHeaders: [String: String] = [:] + {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} static var credential: URLCredential?{{#useAlamofire}} {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} static var requestBuilderFactory: RequestBuilderFactory = AlamofireRequestBuilderFactory(){{/useAlamofire}}{{#useURLSession}} {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} static var requestBuilderFactory: RequestBuilderFactory = URLSessionRequestBuilderFactory(){{/useURLSession}} {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} static var apiResponseQueue: DispatchQueue = .main -} + {{/useVapor}} +}{{^useVapor}} {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} class RequestBuilder { var credential: URLCredential? @@ -33,7 +44,7 @@ import Foundation self.parameters = parameters self.headers = headers - addHeaders({{projectName}}API.customHeaders) + addHeaders({{projectName}}.customHeaders) } {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} func addHeaders(_ aHeaders: [String: String]) { @@ -42,7 +53,7 @@ import Foundation } } - {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} func execute(_ apiResponseQueue: DispatchQueue = {{projectName}}API.apiResponseQueue, _ completion: @escaping (_ result: Swift.Result, Error>) -> Void) { } + {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} func execute(_ apiResponseQueue: DispatchQueue = {{projectName}}.apiResponseQueue, _ completion: @escaping (_ result: Swift.Result, Error>) -> Void) { } {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} func addHeader(name: String, value: String) -> Self { if !value.isEmpty { @@ -52,7 +63,7 @@ import Foundation } {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} func addCredential() -> Self { - credential = {{projectName}}API.credential + credential = {{projectName}}.credential return self } } @@ -60,4 +71,4 @@ import Foundation {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} protocol RequestBuilderFactory { func getNonDecodableBuilder() -> RequestBuilder.Type func getBuilder() -> RequestBuilder.Type -} +}{{/useVapor}} diff --git a/modules/openapi-generator/src/main/resources/swift5/Cartfile.mustache b/modules/openapi-generator/src/main/resources/swift5/Cartfile.mustache index 64dac06473e..98d54ab04c8 100644 --- a/modules/openapi-generator/src/main/resources/swift5/Cartfile.mustache +++ b/modules/openapi-generator/src/main/resources/swift5/Cartfile.mustache @@ -1,4 +1,4 @@ {{#useAlamofire}}github "Alamofire/Alamofire" ~> 4.9.1{{/useAlamofire}}{{#usePromiseKit}} -github "mxcl/PromiseKit" ~> 6.13.1{{/usePromiseKit}}{{#useRxSwift}} -github "ReactiveX/RxSwift" ~> 5.1.1{{/useRxSwift}} -github "Flight-School/AnyCodable" ~> 0.4.0 +github "mxcl/PromiseKit" ~> 6.15.3{{/usePromiseKit}}{{#useRxSwift}} +github "ReactiveX/RxSwift" ~> 6.2.0{{/useRxSwift}} +github "Flight-School/AnyCodable" ~> 0.6.1 diff --git a/modules/openapi-generator/src/main/resources/swift5/Configuration.mustache b/modules/openapi-generator/src/main/resources/swift5/Configuration.mustache index 78f54279711..d6bbdc0ae26 100644 --- a/modules/openapi-generator/src/main/resources/swift5/Configuration.mustache +++ b/modules/openapi-generator/src/main/resources/swift5/Configuration.mustache @@ -4,11 +4,25 @@ // https://openapi-generator.tech // -import Foundation +import Foundation{{#useVapor}} +import Vapor{{/useVapor}} +{{#swiftUseApiNamespace}} +@available(*, deprecated, renamed: "{{projectName}}.Configuration") +{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} typealias Configuration = {{projectName}}.Configuration + +extension {{projectName}} { +{{/swiftUseApiNamespace}} {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} class Configuration { + {{#useVapor}}{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} static var apiClient: Vapor.Client? = nil + {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} static var apiWrapper: (inout Vapor.ClientRequest) throws -> () = { _ in } + {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} static var contentConfiguration = ContentConfiguration.default(){{/useVapor}}{{^useVapor}} // This value is used to configure the date formatter that is used to serialize dates into JSON format. // You must set it prior to encoding any dates, and it will only be read once. @available(*, unavailable, message: "To set a different date format, use CodableHelper.dateFormatter instead.") - {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} static var dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ" + {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} static var dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ"{{/useVapor}} } +{{#swiftUseApiNamespace}} +} + +{{/swiftUseApiNamespace}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/swift5/Extensions.mustache b/modules/openapi-generator/src/main/resources/swift5/Extensions.mustache index 7e6dcc1994f..e81a205164f 100644 --- a/modules/openapi-generator/src/main/resources/swift5/Extensions.mustache +++ b/modules/openapi-generator/src/main/resources/swift5/Extensions.mustache @@ -5,8 +5,11 @@ // import Foundation -import AnyCodable{{#usePromiseKit}} -import PromiseKit{{/usePromiseKit}} +#if canImport(AnyCodable) +import AnyCodable +#endif{{#usePromiseKit}} +import PromiseKit{{/usePromiseKit}}{{#useVapor}} +import Vapor{{/useVapor}}{{^useVapor}} extension Bool: JSONEncodable { func encodeToJSON() -> Any { return self as Any } @@ -92,7 +95,7 @@ extension UUID: JSONEncodable { func encodeToJSON() -> Any { return self.uuidString } -} +}{{/useVapor}}{{#generateModelAdditionalProperties}} extension String: CodingKey { @@ -178,13 +181,13 @@ extension KeyedDecodingContainerProtocol { return map } -} +}{{/generateModelAdditionalProperties}}{{^useVapor}} extension HTTPURLResponse { var isStatusCodeSuccessful: Bool { return Array(200 ..< 300).contains(statusCode) } -}{{#usePromiseKit}} +}{{/useVapor}}{{#usePromiseKit}} extension RequestBuilder { {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} func execute() -> Promise> { @@ -199,45 +202,39 @@ extension RequestBuilder { } return deferred.promise } -}{{/usePromiseKit}} +}{{/usePromiseKit}}{{#useVapor}} -extension AnyCodable: Hashable { - public func hash(into hasher: inout Hasher) { - switch value { - case let value as Bool: - hasher.combine(value) - case let value as Int: - hasher.combine(value) - case let value as Int8: - hasher.combine(value) - case let value as Int16: - hasher.combine(value) - case let value as Int32: - hasher.combine(value) - case let value as Int64: - hasher.combine(value) - case let value as UInt: - hasher.combine(value) - case let value as UInt8: - hasher.combine(value) - case let value as UInt16: - hasher.combine(value) - case let value as UInt32: - hasher.combine(value) - case let value as UInt64: - hasher.combine(value) - case let value as Float: - hasher.combine(value) - case let value as Double: - hasher.combine(value) - case let value as String: - hasher.combine(value) - case let value as [String: AnyCodable]: - hasher.combine(value) - case let value as [AnyCodable]: - hasher.combine(value) - default: - hasher.combine(0) +extension UUID: Content { } + +extension URL: Content { } + +extension Bool: Content { } + +extension Set: ResponseEncodable where Element: Content { + public func encodeResponse(for request: Vapor.Request) -> EventLoopFuture { + let response = Vapor.Response() + do { + try response.content.encode(Array(self)) + } catch { + return request.eventLoop.makeFailedFuture(error) + } + return request.eventLoop.makeSucceededFuture(response) + } +} + +extension Set: RequestDecodable where Element: Content { + public static func decodeRequest(_ request: Vapor.Request) -> EventLoopFuture { + do { + let content = try request.content.decode([Element].self) + return request.eventLoop.makeSucceededFuture(Set(content)) + } catch { + return request.eventLoop.makeFailedFuture(error) } } -} \ No newline at end of file +} + +extension Set: Content where Element: Content { } + +extension AnyCodable: Content {} +{{/useVapor}} + diff --git a/modules/openapi-generator/src/main/resources/swift5/Package.swift.mustache b/modules/openapi-generator/src/main/resources/swift5/Package.swift.mustache index 353c6e9f341..cd573b4a96f 100644 --- a/modules/openapi-generator/src/main/resources/swift5/Package.swift.mustache +++ b/modules/openapi-generator/src/main/resources/swift5/Package.swift.mustache @@ -5,10 +5,15 @@ import PackageDescription let package = Package( name: "{{projectName}}", platforms: [ + {{#useVapor}} + .macOS(.v10_15), + {{/useVapor}} + {{^useVapor}} .iOS(.v9), .macOS(.v10_11), .tvOS(.v9), .watchOS(.v3), + {{/useVapor}} ], products: [ // Products define the executables and libraries produced by a package, and make them visible to other packages. @@ -19,15 +24,18 @@ let package = Package( ], dependencies: [ // Dependencies declare other packages that this package depends on. - .package(url: "https://github.com/Flight-School/AnyCodable", .exact("0.4.0")), + .package(url: "https://github.com/Flight-School/AnyCodable", from: "0.6.1"), {{#useAlamofire}} - .package(url: "https://github.com/Alamofire/Alamofire.git", from: "4.9.1"), + .package(url: "https://github.com/Alamofire/Alamofire", from: "4.9.1"), {{/useAlamofire}} + {{#useVapor}} + .package(url: "https://github.com/vapor/vapor", from: "4.0.0") + {{/useVapor}} {{#usePromiseKit}} - .package(url: "https://github.com/mxcl/PromiseKit.git", from: "6.12.0"), + .package(url: "https://github.com/mxcl/PromiseKit", from: "6.15.3"), {{/usePromiseKit}} {{#useRxSwift}} - .package(url: "https://github.com/ReactiveX/RxSwift.git", from: "5.0.0"), + .package(url: "https://github.com/ReactiveX/RxSwift", from: "6.2.0"), {{/useRxSwift}} ], targets: [ @@ -35,7 +43,7 @@ let package = Package( // Targets can depend on other targets in this package, and on products in packages which this package depends on. .target( name: "{{projectName}}", - dependencies: ["AnyCodable", {{#useAlamofire}}"Alamofire", {{/useAlamofire}}{{#usePromiseKit}}"PromiseKit", {{/usePromiseKit}}{{#useRxSwift}}"RxSwift"{{/useRxSwift}}], + dependencies: ["AnyCodable", {{#useVapor}}"Vapor", {{/useVapor}}{{#useAlamofire}}"Alamofire", {{/useAlamofire}}{{#usePromiseKit}}"PromiseKit", {{/usePromiseKit}}{{#useRxSwift}}"RxSwift"{{/useRxSwift}}], path: "{{#swiftPackagePath}}{{swiftPackagePath}}{{/swiftPackagePath}}{{^swiftPackagePath}}{{#useSPMFileStructure}}Sources/{{projectName}}{{/useSPMFileStructure}}{{^useSPMFileStructure}}{{projectName}}/Classes{{/useSPMFileStructure}}{{/swiftPackagePath}}" ), ] diff --git a/modules/openapi-generator/src/main/resources/swift5/Podspec.mustache b/modules/openapi-generator/src/main/resources/swift5/Podspec.mustache index 09f07162c03..3cf9daa69a8 100644 --- a/modules/openapi-generator/src/main/resources/swift5/Podspec.mustache +++ b/modules/openapi-generator/src/main/resources/swift5/Podspec.mustache @@ -27,13 +27,13 @@ Pod::Spec.new do |s| {{/podDocumentationURL}} s.source_files = '{{#swiftPackagePath}}{{swiftPackagePath}}{{/swiftPackagePath}}{{^swiftPackagePath}}{{#useSPMFileStructure}}Sources/{{projectName}}{{/useSPMFileStructure}}{{^useSPMFileStructure}}{{projectName}}/Classes{{/useSPMFileStructure}}{{/swiftPackagePath}}/**/*.swift' {{#usePromiseKit}} - s.dependency 'PromiseKit/CorePromise', '~> 6.13.1' + s.dependency 'PromiseKit/CorePromise', '~> 6.15.3' {{/usePromiseKit}} {{#useRxSwift}} - s.dependency 'RxSwift', '~> 5.1.1' + s.dependency 'RxSwift', '~> 6.2.0' {{/useRxSwift}} {{#useAlamofire}} s.dependency 'Alamofire', '~> 4.9.1' {{/useAlamofire}} - s.dependency 'AnyCodable-FlightSchool', '~> 0.4.0' + s.dependency 'AnyCodable-FlightSchool', '~> 0.6.1' end diff --git a/modules/openapi-generator/src/main/resources/swift5/README.mustache b/modules/openapi-generator/src/main/resources/swift5/README.mustache index 4e15bc40b0b..2fc73bcdbc1 100644 --- a/modules/openapi-generator/src/main/resources/swift5/README.mustache +++ b/modules/openapi-generator/src/main/resources/swift5/README.mustache @@ -19,6 +19,13 @@ For more information, please visit [{{{infoUrl}}}]({{{infoUrl}}}) ## Installation +{{#useVapor}} +Add the following entry in your Package.swift: + +> .package(path: "./{{{projectName}}}") + +{{/useVapor}} +{{^useVapor}} ### Carthage Run `carthage update` @@ -27,7 +34,7 @@ Run `carthage update` Run `pod install` -## Documentation for API Endpoints +{{/useVapor}}## Documentation for API Endpoints All URIs are relative to *{{basePath}}* diff --git a/modules/openapi-generator/src/main/resources/swift5/XcodeGen.mustache b/modules/openapi-generator/src/main/resources/swift5/XcodeGen.mustache index 54fbb33d468..aed8dcb76b2 100644 --- a/modules/openapi-generator/src/main/resources/swift5/XcodeGen.mustache +++ b/modules/openapi-generator/src/main/resources/swift5/XcodeGen.mustache @@ -11,8 +11,8 @@ targets: settings: APPLICATION_EXTENSION_API_ONLY: true scheme: {} - {{#useAlamofire}}dependencies:{{/useAlamofire}}{{^useAlamofire}}{{#useRxSwift}}dependencies:{{/useRxSwift}}{{/useAlamofire}}{{^useAlamofire}}{{^useRxSwift}}{{#usePromiseKit}}dependencies:{{/usePromiseKit}}{{/useRxSwift}}{{/useAlamofire}}{{#useAlamofire}} + dependencies: + - carthage: AnyCodable{{#useAlamofire}} - carthage: Alamofire{{/useAlamofire}}{{#useRxSwift}} - carthage: RxSwift{{/useRxSwift}}{{#usePromiseKit}} - carthage: PromiseKit{{/usePromiseKit}} - - carthage: AnyCodable diff --git a/modules/openapi-generator/src/main/resources/swift5/api.mustache b/modules/openapi-generator/src/main/resources/swift5/api.mustache index ac3b4b3d954..135c47069c6 100644 --- a/modules/openapi-generator/src/main/resources/swift5/api.mustache +++ b/modules/openapi-generator/src/main/resources/swift5/api.mustache @@ -10,21 +10,26 @@ import PromiseKit{{/usePromiseKit}}{{#useRxSwift}} import RxSwift{{/useRxSwift}}{{#useCombine}} #if canImport(Combine) import Combine -#endif{{/useCombine}}{{#swiftUseApiNamespace}} +#endif{{/useCombine}}{{#useVapor}} +import Vapor{{/useVapor}} +#if canImport(AnyCodable) +import AnyCodable +#endif{{#swiftUseApiNamespace}} -extension {{projectName}}API { +extension {{projectName}} { {{/swiftUseApiNamespace}} {{#description}} -/** {{description}} */{{/description}} +/** {{{description}}} */{{/description}} {{#objcCompatible}}@objc {{/objcCompatible}}{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} class {{classname}}{{#objcCompatible}} : NSObject{{/objcCompatible}} { {{#operation}} + {{#allParams}} {{#isEnum}} /** * enum for parameter {{paramName}} */ - {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} enum {{enumName}}_{{operationId}}: {{^isContainer}}{{{dataType}}}{{/isContainer}}{{#isContainer}}String{{/isContainer}}, CaseIterable { + {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} enum {{enumName}}_{{operationId}}: {{^isContainer}}{{{dataType}}}{{/isContainer}}{{#isContainer}}String{{/isContainer}}, CaseIterable{{#useVapor}}, Content{{/useVapor}} { {{#allowableValues}} {{#enumVars}} case {{name}} = {{{value}}} @@ -34,6 +39,7 @@ extension {{projectName}}API { {{/isEnum}} {{/allParams}} +{{^useVapor}} {{^usePromiseKit}} {{^useRxSwift}} {{^useResult}} @@ -49,7 +55,7 @@ extension {{projectName}}API { {{#isDeprecated}} @available(*, deprecated, message: "This operation is deprecated.") {{/isDeprecated}} - {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} class func {{operationId}}({{#allParams}}{{paramName}}: {{#isEnum}}{{#isContainer}}{{{dataType}}}{{/isContainer}}{{^isContainer}}{{{datatypeWithEnum}}}_{{operationId}}{{/isContainer}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{^required}}? = nil{{/required}}{{^-last}}, {{/-last}}{{/allParams}}{{#hasParams}}, {{/hasParams}}apiResponseQueue: DispatchQueue = {{projectName}}API.apiResponseQueue, completion: @escaping ((_ data: {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}?, _ error: Error?) -> Void)) { + {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} class func {{operationId}}({{#allParams}}{{paramName}}: {{#isEnum}}{{#isContainer}}{{{dataType}}}{{/isContainer}}{{^isContainer}}{{{datatypeWithEnum}}}_{{operationId}}{{/isContainer}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{^required}}? = nil{{/required}}{{^-last}}, {{/-last}}{{/allParams}}{{#hasParams}}, {{/hasParams}}apiResponseQueue: DispatchQueue = {{projectName}}.apiResponseQueue, completion: @escaping ((_ data: {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}?, _ error: Error?) -> Void)) { {{operationId}}WithRequestBuilder({{#allParams}}{{paramName}}: {{paramName}}{{^-last}}, {{/-last}}{{/allParams}}).execute(apiResponseQueue) { result -> Void in switch result { {{#returnType}} @@ -69,6 +75,7 @@ extension {{projectName}}API { {{/useResult}} {{/useRxSwift}} {{/usePromiseKit}} +{{/useVapor}} {{#usePromiseKit}} /** {{#summary}} @@ -81,7 +88,7 @@ extension {{projectName}}API { {{#isDeprecated}} @available(*, deprecated, message: "This operation is deprecated.") {{/isDeprecated}} - {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} class func {{operationId}}({{#allParams}} {{paramName}}: {{#isEnum}}{{#isContainer}}{{{dataType}}}{{/isContainer}}{{^isContainer}}{{{datatypeWithEnum}}}_{{operationId}}{{/isContainer}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{^required}}? = nil{{/required}}{{^-last}}, {{/-last}}{{/allParams}}{{#hasParams}}, {{/hasParams}}apiResponseQueue: DispatchQueue = {{projectName}}API.apiResponseQueue) -> Promise<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}> { + {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} class func {{operationId}}({{#allParams}} {{paramName}}: {{#isEnum}}{{#isContainer}}{{{dataType}}}{{/isContainer}}{{^isContainer}}{{{datatypeWithEnum}}}_{{operationId}}{{/isContainer}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{^required}}? = nil{{/required}}{{^-last}}, {{/-last}}{{/allParams}}{{#hasParams}}, {{/hasParams}}apiResponseQueue: DispatchQueue = {{projectName}}.apiResponseQueue) -> Promise<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}> { let deferred = Promise<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}>.pending() {{operationId}}WithRequestBuilder({{#allParams}}{{paramName}}: {{paramName}}{{^-last}}, {{/-last}}{{/allParams}}).execute(apiResponseQueue) { result -> Void in switch result { @@ -112,7 +119,7 @@ extension {{projectName}}API { {{#isDeprecated}} @available(*, deprecated, message: "This operation is deprecated.") {{/isDeprecated}} - {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} class func {{operationId}}({{#allParams}}{{paramName}}: {{#isEnum}}{{#isContainer}}{{{dataType}}}{{/isContainer}}{{^isContainer}}{{{datatypeWithEnum}}}_{{operationId}}{{/isContainer}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{^required}}? = nil{{/required}}{{^-last}}, {{/-last}}{{/allParams}}{{#hasParams}}, {{/hasParams}}apiResponseQueue: DispatchQueue = {{projectName}}API.apiResponseQueue) -> Observable<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}> { + {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} class func {{operationId}}({{#allParams}}{{paramName}}: {{#isEnum}}{{#isContainer}}{{{dataType}}}{{/isContainer}}{{^isContainer}}{{{datatypeWithEnum}}}_{{operationId}}{{/isContainer}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{^required}}? = nil{{/required}}{{^-last}}, {{/-last}}{{/allParams}}{{#hasParams}}, {{/hasParams}}apiResponseQueue: DispatchQueue = {{projectName}}.apiResponseQueue) -> Observable<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}> { return Observable.create { observer -> Disposable in {{operationId}}WithRequestBuilder({{#allParams}}{{paramName}}: {{paramName}}{{^-last}}, {{/-last}}{{/allParams}}).execute(apiResponseQueue) { result -> Void in switch result { @@ -147,7 +154,7 @@ extension {{projectName}}API { @available(*, deprecated, message: "This operation is deprecated.") {{/isDeprecated}} @available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) - {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} class func {{operationId}}({{#allParams}}{{paramName}}: {{#isEnum}}{{#isContainer}}{{{dataType}}}{{/isContainer}}{{^isContainer}}{{{datatypeWithEnum}}}_{{operationId}}{{/isContainer}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{^required}}? = nil{{/required}}{{^-last}}, {{/-last}}{{/allParams}}{{#hasParams}}, {{/hasParams}}apiResponseQueue: DispatchQueue = {{projectName}}API.apiResponseQueue) -> AnyPublisher<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}, Error> { + {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} class func {{operationId}}({{#allParams}}{{paramName}}: {{#isEnum}}{{#isContainer}}{{{dataType}}}{{/isContainer}}{{^isContainer}}{{{datatypeWithEnum}}}_{{operationId}}{{/isContainer}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{^required}}? = nil{{/required}}{{^-last}}, {{/-last}}{{/allParams}}{{#hasParams}}, {{/hasParams}}apiResponseQueue: DispatchQueue = {{projectName}}.apiResponseQueue) -> AnyPublisher<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}, Error> { return Future<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}, Error>.init { promise in {{operationId}}WithRequestBuilder({{#allParams}}{{paramName}}: {{paramName}}{{^-last}}, {{/-last}}{{/allParams}}).execute(apiResponseQueue) { result -> Void in switch result { @@ -179,7 +186,7 @@ extension {{projectName}}API { {{#isDeprecated}} @available(*, deprecated, message: "This operation is deprecated.") {{/isDeprecated}} - open class func {{operationId}}({{#allParams}}{{paramName}}: {{#isEnum}}{{#isContainer}}{{{dataType}}}{{/isContainer}}{{^isContainer}}{{{datatypeWithEnum}}}_{{operationId}}{{/isContainer}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{^required}}? = nil{{/required}}{{^-last}}, {{/-last}}{{/allParams}}{{#hasParams}}, {{/hasParams}}apiResponseQueue: DispatchQueue = {{projectName}}API.apiResponseQueue, completion: @escaping ((_ result: Swift.Result<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}, Error>) -> Void)) { + open class func {{operationId}}({{#allParams}}{{paramName}}: {{#isEnum}}{{#isContainer}}{{{dataType}}}{{/isContainer}}{{^isContainer}}{{{datatypeWithEnum}}}_{{operationId}}{{/isContainer}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{^required}}? = nil{{/required}}{{^-last}}, {{/-last}}{{/allParams}}{{#hasParams}}, {{/hasParams}}apiResponseQueue: DispatchQueue = {{projectName}}.apiResponseQueue, completion: @escaping ((_ result: Swift.Result<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}, Error>) -> Void)) { {{operationId}}WithRequestBuilder({{#allParams}}{{paramName}}: {{paramName}}{{^-last}}, {{/-last}}{{/allParams}}).execute(apiResponseQueue) { result -> Void in switch result { {{#returnType}} @@ -196,6 +203,125 @@ extension {{projectName}}API { } } {{/useResult}} +{{#useVapor}} + /** + {{#summary}} + {{{summary}}} + {{/summary}} + {{httpMethod}} {{{path}}}{{#notes}} + {{{notes}}}{{/notes}}{{#subresourceOperation}} + subresourceOperation: {{subresourceOperation}}{{/subresourceOperation}}{{#defaultResponse}} + defaultResponse: {{defaultResponse}}{{/defaultResponse}} + {{#authMethods}} + - {{#isBasic}}BASIC{{/isBasic}}{{#isOAuth}}OAuth{{/isOAuth}}{{#isApiKey}}API Key{{/isApiKey}}: + - type: {{type}}{{#keyParamName}} {{keyParamName}} {{#isKeyInQuery}}(QUERY){{/isKeyInQuery}}{{#isKeyInHeaer}}(HEADER){{/isKeyInHeaer}}{{/keyParamName}} + - name: {{name}} + {{/authMethods}} + {{#hasResponseHeaders}} + - responseHeaders: [{{#responseHeaders}}{{{baseName}}}({{{dataType}}}){{^-last}}, {{/-last}}{{/responseHeaders}}] + {{/hasResponseHeaders}} + {{#externalDocs}} + - externalDocs: {{externalDocs}} + {{/externalDocs}} + {{#allParams}} + - parameter {{paramName}}: ({{#isFormParam}}form{{/isFormParam}}{{#isQueryParam}}query{{/isQueryParam}}{{#isPathParam}}path{{/isPathParam}}{{#isHeaderParam}}header{{/isHeaderParam}}{{#isBodyParam}}body{{/isBodyParam}}) {{{description}}} {{^required}}(optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}} + {{/allParams}} + - returns: `EventLoopFuture` of `ClientResponse` {{{description}}} + */ + {{#isDeprecated}} + @available(*, deprecated, message: "This operation is deprecated.") + {{/isDeprecated}} + {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} class func {{operationId}}Raw({{#allParams}}{{paramName}}: {{#isEnum}}{{#isArray}}[{{enumName}}_{{operationId}}]{{/isArray}}{{^isArray}}{{#isContainer}}{{{dataType}}}{{/isContainer}}{{^isContainer}}{{{datatypeWithEnum}}}_{{operationId}}{{/isContainer}}{{/isArray}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{^required}}? = nil{{/required}}{{^-last}}, {{/-last}}{{/allParams}}{{#hasParams}}, {{/hasParams}}headers: HTTPHeaders = {{projectName}}.customHeaders, beforeSend: (inout ClientRequest) throws -> () = { _ in }) -> EventLoopFuture { + {{^pathParams}}let{{/pathParams}}{{#pathParams}}{{#-first}}var{{/-first}}{{/pathParams}} localVariablePath = "{{{path}}}"{{#pathParams}} + let {{paramName}}PreEscape = String(describing: {{#isEnum}}{{paramName}}{{#isContainer}}{{{dataType}}}{{/isContainer}}{{^isContainer}}.rawValue{{/isContainer}}{{/isEnum}}{{^isEnum}}{{paramName}}{{/isEnum}}) + let {{paramName}}PostEscape = {{paramName}}PreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + localVariablePath = localVariablePath.replacingOccurrences(of: "{{=<% %>=}}{<%baseName%>}<%={{ }}=%>", with: {{paramName}}PostEscape, options: .literal, range: nil){{/pathParams}} + let localVariableURLString = {{projectName}}.basePath + localVariablePath + + guard let localVariableApiClient = {{#swiftUseApiNamespace}}{{projectName}}.{{/swiftUseApiNamespace}}Configuration.apiClient else { + fatalError("Configuration.apiClient is not set.") + } + + return localVariableApiClient.send(.{{httpMethod}}, headers: headers, to: URI(string: localVariableURLString)) { localVariableRequest in + try {{#swiftUseApiNamespace}}{{projectName}}.{{/swiftUseApiNamespace}}Configuration.apiWrapper(&localVariableRequest) + {{#hasHeaderParams}}{{#headerParams}} + localVariableRequest.headers.add(name: "{{baseName}}", value: {{#isArray}}{{paramName}}{{^required}}?{{/required}}.map { $0{{#isEnum}}.rawValue{{/isEnum}}.description }.description{{/isArray}}{{^isArray}}{{#isEnum}}{{paramName}}{{^required}}?{{/required}}.rawValue.description{{/isEnum}}{{^isEnum}}{{paramName}}{{^required}}?{{/required}}.description{{/isEnum}}{{/isArray}}{{^required}} ?? ""{{/required}}) + {{/headerParams}}{{/hasHeaderParams}} + {{#hasQueryParams}}struct QueryParams: Content { + {{#queryParams}} + var {{paramName}}: {{#isEnum}}{{#isArray}}[{{enumName}}_{{operationId}}]{{/isArray}}{{^isArray}}{{#isContainer}}{{{dataType}}}{{/isContainer}}{{^isContainer}}{{{datatypeWithEnum}}}_{{operationId}}{{/isContainer}}{{/isArray}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{^required}}?{{/required}} + {{/queryParams}} + } + try localVariableRequest.query.encode(QueryParams({{#queryParams}}{{paramName}}: {{paramName}}{{^-last}}, {{/-last}}{{/queryParams}})){{/hasQueryParams}} + {{#hasBodyParam}} + {{#bodyParam}}{{#required}}{{#isBinary}}localVariableRequest.body = ByteBuffer(data: {{paramName}}){{/isBinary}}{{^isBinary}}{{#isFile}}localVariableRequest.body = ByteBuffer(data: {{paramName}}){{/isFile}}try localVariableRequest.content.encode({{paramName}}, using: Configuration.contentConfiguration.requireEncoder(for: {{{dataType}}}.defaultContentType)){{/isBinary}}{{/required}}{{^required}}if let localVariableBody = {{paramName}} { + {{#isBinary}}localVariableRequest.body = ByteBuffer(data: localVariableBody){{/isBinary}}{{^isBinary}}{{#isFile}}localVariableRequest.body = ByteBuffer(data: localVariableBody){{/isFile}}try localVariableRequest.content.encode(localVariableBody, using: Configuration.contentConfiguration.requireEncoder(for: {{{dataType}}}.defaultContentType)){{/isBinary}} + }{{/required}}{{/bodyParam}} + {{/hasBodyParam}} + {{#hasFormParams}}struct FormParams: Content { + static let defaultContentType = Vapor.HTTPMediaType.formData + {{#formParams}} + var {{paramName}}: {{#isEnum}}{{#isArray}}[{{enumName}}_{{operationId}}]{{/isArray}}{{^isArray}}{{#isContainer}}{{{dataType}}}{{/isContainer}}{{^isContainer}}{{{datatypeWithEnum}}}_{{operationId}}{{/isContainer}}{{/isArray}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{^required}}?{{/required}} + {{/formParams}} + } + try localVariableRequest.content.encode(FormParams({{#formParams}}{{paramName}}: {{paramName}}{{^-last}}, {{/-last}}{{/formParams}}), using: Configuration.contentConfiguration.requireEncoder(for: FormParams.defaultContentType)){{/hasFormParams}} + try beforeSend(&localVariableRequest) + } + } + + {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} enum {{#lambda.titlecase}}{{operationId}}{{/lambda.titlecase}} { + {{#responses}} + case http{{code}}({{#dataType}}value: {{{dataType}}}, {{/dataType}}raw: ClientResponse) + {{/responses}} + {{^hasDefaultResponse}} + case http0(raw: ClientResponse) + {{/hasDefaultResponse}} + } + + /** + {{#summary}} + {{{summary}}} + {{/summary}} + {{httpMethod}} {{{path}}}{{#notes}} + {{{notes}}}{{/notes}}{{#subresourceOperation}} + subresourceOperation: {{subresourceOperation}}{{/subresourceOperation}}{{#defaultResponse}} + defaultResponse: {{defaultResponse}}{{/defaultResponse}} + {{#authMethods}} + - {{#isBasic}}BASIC{{/isBasic}}{{#isOAuth}}OAuth{{/isOAuth}}{{#isApiKey}}API Key{{/isApiKey}}: + - type: {{type}}{{#keyParamName}} {{keyParamName}} {{#isKeyInQuery}}(QUERY){{/isKeyInQuery}}{{#isKeyInHeaer}}(HEADER){{/isKeyInHeaer}}{{/keyParamName}} + - name: {{name}} + {{/authMethods}} + {{#hasResponseHeaders}} + - responseHeaders: [{{#responseHeaders}}{{{baseName}}}({{{dataType}}}){{^-last}}, {{/-last}}{{/responseHeaders}}] + {{/hasResponseHeaders}} + {{#externalDocs}} + - externalDocs: {{externalDocs}} + {{/externalDocs}} + {{#allParams}} + - parameter {{paramName}}: ({{#isFormParam}}form{{/isFormParam}}{{#isQueryParam}}query{{/isQueryParam}}{{#isPathParam}}path{{/isPathParam}}{{#isHeaderParam}}header{{/isHeaderParam}}{{#isBodyParam}}body{{/isBodyParam}}) {{{description}}} {{^required}}(optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}} + {{/allParams}} + - returns: `EventLoopFuture` of `{{#lambda.titlecase}}{{operationId}}{{/lambda.titlecase}}` {{{description}}} + */ + {{#isDeprecated}} + @available(*, deprecated, message: "This operation is deprecated.") + {{/isDeprecated}} + {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} class func {{operationId}}({{#allParams}}{{paramName}}: {{#isEnum}}{{#isArray}}[{{enumName}}_{{operationId}}]{{/isArray}}{{^isArray}}{{#isContainer}}{{{dataType}}}{{/isContainer}}{{^isContainer}}{{{datatypeWithEnum}}}_{{operationId}}{{/isContainer}}{{/isArray}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{^required}}? = nil{{/required}}{{^-last}}, {{/-last}}{{/allParams}}{{#hasParams}}, {{/hasParams}}headers: HTTPHeaders = {{projectName}}.customHeaders, beforeSend: (inout ClientRequest) throws -> () = { _ in }) -> EventLoopFuture<{{#lambda.titlecase}}{{operationId}}{{/lambda.titlecase}}> { + return {{operationId}}Raw({{#allParams}}{{paramName}}: {{paramName}}{{^-last}}, {{/-last}}{{/allParams}}{{#hasParams}}, {{/hasParams}}headers: headers, beforeSend: beforeSend).flatMapThrowing { response -> {{#lambda.titlecase}}{{operationId}}{{/lambda.titlecase}} in + switch response.status.code { + {{#responses}} + {{#isDefault}}default{{/isDefault}}{{^isDefault}}case {{code}}{{/isDefault}}: + return .http{{code}}({{#dataType}}value: {{#isBinary}}Data(buffer: response.body ?? ByteBuffer()){{/isBinary}}{{^isBinary}}{{#isFile}}Data(buffer: response.body ?? ByteBuffer()){{/isFile}}{{^isFile}}try response.content.decode({{{dataType}}}.self, using: Configuration.contentConfiguration.requireDecoder(for: {{{dataType}}}.defaultContentType)){{/isFile}}{{/isBinary}}, {{/dataType}}raw: response) + {{/responses}} + {{^hasDefaultResponse}} + default: + return .http0(raw: response) + {{/hasDefaultResponse}} + } + } + } + +{{/useVapor}} +{{^useVapor}} /** {{#summary}} @@ -225,50 +351,50 @@ extension {{projectName}}API { @available(*, deprecated, message: "This operation is deprecated.") {{/isDeprecated}} {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} class func {{operationId}}WithRequestBuilder({{#allParams}}{{paramName}}: {{#isEnum}}{{#isContainer}}{{{dataType}}}{{/isContainer}}{{^isContainer}}{{{datatypeWithEnum}}}_{{operationId}}{{/isContainer}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{^required}}? = nil{{/required}}{{^-last}}, {{/-last}}{{/allParams}}) -> RequestBuilder<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}> { - {{^pathParams}}let{{/pathParams}}{{#pathParams}}{{#-first}}var{{/-first}}{{/pathParams}} path = "{{{path}}}"{{#pathParams}} + {{^pathParams}}let{{/pathParams}}{{#pathParams}}{{#-first}}var{{/-first}}{{/pathParams}} localVariablePath = "{{{path}}}"{{#pathParams}} let {{paramName}}PreEscape = "\({{#isEnum}}{{paramName}}{{#isContainer}}{{{dataType}}}{{/isContainer}}{{^isContainer}}.rawValue{{/isContainer}}{{/isEnum}}{{^isEnum}}APIHelper.mapValueToPathItem({{paramName}}){{/isEnum}})" let {{paramName}}PostEscape = {{paramName}}PreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" - path = path.replacingOccurrences(of: "{{=<% %>=}}{<%baseName%>}<%={{ }}=%>", with: {{paramName}}PostEscape, options: .literal, range: nil){{/pathParams}} - let URLString = {{projectName}}API.basePath + path + localVariablePath = localVariablePath.replacingOccurrences(of: "{{=<% %>=}}{<%baseName%>}<%={{ }}=%>", with: {{paramName}}PostEscape, options: .literal, range: nil){{/pathParams}} + let localVariableURLString = {{projectName}}.basePath + localVariablePath {{#bodyParam}} - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: {{paramName}}) + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: {{paramName}}) {{/bodyParam}} {{^bodyParam}} {{#hasFormParams}} - let formParams: [String: Any?] = [ + let localVariableFormParams: [String: Any?] = [ {{#formParams}} {{> _param}}, {{/formParams}} ] - let nonNullParameters = APIHelper.rejectNil(formParams) - let parameters = APIHelper.convertBoolToString(nonNullParameters) + let localVariableNonNullParameters = APIHelper.rejectNil(localVariableFormParams) + let localVariableParameters = APIHelper.convertBoolToString(localVariableNonNullParameters) {{/hasFormParams}} {{^hasFormParams}} - let parameters: [String: Any]? = nil + let localVariableParameters: [String: Any]? = nil {{/hasFormParams}} {{/bodyParam}}{{#hasQueryParams}} - var urlComponents = URLComponents(string: URLString) - urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([{{^queryParams}}:{{/queryParams}} + var localVariableUrlComponents = URLComponents(string: localVariableURLString) + localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([{{^queryParams}}:{{/queryParams}} {{#queryParams}} {{> _param}}, {{/queryParams}} ]){{/hasQueryParams}}{{^hasQueryParams}} - let urlComponents = URLComponents(string: URLString){{/hasQueryParams}} + let localVariableUrlComponents = URLComponents(string: localVariableURLString){{/hasQueryParams}} - let nillableHeaders: [String: Any?] = [{{^headerParams}}{{^hasFormParams}} + let localVariableNillableHeaders: [String: Any?] = [{{^headerParams}}{{^hasFormParams}} :{{/hasFormParams}}{{/headerParams}}{{#hasFormParams}} "Content-Type": {{^consumes}}"multipart/form-data"{{/consumes}}{{#consumes.0}}"{{{mediaType}}}"{{/consumes.0}},{{/hasFormParams}}{{#headerParams}} {{> _param}},{{/headerParams}} ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}>.Type = {{projectName}}API.requestBuilderFactory.{{#returnType}}getBuilder(){{/returnType}}{{^returnType}}getNonDecodableBuilder(){{/returnType}} + let localVariableRequestBuilder: RequestBuilder<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}>.Type = {{projectName}}.requestBuilderFactory.{{#returnType}}getBuilder(){{/returnType}}{{^returnType}}getNonDecodableBuilder(){{/returnType}} - return requestBuilder.init(method: "{{httpMethod}}", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "{{httpMethod}}", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } - +{{/useVapor}} {{/operation}} } {{#swiftUseApiNamespace}} diff --git a/modules/openapi-generator/src/main/resources/swift5/api_doc.mustache b/modules/openapi-generator/src/main/resources/swift5/api_doc.mustache index f57a93153c6..93b51e32535 100644 --- a/modules/openapi-generator/src/main/resources/swift5/api_doc.mustache +++ b/modules/openapi-generator/src/main/resources/swift5/api_doc.mustache @@ -14,7 +14,9 @@ Method | HTTP request | Description ```swift {{^usePromiseKit}} {{^useRxSwift}} +{{^useVapor}} {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} class func {{operationId}}({{#allParams}}{{paramName}}: {{#isEnum}}{{#isContainer}}{{{dataType}}}{{/isContainer}}{{^isContainer}}{{{datatypeWithEnum}}}_{{operationId}}{{/isContainer}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{^required}}? = nil{{/required}}{{^-last}}, {{/-last}}{{/allParams}}{{#hasParams}}, {{/hasParams}}completion: @escaping (_ data: {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}?, _ error: Error?) -> Void) +{{/useVapor}} {{/useRxSwift}} {{/usePromiseKit}} {{#usePromiseKit}} @@ -23,6 +25,9 @@ Method | HTTP request | Description {{#useRxSwift}} {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} class func {{operationId}}({{#allParams}}{{paramName}}: {{#isEnum}}{{#isContainer}}{{{dataType}}}{{/isContainer}}{{^isContainer}}{{{datatypeWithEnum}}}_{{operationId}}{{/isContainer}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{^required}}? = nil{{/required}}{{^-last}}, {{/-last}}{{/allParams}}) -> Observable<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}> {{/useRxSwift}} +{{#useVapor}} + {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} class func {{operationId}}({{#allParams}}{{paramName}}: {{#isEnum}}{{#isContainer}}{{{dataType}}}{{/isContainer}}{{^isContainer}}{{{datatypeWithEnum}}}_{{operationId}}{{/isContainer}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{^required}}? = nil{{/required}}{{^-last}}, {{/-last}}{{/allParams}}{{#hasParams}}, {{/hasParams}}headers: HTTPHeaders = {{projectName}}.customHeaders, beforeSend: (inout ClientRequest) throws -> () = { _ in }) -> EventLoopFuture<{{#lambda.titlecase}}{{operationId}}{{/lambda.titlecase}}> +{{/useVapor}} ``` {{{summary}}}{{#notes}} @@ -39,6 +44,7 @@ import {{{projectName}}} {{^usePromiseKit}} {{^useRxSwift}} +{{^useVapor}} {{#summary}} // {{{.}}} {{/summary}} @@ -52,6 +58,7 @@ import {{{projectName}}} dump(response) } } +{{/useVapor}} {{/useRxSwift}} {{/usePromiseKit}} {{#usePromiseKit}} @@ -69,6 +76,27 @@ import {{{projectName}}} {{#useRxSwift}} // TODO RxSwift sample code not yet implemented. To contribute, please open a ticket via http://github.com/OpenAPITools/openapi-generator/issues/new {{/useRxSwift}} +{{#useVapor}} +{{#summary}} +// {{{.}}} +{{/summary}} +{{classname}}.{{{operationId}}}({{#allParams}}{{paramName}}: {{paramName}}{{^-last}}, {{/-last}}{{/allParams}}).whenComplete { result in + switch result { + case .failure(let error): + // process error + case .success(let response): + switch response { + // process decoded response value or raw ClientResponse + {{#responses}} + case .http{{code}}(let value, let raw): + {{/responses}} + {{^hasDefaultResponse}} + case .http0(let value, let raw): + {{/hasDefaultResponse}} + } + } +} +{{/useVapor}} ``` ### Parameters @@ -80,7 +108,23 @@ Name | Type | Description | Notes ### Return type +{{#useVapor}} +#### {{#lambda.titlecase}}{{operationId}}{{/lambda.titlecase}} + +```swift +{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} enum {{#lambda.titlecase}}{{operationId}}{{/lambda.titlecase}} { + {{#responses}} + case http{{code}}(value: {{#dataType}}{{dataType}}?{{/dataType}}{{^dataType}}Void?{{/dataType}}, raw: ClientResponse) + {{/responses}} + {{^hasDefaultResponse}} + case http0(value: {{#returnType}}{{returnType}}?{{/returnType}}{{^returnType}}Void?{{/returnType}}, raw: ClientResponse) + {{/hasDefaultResponse}} +} +``` +{{/useVapor}} +{{^useVapor}} {{#returnType}}{{#returnTypeIsPrimitive}}**{{{returnType}}}**{{/returnTypeIsPrimitive}}{{^returnTypeIsPrimitive}}[**{{{returnType}}}**]({{returnBaseType}}.md){{/returnTypeIsPrimitive}}{{/returnType}}{{^returnType}}Void (empty response body){{/returnType}} +{{/useVapor}} ### Authorization diff --git a/modules/openapi-generator/src/main/resources/swift5/gitignore.mustache b/modules/openapi-generator/src/main/resources/swift5/gitignore.mustache index 5e5d5cebcf4..627d360a903 100644 --- a/modules/openapi-generator/src/main/resources/swift5/gitignore.mustache +++ b/modules/openapi-generator/src/main/resources/swift5/gitignore.mustache @@ -1,12 +1,22 @@ +# Created by https://www.toptal.com/developers/gitignore/api/swift,xcode +# Edit at https://www.toptal.com/developers/gitignore?templates=swift,xcode + +### Swift ### # Xcode # # gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore -## Build generated -build/ -DerivedData +## User settings +xcuserdata/ -## Various settings +## compatibility with Xcode 8 and earlier (ignoring not required starting Xcode 9) +*.xcscmblueprint +*.xccheckout + +## compatibility with Xcode 3 and earlier (ignoring not required starting Xcode 4) +build/ +DerivedData/ +*.moved-aside *.pbxuser !default.pbxuser *.mode1v3 @@ -15,49 +25,81 @@ DerivedData !default.mode2v3 *.perspectivev3 !default.perspectivev3 -xcuserdata - -## Other -*.xccheckout -*.moved-aside -*.xcuserstate -*.xcscmblueprint ## Obj-C/Swift specific *.hmap + +## App packaging *.ipa +*.dSYM.zip +*.dSYM ## Playgrounds timeline.xctimeline playground.xcworkspace # Swift Package Manager -# # Add this line if you want to avoid checking in source code from Swift Package Manager dependencies. # Packages/ +# Package.pins +# Package.resolved +# *.xcodeproj +# Xcode automatically generates this directory with a .xcworkspacedata file and xcuserdata +# hence it is not needed unless you have added a package configuration file to your project +# .swiftpm + .build/ # CocoaPods -# # We recommend against adding the Pods directory to your .gitignore. However # you should judge for yourself, the pros and cons are mentioned at: # https://guides.cocoapods.org/using/using-cocoapods.html#should-i-check-the-pods-directory-into-source-control -# # Pods/ +# Add this line if you want to avoid checking in source code from the Xcode workspace +# *.xcworkspace # Carthage -# # Add this line if you want to avoid checking in source code from Carthage dependencies. # Carthage/Checkouts -Carthage/Build +Carthage/Build/ + +# Add this lines if you are using Accio dependency management (Deprecated since Xcode 12) +# Dependencies/ +# .accio/ # fastlane -# -# It is recommended to not store the screenshots in the git repo. Instead, use fastlane to re-generate the -# screenshots whenever they are needed. +# It is recommended to not store the screenshots in the git repo. +# Instead, use fastlane to re-generate the screenshots whenever they are needed. # For more information about the recommended setup visit: -# https://github.com/fastlane/fastlane/blob/master/docs/Gitignore.md +# https://docs.fastlane.tools/best-practices/source-control/#source-control fastlane/report.xml -fastlane/screenshots +fastlane/Preview.html +fastlane/screenshots/**/*.png +fastlane/test_output + +# Code Injection +# After new code Injection tools there's a generated folder /iOSInjectionProject +# https://github.com/johnno1962/injectionforxcode + +iOSInjectionProject/ + +### Xcode ### +# Xcode +# gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore + + + + +## Gcc Patch +/*.gcno + +### Xcode Patch ### +*.xcodeproj/* +!*.xcodeproj/project.pbxproj +!*.xcodeproj/xcshareddata/ +!*.xcworkspace/contents.xcworkspacedata +**/xcshareddata/WorkspaceSettings.xcsettings + +# End of https://www.toptal.com/developers/gitignore/api/swift,xcode diff --git a/modules/openapi-generator/src/main/resources/swift5/libraries/alamofire/AlamofireImplementations.mustache b/modules/openapi-generator/src/main/resources/swift5/libraries/alamofire/AlamofireImplementations.mustache index 71e9670965b..4d53fe6680f 100644 --- a/modules/openapi-generator/src/main/resources/swift5/libraries/alamofire/AlamofireImplementations.mustache +++ b/modules/openapi-generator/src/main/resources/swift5/libraries/alamofire/AlamofireImplementations.mustache @@ -40,7 +40,7 @@ private var managerStore = SynchronizedDictionary URLRequest? { guard let xMethod = Alamofire.HTTPMethod(rawValue: method) else { - fatalError("Unsuported Http method - \(method)") + fatalError("Unsupported Http method - \(method)") } let encoding: ParameterEncoding @@ -76,14 +76,14 @@ private var managerStore = SynchronizedDictionary, Error>) -> Void) { + override {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} func execute(_ apiResponseQueue: DispatchQueue = {{projectName}}.apiResponseQueue, _ completion: @escaping (_ result: Swift.Result, Error>) -> Void) { let managerId = UUID().uuidString // Create a new manager for each request to customize its request header let manager = createSessionManager() managerStore[managerId] = manager guard let xMethod = Alamofire.HTTPMethod(rawValue: method) else { - fatalError("Unsuported Http method - \(method)") + fatalError("Unsupported Http method - \(method)") } let encoding: ParameterEncoding? @@ -133,7 +133,7 @@ private var managerStore = SynchronizedDictionary() return modifiedRequest } - override {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} func execute(_ apiResponseQueue: DispatchQueue = {{projectName}}API.apiResponseQueue, _ completion: @escaping (_ result: Swift.Result, Error>) -> Void) { + override {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} func execute(_ apiResponseQueue: DispatchQueue = {{projectName}}.apiResponseQueue, _ completion: @escaping (_ result: Swift.Result, Error>) -> Void) { let urlSessionId = UUID().uuidString // Create a new manager for each request to customize its request header let urlSession = createURLSession() urlSessionStore[urlSessionId] = urlSession guard let xMethod = HTTPMethod(rawValue: method) else { - fatalError("Unsuported Http method - \(method)") + fatalError("Unsupported Http method - \(method)") } let encoding: ParameterEncoding @@ -119,7 +119,7 @@ private var urlSessionStore = SynchronizedDictionary() } else if contentType == "application/x-www-form-urlencoded" { encoding = FormURLEncoding() } else { - fatalError("Unsuported Media Type - \(contentType)") + fatalError("Unsupported Media Type - \(contentType)") } } @@ -205,16 +205,18 @@ private var urlSessionStore = SynchronizedDictionary() } let fileManager = FileManager.default - let documentsDirectory = fileManager.urls(for: .documentDirectory, in: .userDomainMask)[0] + let cachesDirectory = fileManager.urls(for: .cachesDirectory, in: .userDomainMask)[0] let requestURL = try getURL(from: urlRequest) var requestPath = try getPath(from: requestURL) if let headerFileName = getFileName(fromContentDisposition: httpResponse.allHeaderFields["Content-Disposition"] as? String) { requestPath = requestPath.appending("/\(headerFileName)") + } else { + requestPath = requestPath.appending("/tmp.{{projectName}}.\(UUID().uuidString)") } - let filePath = documentsDirectory.appendingPathComponent(requestPath) + let filePath = cachesDirectory.appendingPathComponent(requestPath) let directoryPath = filePath.deletingLastPathComponent().path try fileManager.createDirectory(atPath: directoryPath, withIntermediateDirectories: true, attributes: nil) @@ -232,6 +234,10 @@ private var urlSessionStore = SynchronizedDictionary() completion(.success(Response(response: httpResponse, body: nil))) + case is Data.Type: + + completion(.success(Response(response: httpResponse, body: data as? T))) + default: completion(.success(Response(response: httpResponse, body: data as? T))) @@ -244,7 +250,7 @@ private var urlSessionStore = SynchronizedDictionary() for (key, value) in headers { httpHeaders[key] = value } - for (key, value) in {{projectName}}API.customHeaders { + for (key, value) in {{projectName}}.customHeaders { httpHeaders[key] = value } return httpHeaders @@ -328,6 +334,43 @@ private var urlSessionStore = SynchronizedDictionary() completion(.success(Response(response: httpResponse, body: body as? T))) + case is URL.Type: + do { + + guard error == nil else { + throw DownloadException.responseFailed + } + + guard let data = data else { + throw DownloadException.responseDataMissing + } + + let fileManager = FileManager.default + let cachesDirectory = fileManager.urls(for: .cachesDirectory, in: .userDomainMask)[0] + let requestURL = try getURL(from: urlRequest) + + var requestPath = try getPath(from: requestURL) + + if let headerFileName = getFileName(fromContentDisposition: httpResponse.allHeaderFields["Content-Disposition"] as? String) { + requestPath = requestPath.appending("/\(headerFileName)") + } else { + requestPath = requestPath.appending("/tmp.{{projectName}}.\(UUID().uuidString)") + } + + let filePath = cachesDirectory.appendingPathComponent(requestPath) + let directoryPath = filePath.deletingLastPathComponent().path + + try fileManager.createDirectory(atPath: directoryPath, withIntermediateDirectories: true, attributes: nil) + try data.write(to: filePath, options: .atomic) + + completion(.success(Response(response: httpResponse, body: filePath as? T))) + + } catch let requestParserError as DownloadException { + completion(.failure(ErrorResponse.error(400, data, response, requestParserError))) + } catch { + completion(.failure(ErrorResponse.error(400, data, response, error))) + } + case is Void.Type: completion(.success(Response(response: httpResponse, body: nil))) diff --git a/modules/openapi-generator/src/main/resources/swift5/model.mustache b/modules/openapi-generator/src/main/resources/swift5/model.mustache index 7ea71a27f23..47df79b7c7d 100644 --- a/modules/openapi-generator/src/main/resources/swift5/model.mustache +++ b/modules/openapi-generator/src/main/resources/swift5/model.mustache @@ -6,11 +6,25 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif{{#useVapor}} +import Vapor{{/useVapor}} +{{#swiftUseApiNamespace}} + +@available(*, deprecated, renamed: "{{projectName}}.{{classname}}") +{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} typealias {{classname}} = {{projectName}}.{{classname}} + +extension {{projectName}} { +{{/swiftUseApiNamespace}} {{#description}} /** {{description}} */{{/description}}{{#isDeprecated}} -@available(*, deprecated, message: "This schema is deprecated."){{/isDeprecated}}{{#isArray}} +@available(*, deprecated, message: "This schema is deprecated."){{/isDeprecated}}{{#vendorExtensions.x-is-one-of-interface}} +{{> modelOneOf}}{{/vendorExtensions.x-is-one-of-interface}}{{^vendorExtensions.x-is-one-of-interface}}{{#isArray}} {{> modelArray}}{{/isArray}}{{^isArray}}{{#isEnum}} {{> modelEnum}}{{/isEnum}}{{^isEnum}} -{{> modelObject}}{{/isEnum}}{{/isArray}}{{/model}}{{/models}} +{{> modelObject}}{{/isEnum}}{{/isArray}}{{/vendorExtensions.x-is-one-of-interface}}{{/model}}{{/models}} +{{#swiftUseApiNamespace}} +} +{{/swiftUseApiNamespace}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/swift5/modelEnum.mustache b/modules/openapi-generator/src/main/resources/swift5/modelEnum.mustache index b10347d63db..4d868682a1e 100644 --- a/modules/openapi-generator/src/main/resources/swift5/modelEnum.mustache +++ b/modules/openapi-generator/src/main/resources/swift5/modelEnum.mustache @@ -1,7 +1,7 @@ -{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} enum {{classname}}: {{dataType}}, Codable, CaseIterable { +{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} enum {{classname}}: {{dataType}}, {{#useVapor}}Content, Hashable{{/useVapor}}{{^useVapor}}Codable{{/useVapor}}, CaseIterable { {{#allowableValues}} {{#enumVars}} - case {{name}} = {{{value}}} + case {{{name}}} = {{{value}}} {{/enumVars}} {{/allowableValues}} } \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/swift5/modelInlineEnumDeclaration.mustache b/modules/openapi-generator/src/main/resources/swift5/modelInlineEnumDeclaration.mustache index 1c749e0b6cd..039bae3cb73 100644 --- a/modules/openapi-generator/src/main/resources/swift5/modelInlineEnumDeclaration.mustache +++ b/modules/openapi-generator/src/main/resources/swift5/modelInlineEnumDeclaration.mustache @@ -1,7 +1,7 @@ - {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} enum {{enumName}}: {{^isContainer}}{{dataType}}{{/isContainer}}{{#isContainer}}String{{/isContainer}}, Codable, CaseIterable { + {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} enum {{enumName}}: {{^isContainer}}{{dataType}}{{/isContainer}}{{#isContainer}}String{{/isContainer}}, {{#useVapor}}Content, Hashable{{/useVapor}}{{^useVapor}}Codable{{/useVapor}}, CaseIterable { {{#allowableValues}} {{#enumVars}} - case {{name}} = {{{value}}} + case {{{name}}} = {{{value}}} {{/enumVars}} {{/allowableValues}} } \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/swift5/modelObject.mustache b/modules/openapi-generator/src/main/resources/swift5/modelObject.mustache index c119f723a2a..450d95f1f76 100644 --- a/modules/openapi-generator/src/main/resources/swift5/modelObject.mustache +++ b/modules/openapi-generator/src/main/resources/swift5/modelObject.mustache @@ -1,4 +1,4 @@ -{{^objcCompatible}}{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} {{#useClasses}}final class{{/useClasses}}{{^useClasses}}struct{{/useClasses}} {{classname}}: Codable, Hashable { +{{^objcCompatible}}{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} {{#useClasses}}final class{{/useClasses}}{{^useClasses}}struct{{/useClasses}} {{{classname}}}: {{#useVapor}}Content{{/useVapor}}{{^useVapor}}Codable{{/useVapor}}{{#vendorExtensions.x-swift-hashable}}, Hashable{{/vendorExtensions.x-swift-hashable}} { {{/objcCompatible}}{{#objcCompatible}}@objc {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} class {{classname}}: NSObject, Codable { {{/objcCompatible}} @@ -9,12 +9,12 @@ {{/allVars}} {{#allVars}} {{#isEnum}} - {{#description}}/** {{description}} */ + {{#description}}/** {{{description}}} */ {{/description}}{{#deprecated}}@available(*, deprecated, message: "This property is deprecated.") {{/deprecated}}{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} {{#readonlyProperties}}private(set) {{/readonlyProperties}}var {{{name}}}: {{{datatypeWithEnum}}}{{#required}}{{#isNullable}}?{{/isNullable}}{{/required}}{{^required}}?{{/required}}{{#defaultValue}} = {{{defaultValue}}}{{/defaultValue}} {{/isEnum}} {{^isEnum}} - {{#description}}/** {{description}} */ + {{#description}}/** {{{description}}} */ {{/description}}{{#deprecated}}@available(*, deprecated, message: "This property is deprecated.") {{/deprecated}}{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} {{#readonlyProperties}}private(set) {{/readonlyProperties}}var {{{name}}}: {{{datatype}}}{{#required}}{{#isNullable}}?{{/isNullable}}{{/required}}{{^required}}?{{/required}}{{#defaultValue}} = {{{defaultValue}}}{{/defaultValue}} {{#objcCompatible}} @@ -36,12 +36,13 @@ {{/allVars}} } {{/hasVars}} + {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} enum CodingKeys: {{#hasVars}}String, {{/hasVars}}CodingKey, CaseIterable { {{#allVars}} case {{{name}}}{{#vendorExtensions.x-codegen-escaped-property-name}} = "{{{baseName}}}"{{/vendorExtensions.x-codegen-escaped-property-name}} {{/allVars}} - } -{{#additionalPropertiesType}} + }{{#generateModelAdditionalProperties}}{{#additionalPropertiesType}} + {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} {{#readonlyProperties}}private(set) {{/readonlyProperties}}var additionalProperties: [String: {{{additionalPropertiesType}}}] = [:] {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} subscript(key: String) -> {{{additionalPropertiesType}}}? { @@ -55,8 +56,7 @@ set { additionalProperties[key] = newValue } - } -{{/additionalPropertiesType}} + }{{/additionalPropertiesType}}{{/generateModelAdditionalProperties}} // Encodable protocol methods @@ -65,42 +65,41 @@ {{#allVars}} try container.encode{{^required}}IfPresent{{/required}}({{{name}}}, forKey: .{{{name}}}) {{/allVars}} + {{#generateModelAdditionalProperties}} {{#additionalPropertiesType}} var additionalPropertiesContainer = encoder.container(keyedBy: String.self) try additionalPropertiesContainer.encodeMap(additionalProperties) {{/additionalPropertiesType}} - } + {{/generateModelAdditionalProperties}} + }{{#generateModelAdditionalProperties}}{{#additionalPropertiesType}} -{{#additionalPropertiesType}} // Decodable protocol methods {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}}{{#objcCompatible}} required{{/objcCompatible}} init(from decoder: Decoder) throws { - let container = try decoder.container(keyedBy: String.self) + let container = try decoder.container(keyedBy: CodingKeys.self) {{#allVars}} - {{{name}}} = try container.decode{{#required}}{{#isNullable}}IfPresent{{/isNullable}}{{/required}}{{^required}}IfPresent{{/required}}({{{datatypeWithEnum}}}.self, forKey: "{{{baseName}}}") + {{{name}}} = try container.decode{{#required}}{{#isNullable}}IfPresent{{/isNullable}}{{/required}}{{^required}}IfPresent{{/required}}({{{datatypeWithEnum}}}.self, forKey: .{{{name}}}) {{/allVars}} var nonAdditionalPropertyKeys = Set() {{#allVars}} nonAdditionalPropertyKeys.insert("{{{baseName}}}") {{/allVars}} - additionalProperties = try container.decodeMap({{{additionalPropertiesType}}}.self, excludedKeys: nonAdditionalPropertyKeys) - } -{{/additionalPropertiesType}} + let additionalPropertiesContainer = try decoder.container(keyedBy: String.self) + additionalProperties = try additionalPropertiesContainer.decodeMap({{{additionalPropertiesType}}}.self, excludedKeys: nonAdditionalPropertyKeys) + }{{/additionalPropertiesType}}{{/generateModelAdditionalProperties}}{{^objcCompatible}}{{#useClasses}}{{#vendorExtensions.x-swift-hashable}} -{{^objcCompatible}}{{#useClasses}} {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} static func == (lhs: {{classname}}, rhs: {{classname}}) -> Bool { {{#allVars}} lhs.{{{name}}} == rhs.{{{name}}}{{^-last}} &&{{/-last}} {{/allVars}} - {{#additionalPropertiesType}}{{#hasVars}}&& {{/hasVars}}lhs.additionalProperties == rhs.additionalProperties{{/additionalPropertiesType}} + {{#generateModelAdditionalProperties}}{{#additionalPropertiesType}}{{#hasVars}}&& {{/hasVars}}lhs.additionalProperties == rhs.additionalProperties{{/additionalPropertiesType}}{{/generateModelAdditionalProperties}} } {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} func hash(into hasher: inout Hasher) { {{#allVars}} hasher.combine({{{name}}}{{^required}}?{{/required}}.hashValue) {{/allVars}} - {{#additionalPropertiesType}}hasher.combine(additionalProperties.hashValue){{/additionalPropertiesType}} - } -{{/useClasses}}{{/objcCompatible}} -} \ No newline at end of file + {{#generateModelAdditionalProperties}}{{#additionalPropertiesType}}hasher.combine(additionalProperties.hashValue){{/additionalPropertiesType}}{{/generateModelAdditionalProperties}} + }{{/vendorExtensions.x-swift-hashable}}{{/useClasses}}{{/objcCompatible}} +} diff --git a/modules/openapi-generator/src/main/resources/swift5/modelOneOf.mustache b/modules/openapi-generator/src/main/resources/swift5/modelOneOf.mustache new file mode 100644 index 00000000000..fae34faa975 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/swift5/modelOneOf.mustache @@ -0,0 +1,31 @@ +public enum {{classname}}: {{#useVapor}}Content{{/useVapor}}{{^useVapor}}Codable{{/useVapor}} { + {{#oneOf}} + case type{{.}}({{.}}) + {{/oneOf}} + + public func encode(to encoder: Encoder) throws { + var container = encoder.singleValueContainer() + switch self { + {{#oneOf}} + case .type{{.}}(let value): + try container.encode(value) + {{/oneOf}} + } + } + + public init(from decoder: Decoder) throws { + let container = try decoder.singleValueContainer() + {{#oneOf}} + {{#-first}} + if let value = try? container.decode({{.}}.self) { + {{/-first}} + {{^-first}} + } else if let value = try? container.decode({{.}}.self) { + {{/-first}} + self = .type{{.}}(value) + {{/oneOf}} + } else { + throw DecodingError.typeMismatch(Self.Type.self, .init(codingPath: decoder.codingPath, debugDescription: "Unable to decode instance of {{classname}}")) + } + } +} diff --git a/modules/openapi-generator/src/main/resources/typescript-angular/api.service.mustache b/modules/openapi-generator/src/main/resources/typescript-angular/api.service.mustache index 8f66fcf6f9e..4fe3186f1ad 100644 --- a/modules/openapi-generator/src/main/resources/typescript-angular/api.service.mustache +++ b/modules/openapi-generator/src/main/resources/typescript-angular/api.service.mustache @@ -93,11 +93,16 @@ export class {{classname}} { {{/hasSomeFormParams}} private addToHttpParams(httpParams: HttpParams, value: any, key?: string): HttpParams { + {{#isQueryParamObjectFormatJson}} + httpParams = this.addToHttpParamsRecursive(httpParams, value, key); + {{/isQueryParamObjectFormatJson}} + {{^isQueryParamObjectFormatJson}} if (typeof value === "object" && value instanceof Date === false) { httpParams = this.addToHttpParamsRecursive(httpParams, value); } else { httpParams = this.addToHttpParamsRecursive(httpParams, value, key); } + {{/isQueryParamObjectFormatJson}} return httpParams; } diff --git a/modules/openapi-generator/src/main/resources/typescript-axios/apiInner.mustache b/modules/openapi-generator/src/main/resources/typescript-axios/apiInner.mustache index 0550c77b4d8..b425c807a24 100644 --- a/modules/openapi-generator/src/main/resources/typescript-axios/apiInner.mustache +++ b/modules/openapi-generator/src/main/resources/typescript-axios/apiInner.mustache @@ -34,7 +34,8 @@ export const {{classname}}AxiosParamCreator = function (configuration?: Configur {{#allParams}} * @param {{=<% %>=}}{<%&dataType%>}<%={{ }}=%> {{^required}}[{{/required}}{{paramName}}{{^required}}]{{/required}} {{description}} {{/allParams}} - * @param {*} [options] Override http request option. + * @param {*} [options] Override http request option.{{#isDeprecated}} + * @deprecated{{/isDeprecated}} * @throws {RequiredError} */ {{nickname}}: async ({{#allParams}}{{paramName}}{{^required}}?{{/required}}: {{{dataType}}}, {{/allParams}}options: any = {}): Promise => { @@ -217,7 +218,8 @@ export const {{classname}}Fp = function(configuration?: Configuration) { {{#allParams}} * @param {{=<% %>=}}{<%&dataType%>}<%={{ }}=%> {{^required}}[{{/required}}{{paramName}}{{^required}}]{{/required}} {{description}} {{/allParams}} - * @param {*} [options] Override http request option. + * @param {*} [options] Override http request option.{{#isDeprecated}} + * @deprecated{{/isDeprecated}} * @throws {RequiredError} */ async {{nickname}}({{#allParams}}{{paramName}}{{^required}}?{{/required}}: {{{dataType}}}, {{/allParams}}options?: any): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}}>> { @@ -245,7 +247,8 @@ export const {{classname}}Factory = function (configuration?: Configuration, bas {{#allParams}} * @param {{=<% %>=}}{<%&dataType%>}<%={{ }}=%> {{^required}}[{{/required}}{{paramName}}{{^required}}]{{/required}} {{description}} {{/allParams}} - * @param {*} [options] Override http request option. + * @param {*} [options] Override http request option.{{#isDeprecated}} + * @deprecated{{/isDeprecated}} * @throws {RequiredError} */ {{nickname}}({{#allParams}}{{paramName}}{{^required}}?{{/required}}: {{{dataType}}}, {{/allParams}}options?: any): AxiosPromise<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}}> { @@ -272,7 +275,8 @@ export interface {{classname}}Interface { {{#allParams}} * @param {{=<% %>=}}{<%&dataType%>}<%={{ }}=%> {{^required}}[{{/required}}{{paramName}}{{^required}}]{{/required}} {{description}} {{/allParams}} - * @param {*} [options] Override http request option. + * @param {*} [options] Override http request option.{{#isDeprecated}} + * @deprecated{{/isDeprecated}} * @throws {RequiredError} * @memberof {{classname}}Interface */ @@ -336,7 +340,8 @@ export class {{classname}} extends BaseAPI { * @param {{=<% %>=}}{<%&dataType%>}<%={{ }}=%> {{^required}}[{{/required}}{{paramName}}{{^required}}]{{/required}} {{description}} {{/allParams}} {{/useSingleRequestParameter}} - * @param {*} [options] Override http request option. + * @param {*} [options] Override http request option.{{#isDeprecated}} + * @deprecated{{/isDeprecated}} * @throws {RequiredError} * @memberof {{classname}} */ diff --git a/modules/openapi-generator/src/main/resources/typescript-axios/modelEnum.mustache b/modules/openapi-generator/src/main/resources/typescript-axios/modelEnum.mustache index 1e25a6e2f02..7ff0379b4c3 100644 --- a/modules/openapi-generator/src/main/resources/typescript-axios/modelEnum.mustache +++ b/modules/openapi-generator/src/main/resources/typescript-axios/modelEnum.mustache @@ -3,6 +3,11 @@ * @export * @enum {string} */ +{{#isBoolean}} +export type {{classname}} = {{#allowableValues}}{{#enumVars}}{{{value}}}{{^-last}} | {{/-last}}{{/enumVars}}{{/allowableValues}} +{{/isBoolean}} + +{{^isBoolean}} export enum {{classname}} { {{#allowableValues}} {{#enumVars}} @@ -15,3 +20,4 @@ export enum {{classname}} { {{/enumVars}} {{/allowableValues}} } +{{/isBoolean}} diff --git a/modules/openapi-generator/src/main/resources/typescript-fetch/ApiEntitiesRecord.mustache b/modules/openapi-generator/src/main/resources/typescript-fetch/ApiEntitiesRecord.mustache new file mode 100644 index 00000000000..5860cc04b37 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/typescript-fetch/ApiEntitiesRecord.mustache @@ -0,0 +1,26 @@ +import {Map, Record, RecordOf} from 'immutable'; + +import { +{{#models}} +{{#model}} +{{#isEntity}} + {{classname}}RecordEntity, +{{/isEntity}} +{{/model}} +{{/models}} +} from "./models" + +export const ApiEntitiesRecordProps = { + recType: "ApiEntitiesRecord" as "ApiEntitiesRecord", +{{#models}} +{{#model}} +{{#isEntity}} + {{#lambda.camelcase}}{{classname}}{{/lambda.camelcase}}: ({{classname}}RecordEntity(), Map()), +{{/isEntity}} +{{/model}} +{{/models}} +}; + +export type ApiEntitiesRecordPropsType = typeof ApiEntitiesRecordProps; +export const ApiEntitiesRecord = Record(ApiEntitiesRecordProps, ApiEntitiesRecordProps.recType); +export type ApiEntitiesRecord = RecordOf; \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/typescript-fetch/ApiEntitiesReducer.mustache b/modules/openapi-generator/src/main/resources/typescript-fetch/ApiEntitiesReducer.mustache new file mode 100644 index 00000000000..9f607ac090f --- /dev/null +++ b/modules/openapi-generator/src/main/resources/typescript-fetch/ApiEntitiesReducer.mustache @@ -0,0 +1,21 @@ +import {ApiEntitiesRecord} from "./ApiEntitiesRecord"; +import {ReducerBuilder} from "redux-ts-simple"; +import {normalizedEntities} from "./runtimeSagasAndRecords"; + +export const ApiEntitiesReducer = new ReducerBuilder(ApiEntitiesRecord()) + .on(normalizedEntities, (state, action): ApiEntitiesRecord => { + const {entities} = action.payload; + return state.withMutations(mutableState => { + for (const entityKey in entities) { + const entityMap = entities[entityKey]; + const currentEntityMap = mutableState.get(entityKey as any); + if (currentEntityMap) { + let mergedEntityMap = currentEntityMap.mergeDeep(entityMap); + if (!mergedEntityMap.equals(currentEntityMap)) { + mutableState.set(entityKey as any, mergedEntityMap); + } + } + } + }); + }) + .build(); \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/typescript-fetch/ApiEntitiesSelectors.mustache b/modules/openapi-generator/src/main/resources/typescript-fetch/ApiEntitiesSelectors.mustache new file mode 100644 index 00000000000..9eaffec0dfe --- /dev/null +++ b/modules/openapi-generator/src/main/resources/typescript-fetch/ApiEntitiesSelectors.mustache @@ -0,0 +1,5 @@ +export let getApiEntitiesState: (state: any) => any = (state: any) => state.app.apiEntities; + +export function setApiEntitiesStateGetter(getter: (state: any) => any) { // Use this to customize the location where you have placed your ApiEntitiesRecord in your project. + getApiEntitiesState = getter; +} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/typescript-fetch/allSagas.mustache b/modules/openapi-generator/src/main/resources/typescript-fetch/allSagas.mustache new file mode 100644 index 00000000000..018140fc886 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/typescript-fetch/allSagas.mustache @@ -0,0 +1,19 @@ +import {all, fork} from "redux-saga/effects"; + +import { +{{#apiInfo}} +{{#apis}} + {{#lambda.camelcase}}{{classFilename}}{{/lambda.camelcase}}AllSagas, +{{/apis}} +{{/apiInfo}} +} from "./"; + +export function *allApiSagas() { + yield all([ +{{#apiInfo}} +{{#apis}} + fork({{#lambda.camelcase}}{{classFilename}}{{/lambda.camelcase}}AllSagas), +{{/apis}} +{{/apiInfo}} + ]); +} diff --git a/modules/openapi-generator/src/main/resources/typescript-fetch/apis.index.mustache b/modules/openapi-generator/src/main/resources/typescript-fetch/apis.index.mustache index 6286332d7bc..44f8c989936 100644 --- a/modules/openapi-generator/src/main/resources/typescript-fetch/apis.index.mustache +++ b/modules/openapi-generator/src/main/resources/typescript-fetch/apis.index.mustache @@ -1,7 +1,14 @@ +{{#useSagaAndRecords}} +export * from './SagaApiManager' +export * from './allSagas' +{{/useSagaAndRecords}} {{#apiInfo}} {{#apis}} {{#operations}} export * from './{{ classFilename }}'; +{{#useSagaAndRecords}} +export * from './{{{ classFilename }}}Sagas'; +{{/useSagaAndRecords}} {{/operations}} {{/apis}} {{/apiInfo}} 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 8466deb2853..851b9ce3831 100644 --- a/modules/openapi-generator/src/main/resources/typescript-fetch/apis.mustache +++ b/modules/openapi-generator/src/main/resources/typescript-fetch/apis.mustache @@ -167,7 +167,7 @@ export class {{classname}} extends runtime.BaseAPI { {{#isBasicBearer}} if (this.configuration && this.configuration.accessToken) { const token = this.configuration.accessToken; - const tokenString = typeof token === 'function' ? token("{{name}}", [{{#scopes}}"{{{scope}}}"{{^-last}}, {{/-last}}{{/scopes}}]) : token; + const tokenString = await token("{{name}}", [{{#scopes}}"{{{scope}}}"{{^-last}}, {{/-last}}{{/scopes}}]); if (tokenString) { headerParameters["Authorization"] = `Bearer ${tokenString}`; @@ -192,11 +192,7 @@ export class {{classname}} extends runtime.BaseAPI { {{#isOAuth}} if (this.configuration && this.configuration.accessToken) { // oauth required - if (typeof this.configuration.accessToken === 'function') { - headerParameters["Authorization"] = this.configuration.accessToken("{{name}}", [{{#scopes}}"{{{scope}}}"{{^-last}}, {{/-last}}{{/scopes}}]); - } else { - headerParameters["Authorization"] = this.configuration.accessToken; - } + headerParameters["Authorization"] = await this.configuration.accessToken("{{name}}", [{{#scopes}}"{{{scope}}}"{{^-last}}, {{/-last}}{{/scopes}}]); } {{/isOAuth}} diff --git a/modules/openapi-generator/src/main/resources/typescript-fetch/index.mustache b/modules/openapi-generator/src/main/resources/typescript-fetch/index.mustache index e548c9df6b2..ede27a38747 100644 --- a/modules/openapi-generator/src/main/resources/typescript-fetch/index.mustache +++ b/modules/openapi-generator/src/main/resources/typescript-fetch/index.mustache @@ -1,4 +1,10 @@ export * from './runtime'; +{{#useSagaAndRecords}} +export * from './runtimeSagasAndRecords'; +export * from './ApiEntitiesRecord'; +export * from './ApiEntitiesReducer'; +export * from './ApiEntitiesSelectors'; +{{/useSagaAndRecords}} {{#apiInfo}} {{#apis.0}} export * from './apis'; diff --git a/modules/openapi-generator/src/main/resources/typescript-fetch/models.index.mustache b/modules/openapi-generator/src/main/resources/typescript-fetch/models.index.mustache index 7331df67ca9..1be5a347b38 100644 --- a/modules/openapi-generator/src/main/resources/typescript-fetch/models.index.mustache +++ b/modules/openapi-generator/src/main/resources/typescript-fetch/models.index.mustache @@ -2,7 +2,13 @@ {{#model}} {{^withoutRuntimeChecks}} export * from './{{{ classFilename }}}'; -{{/withoutRuntimeChecks}}{{#withoutRuntimeChecks}} +{{#useSagaAndRecords}} +{{^isEnum}} +export * from './{{{ classFilename }}}Record'; +{{/isEnum}} +{{/useSagaAndRecords}} +{{/withoutRuntimeChecks}} +{{#withoutRuntimeChecks}} {{#isEnum}} {{>modelEnumInterfaces}} {{/isEnum}} diff --git a/modules/openapi-generator/src/main/resources/typescript-fetch/package.mustache b/modules/openapi-generator/src/main/resources/typescript-fetch/package.mustache index b7c3d544af1..c082bbf3982 100644 --- a/modules/openapi-generator/src/main/resources/typescript-fetch/package.mustache +++ b/modules/openapi-generator/src/main/resources/typescript-fetch/package.mustache @@ -3,14 +3,27 @@ "version": "{{npmVersion}}", "description": "OpenAPI client for {{npmName}}", "author": "OpenAPI-Generator", +{{#packageAsSourceOnlyLibrary}} + "main": "./index.ts", +{{/packageAsSourceOnlyLibrary}} +{{^packageAsSourceOnlyLibrary}} "main": "./dist/index.js", "typings": "./dist/index.d.ts", "scripts": { - "build": "tsc", + "build": "tsc"{{^sagasAndRecords}}, "prepare": "npm run build" +{{/sagasAndRecords}} }, +{{/packageAsSourceOnlyLibrary}} "devDependencies": { - "typescript": "^{{#typescriptThreePlus}}3.6{{/typescriptThreePlus}}{{^typescriptThreePlus}}2.4{{/typescriptThreePlus}}" +{{#sagasAndRecords}} + "immutable": "^4.0.0-rc.12", + "normalizr": "^3.6.1", + "redux-saga": "^1.1.3", + "redux-ts-simple": "^3.2.0", + "reselect": "^4.0.0", +{{/sagasAndRecords}} + "typescript": "^{{#typescriptThreePlus}}3.9.5{{/typescriptThreePlus}}{{^typescriptThreePlus}}2.4{{/typescriptThreePlus}}" }{{#npmRepository}},{{/npmRepository}} {{#npmRepository}} "publishConfig": { diff --git a/modules/openapi-generator/src/main/resources/typescript-fetch/recordGeneric.mustache b/modules/openapi-generator/src/main/resources/typescript-fetch/recordGeneric.mustache new file mode 100644 index 00000000000..b418276e452 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/typescript-fetch/recordGeneric.mustache @@ -0,0 +1,271 @@ +import {ApiRecordUtils, knownRecordFactories{{#returnPassthrough}}, appFromJS, NormalizedRecordEntities{{/returnPassthrough}}} from "../runtimeSagasAndRecords"; +import {getApiEntitiesState} from "../ApiEntitiesSelectors" +import {List, Record, RecordOf, Map} from 'immutable'; +import {Schema, schema, NormalizedSchema} from "normalizr"; +import {select, call} from "redux-saga/effects"; + +import { + {{classname}}, +{{#vars}} +{{#isEnum}} + {{classname}}{{enumName}}, +{{/isEnum}} +{{/vars}} +} from './{{classname}}'; + +{{#imports}} +import { + {{{.}}}, +} from './{{{.}}}'; +{{/imports}} + +{{#modelImports}} +import { + {{{.}}}Record, + {{#lambda.camelcase}}{{.}}{{/lambda.camelcase}}RecordUtils +} from './{{{.}}}Record'; +{{/modelImports}} + +export const {{classname}}RecordProps = { + recType: "{{classname}}ApiRecord" as "{{classname}}ApiRecord", +{{#vars}} + {{#isArray}} + {{#items.isModel}} + {{#keepAsJSObject}} + {{name}}: {{#required}}new {{{dataType}}}(){{/required}}{{^required}}null as {{{dataType}}} | null{{/required}}, + {{/keepAsJSObject}} + {{^keepAsJSObject}} + {{name}}: ({{{items.dataType}}}Record(), {{#required}}{{{defaultValue}}}{{/required}}{{^required}}null as {{{dataTypeAlternate}}} | null{{/required}}), + {{/keepAsJSObject}} + {{/items.isModel}} + {{^items.isModel}} + {{name}}: {{#required}}{{{defaultValue}}}{{/required}}{{^required}}null as {{{dataTypeAlternate}}} | null{{/required}}, + {{/items.isModel}} + {{/isArray}} + {{#isModel}} + {{#keepAsJSObject}} + {{name}}: {{#required}}{} as any as {{{dataType}}}{{/required}}{{^required}}null as {{{dataType}}} | null{{/required}}, + {{/keepAsJSObject}} + {{^keepAsJSObject}} + {{name}}: {{#required}}{{{defaultValue}}}{{/required}}{{^required}}({{{defaultValue}}}, null as {{{dataTypeAlternate}}} | null){{/required}}, + {{/keepAsJSObject}} + {{/isModel}} + {{^isArray}} + {{^isModel}} + {{name}}: {{#required}}{{{defaultValue}}}{{/required}}{{^required}}null as {{{dataTypeAlternate}}} | null{{/required}}, + {{/isModel}} + {{/isArray}} +{{/vars}} +}; + +export type {{classname}}RecordPropsType = typeof {{classname}}RecordProps; +export const {{classname}}Record = Record({{classname}}RecordProps, {{classname}}RecordProps.recType); +export type {{classname}}Record = RecordOf<{{classname}}RecordPropsType>; + +knownRecordFactories.set({{classname}}RecordProps.recType, {{classname}}Record); + +{{#isEntity}} +export const {{classname}}RecordEntityProps = { + ...{{classname}}RecordProps, + recType: "{{classname}}ApiRecordEntity" as "{{classname}}ApiRecordEntity", +{{#vars}} + {{#isEntity}} + {{^keepAsJSObject}} + {{name}}: {{#required}}"-1"{{/required}}{{^required}}null as string | null{{/required}}, + {{/keepAsJSObject}} + {{/isEntity}} + {{#isArray}} + {{#items.isEntity}} + {{^keepAsJSObject}} + {{name}}: {{#required}}List(){{/required}}{{^required}}null as List | null{{/required}}, + {{/keepAsJSObject}} + {{/items.isEntity}} + {{/isArray}} +{{/vars}} +}; + +export type {{classname}}RecordEntityPropsType = typeof {{classname}}RecordEntityProps; +export const {{classname}}RecordEntity = Record({{classname}}RecordEntityProps, {{classname}}RecordEntityProps.recType); +export type {{classname}}RecordEntity = RecordOf<{{classname}}RecordEntityPropsType>; + +knownRecordFactories.set({{classname}}RecordEntityProps.recType, {{classname}}RecordEntity); +{{/isEntity}} + +class {{classname}}RecordUtils extends ApiRecordUtils<{{classname}}, {{classname}}Record> { + public normalize(apiObject: {{classname}}, asEntity?: boolean): {{classname}} { + (apiObject as any).recType = {{#isEntity}}asEntity ? {{classname}}RecordEntityProps.recType : {{/isEntity}}{{classname}}RecordProps.recType; +{{#vars}} + {{#isUniqueId}} + {{^required}}if (apiObject.{{name}}) { {{/required}}(apiObject as any).{{name}} = apiObject.{{name}}.{{#isArray}}map(item => item.{{/isArray}}toString(){{#isArray}}){{/isArray}};{{^required}} } {{/required}} + {{/isUniqueId}} + {{^keepAsJSObject}} + {{#isModel}} + {{^required}}if (apiObject.{{name}}) { {{/required}}{{#lambda.camelcase}}{{{dataTypeAlternate}}}{{/lambda.camelcase}}Utils.normalize(apiObject.{{name}});{{^required}} } {{/required}} + {{/isModel}} + {{#isArray}} + {{#items.isModel}} + {{^required}}if (apiObject.{{name}}) { {{/required}}{{#lambda.camelcase}}{{items.dataType}}{{/lambda.camelcase}}RecordUtils.normalizeArray(apiObject.{{name}});{{^required}} } {{/required}} + {{/items.isModel}} + {{/isArray}} + {{/keepAsJSObject}} +{{/vars}} + return apiObject; + } +{{#isEntity}} + + public getSchema(): Schema { + return new schema.Entity("{{#lambda.camelcase}}{{classname}}{{/lambda.camelcase}}", { +{{#vars}} + {{#isEntity}} + {{^keepAsJSObject}} + {{name}}: {{#lambda.camelcase}}{{{dataTypeAlternate}}}{{/lambda.camelcase}}Utils.getSchema(), + {{/keepAsJSObject}} + {{/isEntity}} + {{#isArray}} + {{#items.isEntity}} + {{^keepAsJSObject}} + {{name}}: [{{#lambda.camelcase}}{{items.dataType}}{{/lambda.camelcase}}RecordUtils.getSchema()], + {{/keepAsJSObject}} + {{/items.isEntity}} + {{/isArray}} +{{/vars}} + }); + } + + public *toInlined(entityId?: string | null) { + if (!entityId) {return undefined; } + const entity = yield select(apiEntity{{classname}}Selector, {id: entityId}); + if (!entity) {return undefined; } + + const { + recType, +{{#vars}} +{{#isEntity}} +{{^keepAsJSObject}} + {{name}}: {{name}}_original, +{{/keepAsJSObject}} +{{/isEntity}} +{{#isArray}} +{{#items.isEntity}} +{{^keepAsJSObject}} + {{name}}: {{name}}_original, +{{/keepAsJSObject}} +{{/items.isEntity}} +{{/isArray}} +{{/vars}} + ...unchangedProperties + } = entity; + + const entityProperties = { +{{#vars}} +{{#isEntity}} +{{^keepAsJSObject}} + {{name}}: {{^required}}entity.{{name}} ? {{/required}}yield call({{#lambda.camelcase}}{{{dataTypeAlternate}}}{{/lambda.camelcase}}Utils.toInlined, entity.{{name}}){{^required}} : null{{/required}}, +{{/keepAsJSObject}} +{{/isEntity}} +{{#isArray}} +{{#items.isEntity}} +{{^keepAsJSObject}} + {{name}}: {{^required}}entity.{{name}} ? {{/required}}yield call({{#lambda.camelcase}}{{items.dataType}}{{/lambda.camelcase}}RecordUtils.toInlinedArray, entity.{{name}}){{^required}} : null{{/required}}, +{{/keepAsJSObject}} +{{/items.isEntity}} +{{/isArray}} +{{/vars}} + } + + return {{classname}}Record({ + ...unchangedProperties, + ...entityProperties + }); + } + + public *toInlinedArray(entityIds: List | null) { + if (!entityIds) {return null; } + let entities = List<{{classname}}Record>(); + for (let entityIndex = 0; entityIndex < entityIds.count(); entityIndex++) { + const entity = yield call(this.toInlined, entityIds.get(entityIndex)); + if (entity) { + entities.push(entity); + } + } + return entities; + } +{{/isEntity}} + + public toApi(record: {{classname}}Record): {{classname}} { + const apiObject = super.toApi(record); +{{#vars}} + {{#isUniqueId}} + {{^required}}if (record.{{name}}) { {{/required}}apiObject.{{name}} = {{#isArray}}record.{{name}}.map(item => parseFloat(item)).toArray(){{/isArray}}{{^isArray}}parseFloat(record.{{name}}){{/isArray}};{{^required}} } {{/required}} + {{/isUniqueId}} + {{^keepAsJSObject}} + {{#isModel}} + {{^required}}if (record.{{name}}) { {{/required}}apiObject.{{name}} = {{#lambda.camelcase}}{{{dataTypeAlternate}}}{{/lambda.camelcase}}Utils.toApi(record.{{name}});{{^required}} } {{/required}} + {{/isModel}} + {{#isArray}} + {{#items.isModel}} + {{^required}}if (record.{{name}}) { {{/required}}apiObject.{{name}} = {{#lambda.camelcase}}{{items.dataType}}{{/lambda.camelcase}}RecordUtils.toApiArray(record.{{name}});{{^required}} } {{/required}} + {{/items.isModel}} + {{/isArray}} + {{/keepAsJSObject}} +{{/vars}} + return apiObject; + } +{{#returnPassthrough}} +{{#vars.1}} + + public fromApiPassthrough(apiObject: {{classname}}): {{{dataTypeAlternate}}} { + {{#isModel}} + if (!apiObject.{{{returnPassthrough}}}) {return {{{defaultValue}}}; } + const normalizedApiObject = {{#lambda.camelcase}}{{{dataTypeAlternate}}}{{/lambda.camelcase}}Utils.normalize(apiObject.{{{returnPassthrough}}}); + return appFromJS(normalizedApiObject); + {{/isModel}} + {{#isArray}} + {{#items.isModel}} + if (!apiObject.{{{returnPassthrough}}}) {return {{{defaultValue}}}; } + const normalizedApiObject = {{#lambda.camelcase}}{{items.dataType}}{{/lambda.camelcase}}RecordUtils.normalizeArray(apiObject.{{{returnPassthrough}}}); + return appFromJS(normalizedApiObject); + {{/items.isModel}} + {{^items.isModel}} + return appFromJS(apiObject.{{{returnPassthrough}}}); + {{/items.isModel}} + {{/isArray}} + {{^isModel}} + {{^isArray}} + return apiObject.{{{returnPassthrough}}}!; + {{/isArray}} + {{/isModel}} + } + + public fromApiPassthroughAsEntities(apiObject: {{classname}}): NormalizedRecordEntities { + {{#isEntity}} + if (!apiObject.{{{returnPassthrough}}}) {return {entities: {}, result: List()}; } + return ApiRecordUtils.toNormalizedRecordEntities({{#lambda.camelcase}}{{{dataTypeAlternate}}}{{/lambda.camelcase}}Utils.normalizeArrayAsEntities([apiObject.{{{returnPassthrough}}}]), true); + {{/isEntity}} + {{#isArray}} + {{#items.isEntity}} + if (!apiObject.{{{returnPassthrough}}}) {return {entities: {}, result: List()}; } + return ApiRecordUtils.toNormalizedRecordEntities({{#lambda.camelcase}}{{items.dataType}}{{/lambda.camelcase}}RecordUtils.normalizeArrayAsEntities(apiObject.{{{returnPassthrough}}}), true); + {{/items.isEntity}} + {{^items.isEntity}} + console.log("entities revival not supported on this response"); + return {entities: {}, result: List()}; + {{/items.isEntity}} + {{/isArray}} + {{^isEntity}} + {{^isArray}} + console.log("entities revival not supported on this response"); + return {entities: {}, result: List()}; + {{/isArray}} + {{/isEntity}} + } +{{/vars.1}} +{{/returnPassthrough}} +} + +export const {{#lambda.camelcase}}{{classname}}{{/lambda.camelcase}}RecordUtils = new {{classname}}RecordUtils(); + +{{#isEntity}} +export const apiEntities{{classname}}Selector = (state: any) => getApiEntitiesState(state).{{#lambda.camelcase}}{{classname}}{{/lambda.camelcase}} as Map; +export const apiEntity{{classname}}Selector = (state: any, {id}: {id?: string | null}) => id ? apiEntities{{classname}}Selector(state).get(id) : undefined; +{{/isEntity}} diff --git a/modules/openapi-generator/src/main/resources/typescript-fetch/records.mustache b/modules/openapi-generator/src/main/resources/typescript-fetch/records.mustache new file mode 100644 index 00000000000..5c8a0ad348a --- /dev/null +++ b/modules/openapi-generator/src/main/resources/typescript-fetch/records.mustache @@ -0,0 +1,15 @@ +{{#models}} +{{#model}} +{{#isEnum}} +// This file is not needed and was generated only because of how codegen is built... Enums do not need to be converted to Records and can be used directly. +{{/isEnum}} +{{^isEnum}} +{{^oneOf}} +/* tslint:disable */ +/* eslint-disable */ +{{>licenseInfo}} +{{>recordGeneric}} +{{/oneOf}} +{{/isEnum}} +{{/model}} +{{/models}} 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 d0c29b93a75..8df16e9074e 100644 --- a/modules/openapi-generator/src/main/resources/typescript-fetch/runtime.mustache +++ b/modules/openapi-generator/src/main/resources/typescript-fetch/runtime.mustache @@ -79,8 +79,8 @@ export class BaseAPI { if (middleware.post) { response = await middleware.post({ fetch: this.fetchApi, - url, - init, + url: fetchParams.url, + init: fetchParams.init, response: response.clone(), }) || response; } @@ -124,7 +124,7 @@ export interface ConfigurationParameters { username?: string; // parameter for basic security password?: string; // parameter for basic security apiKey?: string | ((name: string) => string); // parameter for apiKey security - accessToken?: string | ((name?: string, scopes?: string[]) => string); // parameter for oauth2 security + accessToken?: string | Promise | ((name?: string, scopes?: string[]) => string | Promise); // parameter for oauth2 security headers?: HTTPHeaders; //header params we want to use on every request credentials?: RequestCredentials; //value for the credentials param we want to use on each request } @@ -164,10 +164,10 @@ export class Configuration { return undefined; } - get accessToken(): ((name: string, scopes?: string[]) => string) | undefined { + get accessToken(): ((name?: string, scopes?: string[]) => string | Promise) | undefined { const accessToken = this.configuration.accessToken; if (accessToken) { - return typeof accessToken === 'function' ? accessToken : () => accessToken; + return typeof accessToken === 'function' ? accessToken : async () => accessToken; } return undefined; } diff --git a/modules/openapi-generator/src/main/resources/typescript-fetch/runtimeSagasAndRecords.mustache b/modules/openapi-generator/src/main/resources/typescript-fetch/runtimeSagasAndRecords.mustache new file mode 100644 index 00000000000..e182521fac3 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/typescript-fetch/runtimeSagasAndRecords.mustache @@ -0,0 +1,120 @@ +/* tslint:disable */ +/* eslint-disable */ + +import {fromJS as originalFromJS, isIndexed, List, Map as ImmMap, RecordOf} from 'immutable'; +import {normalize, NormalizedSchema, schema, Schema} from "normalizr"; +import {ActionDefinition, createAction} from "redux-ts-simple"; + +export const knownRecordFactories = new Map(); +export const knownIndexedSetByKey: (string | number)[] = []; + +export function appFromJS(any: any): any { + return originalFromJS(any, (key, value) => { + if (isIndexed(value)) { + return knownIndexedSetByKey.indexOf(key) !== -1 ? value.toSet() : value.toList(); + } // we're reviving an array -> it's a List + const MatchingType = knownRecordFactories.get(value.get('recType')) as { new(input?: any): any }; // check if we know a Record with this type + if (MatchingType) { + return new MatchingType(value); + } + return value.toMap(); // no matching Record type found -> it's a plain old Map + }); +} + +export type NormalizedRecordEntity = NormalizedSchema<{ [key: string]: Map> }, string>; +export type NormalizedRecordEntities = NormalizedSchema<{ [key: string]: Map> }, List>; + +export abstract class ApiRecordUtils> { + public abstract normalize(apiObject: TAPI, asEntity?: boolean): any; + + public getSchema(): Schema { + console.log("Entity mode not supported on this record."); + return new schema.Entity("entityNotSupported"); + } + + public normalizeArray(apiObjectArray: TAPI[], asEntity?: boolean): TAPI[] { + apiObjectArray.forEach(apiObject => this.normalize(apiObject, asEntity)); + return apiObjectArray; + } + + public normalizeAsEntities(apiObject: TAPI): NormalizedSchema { + const normalized = this.normalize(apiObject, true); + return normalize(normalized, this.getSchema()); + } + + public normalizeArrayAsEntities(apiObject: TAPI[]): NormalizedSchema { + const normalized = this.normalizeArray(apiObject, true); + return normalize(normalized, new schema.Array(this.getSchema())); + } + + public fromApi(apiObject: TAPI): TREC { + return appFromJS(this.normalize(apiObject)); + } + + public fromApiArray(apiObjectArray: TAPI[]): List { + this.normalizeArray(apiObjectArray); + return appFromJS(apiObjectArray); + } + + public fromApiAsEntities(apiObject: TAPI): NormalizedRecordEntity { + return ApiRecordUtils.toNormalizedRecordEntities(this.normalizeAsEntities(apiObject), false); + } + + public fromApiArrayAsEntities(apiObject: TAPI[]): NormalizedRecordEntities { + return ApiRecordUtils.toNormalizedRecordEntities(this.normalizeArrayAsEntities(apiObject), true); + } + + public toApi(record: TREC): TAPI { + const apiObject = record.toJS(); + delete apiObject.recType; + return apiObject; + } + + public toApiArray(records: List): TAPI[] { + return records.map(record => this.toApi(record)).toArray(); + } + + public static toNormalizedRecordEntities(normalizedAsEntities: any, forArray: boolean) { + const entities = normalizedAsEntities.entities; + for (const entityKey of Object.keys(entities)) { + entities[entityKey] = appFromJS(entities[entityKey]); + } + normalizedAsEntities.result = appFromJS(normalizedAsEntities.result || (forArray ? "" : [])); + return normalizedAsEntities; + } +} + +export const allApiActionFailures: SagaActionDefinition[] = []; + +export interface BaseEntitySupportPayloadApiAction { + toInlined?: boolean; + toEntities?: boolean; + markErrorsAsHandled?: boolean; +} + +export interface BasePayloadApiAction { + markErrorsAsHandled?: boolean; +} + +export interface SagaActionDefinition extends ActionDefinition { + toString: () => string; +} + +export function createSagaAction(type: string, options?: { doNotAutoRegisterFailure?: boolean, namespace?: string }): SagaActionDefinition { + const {doNotAutoRegisterFailure, namespace} = options || {} as any; + let actionDefinition = createAction(namespace ? `${namespace}-${type}` : type); + (actionDefinition as any).toString = () => actionDefinition.type; + if (type.endsWith("Failure") && !doNotAutoRegisterFailure) { + allApiActionFailures.push(actionDefinition); + } + return actionDefinition; +} + +export let apiCall: any>(context: Ctx, fn: Fn, ...args: Parameters) => Generator; + +export function setApiCall(apiCallFc: any>(context: Ctx, fn: Fn, ...args: Parameters) => Generator) { + console.log("init apiCall"); + apiCall = apiCallFc; +} + +export const normalizedEntities = createSagaAction("normalizedEntities"); \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/typescript-fetch/sagaApiManager.mustache b/modules/openapi-generator/src/main/resources/typescript-fetch/sagaApiManager.mustache new file mode 100644 index 00000000000..af6fa7fdd71 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/typescript-fetch/sagaApiManager.mustache @@ -0,0 +1,36 @@ +import { + Configuration, + ConfigurationParameters, +} from "../"; + +import { +{{#apiInfo}} +{{#apis}} + {{classFilename}}, +{{/apis}} +{{/apiInfo}} +} from "./"; + +export class Api { +{{#apiInfo}} +{{#apis}} + public static {{#lambda.camelcase}}{{classFilename}}{{/lambda.camelcase}}: {{classFilename}}; +{{/apis}} +{{/apiInfo}} + + public static init(apiBasePath: string) { + const apiBaseConfig: ConfigurationParameters = { + basePath: apiBasePath, + credentials: "include", + headers: { + 'Cache-Control': 'no-cache, no-store' // this is needed to prevent stalling issues in Chrome. Also it is a good behavior for api calls. + } + }; + +{{#apiInfo}} +{{#apis}} + Api.{{#lambda.camelcase}}{{classFilename}}{{/lambda.camelcase}} = new {{classFilename}}(new Configuration(apiBaseConfig)); +{{/apis}} +{{/apiInfo}} + } +} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/typescript-fetch/sagas.mustache b/modules/openapi-generator/src/main/resources/typescript-fetch/sagas.mustache new file mode 100644 index 00000000000..ac5581582d8 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/typescript-fetch/sagas.mustache @@ -0,0 +1,239 @@ +/* tslint:disable */ +/* eslint-disable */ +{{>licenseInfo}} + +import {Api} from './'; +import {List} from 'immutable'; +import {all, fork, put, takeLatest} from "redux-saga/effects"; +import {apiCall, createSagaAction as originalCreateSagaAction, BaseEntitySupportPayloadApiAction, BasePayloadApiAction, NormalizedRecordEntities, normalizedEntities} from "../runtimeSagasAndRecords"; +import {Action} from "redux-ts-simple"; + +{{#imports.0}} +import { + {{#imports}} + {{className}}, + {{className}}Record, + {{#lambda.camelcase}}{{classname}}{{/lambda.camelcase}}RecordUtils, + {{/imports}} + {{#passthroughImports}} + {{.}}, + {{/passthroughImports}} +} from '../models'; +{{/imports.0}} +{{#hasEnums}} +{{#operations}} +{{#operation}} +{{#allParams}} +{{#isEnum}} + +import { + {{operationIdCamelCase}}{{enumName}}, +} from './{{classname}}'; +{{/isEnum}} +{{/allParams}} +{{/operation}} +{{/operations}} +{{/hasEnums}} + +const createSagaAction = (type: string) => originalCreateSagaAction(type, {namespace: "api_{{#lambda.camelcase}}{{classname}}{{/lambda.camelcase}}"}); + +export const {{#lambda.camelcase}}{{classname}}{{/lambda.camelcase}}SagaMap = new Map Generator>([ +{{#operations}} + {{#operation}} + ["{{nickname}}", {{nickname}}Saga], + {{/operation}} +{{/operations}} + ] +); + +export function *{{#lambda.camelcase}}{{classname}}{{/lambda.camelcase}}AllSagas() { + yield all([...{{#lambda.camelcase}}{{classname}}{{/lambda.camelcase}}SagaMap.values()].map(actionSaga => fork(actionSaga))); +} + +{{#operations}} +{{#operation}} +//region {{nickname}} + +{{#returnTypeSupportsEntities}} +export interface Payload{{#lambda.titlecase}}{{#lambda.camelcase}}{{nickname}}{{/lambda.camelcase}}{{/lambda.titlecase}} extends {{#allParams.0}}Payload{{#lambda.titlecase}}{{#lambda.camelcase}}{{nickname}}{{/lambda.camelcase}}{{/lambda.titlecase}}Request, {{/allParams.0}}BaseEntitySupportPayloadApiAction { +} +{{/returnTypeSupportsEntities}} +{{^returnTypeSupportsEntities}} +export interface Payload{{#lambda.titlecase}}{{#lambda.camelcase}}{{nickname}}{{/lambda.camelcase}}{{/lambda.titlecase}} extends {{#allParams.0}}Payload{{#lambda.titlecase}}{{#lambda.camelcase}}{{nickname}}{{/lambda.camelcase}}{{/lambda.titlecase}}Request, {{/allParams.0}}BasePayloadApiAction { +} +{{/returnTypeSupportsEntities}} + +{{#allParams.0}} +export interface Payload{{#lambda.titlecase}}{{#lambda.camelcase}}{{nickname}}{{/lambda.camelcase}}{{/lambda.titlecase}}Request { +{{#allParams}} + {{paramName}}{{^required}}?{{/required}}: {{{dataTypeAlternate}}}; +{{/allParams}} +} +{{/allParams.0}} + +export const {{nickname}}Request = createSagaAction<{{#allParams.0}}Payload{{#lambda.titlecase}}{{#lambda.camelcase}}{{nickname}}{{/lambda.camelcase}}{{/lambda.titlecase}}Request{{/allParams.0}}{{^allParams.0}}void{{/allParams.0}}>("{{nickname}}Request"); +{{#returnType}} +export const {{nickname}}Success = createSagaAction<{{#hasReturnPassthroughVoid}}void{{/hasReturnPassthroughVoid}}{{^hasReturnPassthroughVoid}}{{{returnTypeAlternate}}}{{/hasReturnPassthroughVoid}}>("{{nickname}}Success"); +{{#returnTypeSupportsEntities}} +export const {{nickname}}Success_Entities = createSagaAction("{{nickname}}Success_Entities"); +{{/returnTypeSupportsEntities}} +{{/returnType}} +{{^returnType}} +export const {{nickname}}Success = createSagaAction("{{nickname}}Success"); +{{/returnType}} +export const {{nickname}}Failure = createSagaAction<{error: any, requestPayload: Payload{{#lambda.titlecase}}{{#lambda.camelcase}}{{nickname}}{{/lambda.camelcase}}{{/lambda.titlecase}}}>("{{nickname}}Failure"); + +export const {{nickname}} = createSagaAction("{{nickname}}"); + +export function *{{nickname}}Saga() { + yield takeLatest({{nickname}}, {{nickname}}SagaImp); +} + +export function *{{nickname}}SagaImp(_action_: Action) { + const {markErrorsAsHandled, ..._payloadRest_} = _action_.payload; + try { +{{#returnTypeSupportsEntities}} + const {toEntities, toInlined = !toEntities, ...requestPayload} = _payloadRest_; +{{/returnTypeSupportsEntities}} +{{#allParams.0}} + const { +{{#allParams}} + {{paramName}}, +{{/allParams}} + } = _payloadRest_; +{{/allParams.0}} + + yield put({{nickname}}Request({{#allParams.0}}{{#returnTypeSupportsEntities}}requestPayload{{/returnTypeSupportsEntities}}{{^returnTypeSupportsEntities}}_action_.payload{{/returnTypeSupportsEntities}}{{/allParams.0}})); + + const response{{#returnType}}: Required<{{{returnType}}}>{{/returnType}} = yield apiCall(Api.{{#lambda.camelcase}}{{classname}}{{/lambda.camelcase}}, Api.{{#lambda.camelcase}}{{classname}}{{/lambda.camelcase}}.{{nickname}}, +{{#allParams.0}} +{{#allParams}} +{{#isUniqueId}} +{{#isArray}} + {{^required}}{{paramName}} ? {{/required}}{{paramName}}.map(p => parseFloat(p)).toArray(){{^required}} : undefined{{/required}}, +{{/isArray}} +{{^isArray}} + {{^required}}{{paramName}} ? {{/required}}parseFloat({{paramName}}){{^required}} : undefined{{/required}}, +{{/isArray}} +{{/isUniqueId}} +{{^isUniqueId}} +{{#isArray}} +{{#items.isModel}} + {{^required}}{{paramName}} ? {{/required}}{{#lambda.camelcase}}{{items.dataType}}{{/lambda.camelcase}}RecordUtils.toApiArray({{paramName}}){{^required}} : undefined{{/required}}, +{{/items.isModel}} +{{^items.isModel}} + {{^required}}{{paramName}} ? {{/required}}{{paramName}}.toJS(){{^required}} : undefined{{/required}}, +{{/items.isModel}} +{{/isArray}} +{{#isModel}} + {{^required}}{{paramName}} ? {{/required}}{{#lambda.camelcase}}{{{dataTypeAlternate}}}{{/lambda.camelcase}}Utils.toApi({{paramName}}){{^required}} : undefined{{/required}}, +{{/isModel}} +{{^isArray}} +{{^isModel}} + {{paramName}}, +{{/isModel}} +{{/isArray}} +{{/isUniqueId}} +{{/allParams}} +{{/allParams.0}} + ); + +{{#returnType}} +{{^hasReturnPassthroughVoid}} + let successReturnValue: any = undefined; +{{/hasReturnPassthroughVoid}} +{{/returnType}} +{{#returnTypeSupportsEntities}} + if (toEntities) { +{{#returnPassthrough}} + successReturnValue = {{#lambda.camelcase}}{{{returnType}}}{{/lambda.camelcase}}RecordUtils.fromApiPassthroughAsEntities(response); +{{/returnPassthrough}} +{{^hasReturnPassthroughVoid}} +{{^returnPassthrough}} +{{#returnTypeIsArray}} +{{#returnTypeAlternate}} + successReturnValue = {{#lambda.camelcase}}{{returnBaseTypeAlternate}}{{/lambda.camelcase}}Utils.fromApiArrayAsEntities(response); +{{/returnTypeAlternate}} +{{/returnTypeIsArray}} +{{#returnTypeIsModel}} + successReturnValue = {{#lambda.camelcase}}{{returnTypeAlternate}}{{/lambda.camelcase}}Utils.fromApiArrayAsEntities([response]); +{{/returnTypeIsModel}} +{{/returnPassthrough}} +{{/hasReturnPassthroughVoid}} + yield put(normalizedEntities(successReturnValue)); + yield put({{nickname}}Success_Entities(successReturnValue)); + } + if (toInlined) { +{{/returnTypeSupportsEntities}} +{{#returnType}} +{{#returnPassthrough}} + successReturnValue = {{#lambda.camelcase}}{{{returnType}}}{{/lambda.camelcase}}RecordUtils.fromApiPassthrough(response); + yield put({{nickname}}Success(successReturnValue)); +{{/returnPassthrough}} +{{#hasReturnPassthroughVoid}} + yield put({{nickname}}Success()); +{{/hasReturnPassthroughVoid}} +{{^hasReturnPassthroughVoid}} +{{^returnPassthrough}} +{{#returnTypeIsArray}} +{{#returnTypeAlternate}} + successReturnValue = {{#lambda.camelcase}}{{returnBaseTypeAlternate}}{{/lambda.camelcase}}Utils.fromApiArray(response); + yield put({{nickname}}Success(successReturnValue)); +{{/returnTypeAlternate}} +{{/returnTypeIsArray}} +{{#returnTypeIsModel}} + successReturnValue = {{#lambda.camelcase}}{{returnTypeAlternate}}{{/lambda.camelcase}}Utils.fromApi(response); + yield put({{nickname}}Success(successReturnValue)); +{{/returnTypeIsModel}} +{{^returnTypeIsArray}} +{{^returnTypeIsModel}} + yield put({{nickname}}Success(response)); +{{/returnTypeIsModel}} +{{/returnTypeIsArray}} +{{/returnPassthrough}} +{{/hasReturnPassthroughVoid}} +{{/returnType}} +{{^returnType}} + yield put({{nickname}}Success()); +{{/returnType}} +{{#returnTypeSupportsEntities}} + } +{{/returnTypeSupportsEntities}} + +{{#returnType}} +{{#returnPassthrough}} + return successReturnValue; +{{/returnPassthrough}} +{{#hasReturnPassthroughVoid}} + return undefined; +{{/hasReturnPassthroughVoid}} +{{^hasReturnPassthroughVoid}} +{{^returnPassthrough}} +{{#returnTypeIsArray}} +{{#returnTypeAlternate}} + return successReturnValue; +{{/returnTypeAlternate}} +{{/returnTypeIsArray}} +{{#returnTypeIsModel}} + return successReturnValue; +{{/returnTypeIsModel}} +{{^returnTypeIsArray}} +{{^returnTypeIsModel}} + return response; +{{/returnTypeIsModel}} +{{/returnTypeIsArray}} +{{/returnPassthrough}} +{{/hasReturnPassthroughVoid}} +{{/returnType}} +{{^returnType}} + return undefined; +{{/returnType}} + } catch (error) { + if (markErrorsAsHandled) {error.wasHandled = true; } + yield put({{nickname}}Failure({error, requestPayload: _action_.payload})); + return error; + } +} +//endregion +{{/operation}} +{{/operations}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/typescript-fetch/sourceLibraryIndex.mustache b/modules/openapi-generator/src/main/resources/typescript-fetch/sourceLibraryIndex.mustache new file mode 100644 index 00000000000..8879d7a13f3 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/typescript-fetch/sourceLibraryIndex.mustache @@ -0,0 +1 @@ +export * from './src'; \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/typescript-fetch/tsconfig.mustache b/modules/openapi-generator/src/main/resources/typescript-fetch/tsconfig.mustache index 420c3a44f88..a8778b09659 100644 --- a/modules/openapi-generator/src/main/resources/typescript-fetch/tsconfig.mustache +++ b/modules/openapi-generator/src/main/resources/typescript-fetch/tsconfig.mustache @@ -2,6 +2,9 @@ "compilerOptions": { "declaration": true, "target": "{{#supportsES6}}es6{{/supportsES6}}{{^supportsES6}}es5{{/supportsES6}}", +{{#sagasAndRecords}} + "strict": true, +{{/sagasAndRecords}} "module": "commonjs", "moduleResolution": "node", "outDir": "dist", diff --git a/modules/openapi-generator/src/main/resources/typescript-node/package.mustache b/modules/openapi-generator/src/main/resources/typescript-node/package.mustache index ff1c5c44519..3679a80fadd 100644 --- a/modules/openapi-generator/src/main/resources/typescript-node/package.mustache +++ b/modules/openapi-generator/src/main/resources/typescript-node/package.mustache @@ -15,7 +15,7 @@ "dependencies": { "bluebird": "^3.5.0", "request": "^2.81.0", - "@types/bluebird": "*", + "@types/bluebird": "3.5.33", "@types/request": "*", "rewire": "^3.0.2" }, diff --git a/modules/openapi-generator/src/main/resources/typescript/auth/auth.mustache b/modules/openapi-generator/src/main/resources/typescript/auth/auth.mustache index 0e0ae23b1f2..bfb303e741e 100644 --- a/modules/openapi-generator/src/main/resources/typescript/auth/auth.mustache +++ b/modules/openapi-generator/src/main/resources/typescript/auth/auth.mustache @@ -75,8 +75,12 @@ export class {{#lambda.pascalcase}}{{name}}{{/lambda.pascalcase}}Authentication public constructor({{#useInversify}}@inject(AbstractTokenProvider) @named("{{name}}") {{/useInversify}}private tokenProvider: TokenProvider) {} {{/isBasicBearer}} {{#isOAuth}} - // TODO: How to handle oauth2 authentication! - public constructor() {} + /** + * Configures OAuth2 with the necessary properties + * + * @param accessToken: The access token to be used for every request + */ + public constructor(private accessToken: string) {} {{/isOAuth}} public getName(): string { @@ -85,7 +89,7 @@ export class {{#lambda.pascalcase}}{{name}}{{/lambda.pascalcase}}Authentication public {{#isBasicBearer}}async {{/isBasicBearer}}applySecurityAuthentication(context: RequestContext) { {{#isApiKey}} - context.{{#isKeyInHeader}}setHeaderParam{{/isKeyInHeader}}{{#isKeyInQuery}}addCookie{{/isKeyInQuery}}{{#isKeyInCookie}}setQueryParam{{/isKeyInCookie}}("{{keyParamName}}", this.apiKey); + context.{{#isKeyInHeader}}setHeaderParam{{/isKeyInHeader}}{{#isKeyInQuery}}setQueryParam{{/isKeyInQuery}}{{#isKeyInCookie}}addCookie{{/isKeyInCookie}}("{{keyParamName}}", this.apiKey); {{/isApiKey}} {{#isBasicBasic}} let comb = this.username + ":" + this.password; @@ -95,7 +99,7 @@ export class {{#lambda.pascalcase}}{{name}}{{/lambda.pascalcase}}Authentication context.setHeaderParam("Authorization", "Bearer " + await this.tokenProvider.getToken()); {{/isBasicBearer}} {{#isOAuth}} - // TODO + context.setHeaderParam("Authorization", "Bearer " + this.accessToken); {{/isOAuth}} } } @@ -119,7 +123,7 @@ export const authMethodServices = { export type ApiKeyConfiguration = string; export type HttpBasicConfiguration = { "username": string, "password": string }; export type HttpBearerConfiguration = { tokenProvider: TokenProvider }; -export type OAuth2Configuration = string; +export type OAuth2Configuration = { accessToken: string }; export type AuthMethodsConfiguration = { {{#authMethods}} @@ -152,6 +156,7 @@ export function configureAuthMethods(config: AuthMethodsConfiguration | undefine config["{{name}}"]["tokenProvider"] {{/isBasicBearer}} {{#isOAuth}} + config["{{name}}"]["accessToken"] {{/isOAuth}} ); } diff --git a/modules/openapi-generator/src/main/resources/wsdl-schema/jaxb-customization.mustache b/modules/openapi-generator/src/main/resources/wsdl-schema/jaxb-customization.mustache new file mode 100644 index 00000000000..cfdd31b1b58 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/wsdl-schema/jaxb-customization.mustache @@ -0,0 +1,50 @@ + + + + true + false + + {{#models}} + {{#model}} + {{^allOf}} + {{#vars}} + {{#isEnum}} + {{#baseType}} + + + {{#allowableValues}} + {{#enumVars}} + + {{/enumVars}} + {{/allowableValues}} + + + {{/baseType}} + {{/isEnum}} + {{/vars}} + {{/allOf}} + {{/model}} + {{/models}} + + {{#models}} + {{#model}} + {{^vars}} + + + {{#allowableValues}} + {{#enumVars}} + + {{/enumVars}} + {{/allowableValues}} + + + {{/vars}} + {{/model}} + {{/models}} + + diff --git a/modules/openapi-generator/src/main/resources/wsdl-schema/wsdl-converter.mustache b/modules/openapi-generator/src/main/resources/wsdl-schema/wsdl-converter.mustache new file mode 100644 index 00000000000..c136126eb5a --- /dev/null +++ b/modules/openapi-generator/src/main/resources/wsdl-schema/wsdl-converter.mustache @@ -0,0 +1,348 @@ + + + + + {{#apiInfo}} + {{#apis}} + {{#operations}} + {{#operation}} + + + {{#responses}} + {{#is4xx}} + + + {{message}} + + + {{/is4xx}} + {{#is5xx}} + + + {{message}} + + + {{/is5xx}} + {{/responses}} + {{/operation}} + {{/operations}} + {{/apis}} + {{/apiInfo}} + {{#models}} + {{#model}} + {{^vendorExtensions.x-is-openapimodel-enum}} + + {{#description}} + + {{description}} + + {{/description}} + + {{#vars}} + {{#vendorExtensions.x-prop-has-minormax}} + + + {{#description}} + + {{description}} + + {{/description}} + + {{#maximum}} + + {{/maximum}} + {{#minimum}} + + {{/minimum}} + {{#maxLength}} + + {{/maxLength}} + {{#minLength}} + + {{/minLength}} + + + + {{/vendorExtensions.x-prop-has-minormax}} + {{^vendorExtensions.x-prop-has-minormax}} + {{#isContainer}} + + {{/isContainer}} + {{^isContainer}} + + {{/isContainer}} + {{#description}} + + {{description}} + + + {{/description}} + {{/vendorExtensions.x-prop-has-minormax}} + {{/vars}} + + + {{/vendorExtensions.x-is-openapimodel-enum}} + {{/model}} + {{/models}} + {{#models}} + {{#model}} + {{^allOf}} + {{#vars}} + {{#isEnum}} + {{#baseType}} + + {{#description}} + + {{description}} + + {{/description}} + + {{#allowableValues}} + {{#enumVars}} + + {{/enumVars}} + {{/allowableValues}} + + + {{/baseType}} + {{/isEnum}} + {{/vars}} + {{/allOf}} + {{/model}} + {{/models}} + {{#models}} + {{#model}} + {{^vars}} + + {{#description}} + + {{description}} + + {{/description}} + + {{#allowableValues}} + {{#enumVars}} + + {{/enumVars}} + {{/allowableValues}} + + + {{/vars}} + {{/model}} + {{/models}} + {{#apiInfo}} + {{#apis}} + {{#operations}} + {{#operation}} + {{#allParams}} + {{#isEnum}} + + + {{#allowableValues}} + {{#enumVars}} + + {{/enumVars}} + {{/allowableValues}} + + + {{/isEnum}} + {{/allParams}} + {{/operation}} + {{/operations}} + {{/apis}} + {{/apiInfo}} + {{#apiInfo}} + {{#apis}} + {{#operations}} + {{#operation}} + {{#hasParams}} + + + {{#allParams}} + {{#vendorExtensions.x-param-has-minormax}} + + + {{#description}} + + {{description}} + + {{/description}} + + {{#maximum}} + + {{/maximum}} + {{#minimum}} + + {{/minimum}} + {{#maxLength}} + + {{/maxLength}} + {{#minLength}} + + {{/minLength}} + + + + {{/vendorExtensions.x-param-has-minormax}} + {{^vendorExtensions.x-param-has-minormax}} + + {{#description}} + + {{description}} + + + {{/description}} + {{/vendorExtensions.x-param-has-minormax}} + {{/allParams}} + + + {{/hasParams}} + {{^hasParams}} + + {{/hasParams}} + {{#responses}} + {{^is4xx}} + {{^is5xx}} + + + {{#message}} + + + {{message}} + + + {{/message}} + {{^message}} + + {{/message}} + + + {{/is5xx}} + {{/is4xx}} + {{/responses}} + {{/operation}} + {{/operations}} + {{/apis}} + {{/apiInfo}} + + + {{#apiInfo}} + {{#apis}} + {{#operations}} + {{#operation}} + + + + {{#responses}} + {{#is2xx}} + + + + {{/is2xx}} + {{#isDefault}} + + + + {{/isDefault}} + {{#is4xx}} + + + + {{/is4xx}} + {{#is5xx}} + + + + {{/is5xx}} + {{/responses}} + {{/operation}} + {{/operations}} + {{/apis}} + {{/apiInfo}} + + {{#apiInfo}} + {{#apis}} + {{#operations}} + {{#operation}} + + {{#notes}} + {{notes}} + {{/notes}} + {{^notes}} + {{#summary}} + {{summary}} + {{/summary}} + {{/notes}} + + {{#responses}} + {{^is4xx}} + {{^is5xx}} + + {{#message}} + {{message}} + + {{/message}} + {{/is5xx}} + {{/is4xx}} + {{#is4xx}} + + {{#message}} + {{message}} + + {{/message}} + {{/is4xx}} + {{#is5xx}} + + {{#message}} + {{message}} + + {{/message}} + {{/is5xx}} + {{/responses}} + + {{/operation}} + {{/operations}} + {{/apis}} + {{/apiInfo}} + + + + {{#apiInfo}} + {{#apis}} + {{#operations}} + {{#operation}} + + + + + + {{#responses}} + {{#is2xx}} + + + + {{/is2xx}} + {{#is4xx}} + + + + {{/is4xx}} + {{#is5xx}} + + + + {{/is5xx}} + {{/responses}} + + {{/operation}} + {{/operations}} + {{/apis}} + {{/apiInfo}} + + + {{appDescription}} + + + + + \ No newline at end of file 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 e125c98a463..4f6e36a62de 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 @@ -76,8 +76,8 @@ public class DefaultCodegenTest { final DefaultCodegen codegen = new DefaultCodegen(); - Assert.assertEquals(codegen.hasBodyParameter(openAPI, pingOperation), false); - Assert.assertEquals(codegen.hasBodyParameter(openAPI, createOperation), true); + Assert.assertFalse(codegen.hasBodyParameter(openAPI, pingOperation)); + Assert.assertTrue(codegen.hasBodyParameter(openAPI, createOperation)); } @Test(expectedExceptions = RuntimeException.class) @@ -174,7 +174,7 @@ public class DefaultCodegenTest { codegen.processOpts(); Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP), Boolean.TRUE); - Assert.assertEquals(codegen.isHideGenerationTimestamp(), true); + Assert.assertTrue(codegen.isHideGenerationTimestamp()); } @Test @@ -184,7 +184,7 @@ public class DefaultCodegenTest { codegen.processOpts(); Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP), Boolean.FALSE); - Assert.assertEquals(codegen.isHideGenerationTimestamp(), false); + Assert.assertFalse(codegen.isHideGenerationTimestamp()); } @Test @@ -194,7 +194,7 @@ public class DefaultCodegenTest { codegen.processOpts(); Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP), Boolean.FALSE); - Assert.assertEquals(codegen.isHideGenerationTimestamp(), false); + Assert.assertFalse(codegen.isHideGenerationTimestamp()); } @Test @@ -248,7 +248,7 @@ public class DefaultCodegenTest { codegen.setDisallowAdditionalPropertiesIfNotPresent(true); Schema schema = openAPI.getComponents().getSchemas().get("AdditionalPropertiesClass"); - Assert.assertEquals(schema.getAdditionalProperties(), null); + Assert.assertNull(schema.getAdditionalProperties()); Schema addProps = ModelUtils.getAdditionalProperties(openAPI, schema); // The petstore-with-fake-endpoints-models-for-testing.yaml does not set the @@ -337,7 +337,7 @@ public class DefaultCodegenTest { */ Schema schema = openAPI.getComponents().getSchemas().get("AdditionalPropertiesClass"); - Assert.assertEquals(schema.getAdditionalProperties(), null); + Assert.assertNull(schema.getAdditionalProperties()); Schema addProps = ModelUtils.getAdditionalProperties(openAPI, schema); // The petstore-with-fake-endpoints-models-for-testing.yaml does not set the @@ -939,19 +939,19 @@ public class DefaultCodegenTest { // to test allOf with double refs Schema supermanSchema = openAPI.getComponents().getSchemas().get("SuperMan"); CodegenModel supermanModel = codegen.fromModel("SuperMan", supermanSchema); - Assert.assertEquals(supermanModel.parent, null); + Assert.assertNull(supermanModel.parent); Assert.assertEquals(supermanModel.allParents, null); // to test allOf with single ref Schema superboySchema = openAPI.getComponents().getSchemas().get("SuperBoy"); CodegenModel superboyModel = codegen.fromModel("SuperBoy", superboySchema); - Assert.assertEquals(superboyModel.parent, null); + Assert.assertNull(superboyModel.parent); Assert.assertEquals(superboyModel.allParents, null); // to test allOf with single ref and no "type: object" in the (last) inline schema Schema superbabySchema = openAPI.getComponents().getSchemas().get("SuperBaby"); CodegenModel superbabyModel = codegen.fromModel("SuperBaby", superbabySchema); - Assert.assertEquals(superbabyModel.parent, null); + Assert.assertNull(superbabyModel.parent); Assert.assertEquals(superbabyModel.allParents, null); } @@ -1093,7 +1093,7 @@ public class DefaultCodegenTest { for (String leafModelName: leafModelNames) { Schema leafSc = openAPI.getComponents().getSchemas().get(leafModelName); CodegenModel leafCm = codegen.fromModel(leafModelName, leafSc); - Assert.assertEquals(leafCm.discriminator, null); + Assert.assertNull(leafCm.discriminator); } // the Pet discriminator map contains all animals + Reptile (children + grandchildren) @@ -1124,7 +1124,7 @@ public class DefaultCodegenTest { modelName = "Reptile"; sc = openAPI.getComponents().getSchemas().get(modelName); CodegenModel reptile = codegen.fromModel(modelName, sc); - Assert.assertEquals(reptile.discriminator, null); + Assert.assertNull(reptile.discriminator); // the MyPets discriminator contains Cat and Lizard CodegenDiscriminator myPetDisc = new CodegenDiscriminator(); @@ -1140,7 +1140,7 @@ public class DefaultCodegenTest { modelName = "MyPetsNoDisc"; sc = openAPI.getComponents().getSchemas().get(modelName); CodegenModel myPetsNoDisc = codegen.fromModel(modelName, sc); - Assert.assertEquals(myPetsNoDisc.discriminator, null); + Assert.assertNull(myPetsNoDisc.discriminator); CodegenModel cm; @@ -1156,13 +1156,13 @@ public class DefaultCodegenTest { modelName = "B"; sc = openAPI.getComponents().getSchemas().get(modelName); cm = codegen.fromModel(modelName, sc); - Assert.assertEquals(cm.discriminator, null); + Assert.assertNull(cm.discriminator); // the mapping in b is in C modelName = "C"; sc = openAPI.getComponents().getSchemas().get(modelName); cm = codegen.fromModel(modelName, sc); - Assert.assertEquals(cm.discriminator, null); + Assert.assertNull(cm.discriminator); } @Test @@ -1922,7 +1922,7 @@ public class DefaultCodegenTest { openAPI.getComponents().getSchemas().get("MyParameterTextField") ); Assert.assertTrue(typeAliasModel.isAlias); - Assert.assertEquals("string", typeAliasModel.dataType); + Assert.assertEquals(typeAliasModel.dataType, "string"); CodegenModel composedModel = codegen.fromModel( "ComposedModel", @@ -2192,7 +2192,7 @@ public class DefaultCodegenTest { @Test public void setStyle() { CodegenParameter parameter = codegenParameter("/set_style"); - assertEquals("form", parameter.style); + assertEquals(parameter.style, "form"); } @Test @@ -2528,26 +2528,26 @@ public class DefaultCodegenTest { sc = openAPI.getComponents().getSchemas().get(modelName); cm = codegen.fromModel(modelName, sc); assertEquals(cm.getAdditionalProperties(), anyTypeSchema); - assertEquals(cm.getAdditionalPropertiesIsAnyType(), true); + assertTrue(cm.getAdditionalPropertiesIsAnyType()); modelName = "AdditionalPropertiesTrue"; sc = openAPI.getComponents().getSchemas().get(modelName); cm = codegen.fromModel(modelName, sc); assertEquals(cm.getAdditionalProperties(), anyTypeSchema); - assertEquals(cm.getAdditionalPropertiesIsAnyType(), true); + assertTrue(cm.getAdditionalPropertiesIsAnyType()); modelName = "AdditionalPropertiesFalse"; sc = openAPI.getComponents().getSchemas().get(modelName); cm = codegen.fromModel(modelName, sc); - assertEquals(cm.getAdditionalProperties(), null); - assertEquals(cm.getAdditionalPropertiesIsAnyType(), false); + assertNull(cm.getAdditionalProperties()); + assertFalse(cm.getAdditionalPropertiesIsAnyType()); modelName = "AdditionalPropertiesSchema"; sc = openAPI.getComponents().getSchemas().get(modelName); cm = codegen.fromModel(modelName, sc); CodegenProperty stringCp = codegen.fromProperty("", new Schema().type("string")); assertEquals(cm.getAdditionalProperties(), stringCp); - assertEquals(cm.getAdditionalPropertiesIsAnyType(), false); + assertFalse(cm.getAdditionalPropertiesIsAnyType()); } @Test @@ -2578,32 +2578,32 @@ public class DefaultCodegenTest { cm = codegen.fromModel(modelName, sc); mapWithAddPropsUnset = cm.getVars().get(0); assertEquals(mapWithAddPropsUnset.getAdditionalProperties(), anyTypeSchema); - assertEquals(mapWithAddPropsUnset.getAdditionalPropertiesIsAnyType(), true); + assertTrue(mapWithAddPropsUnset.getAdditionalPropertiesIsAnyType()); mapWithAddPropsTrue = cm.getVars().get(1); assertEquals(mapWithAddPropsTrue.getAdditionalProperties(), anyTypeSchema); - assertEquals(mapWithAddPropsTrue.getAdditionalPropertiesIsAnyType(), true); + assertTrue(mapWithAddPropsTrue.getAdditionalPropertiesIsAnyType()); mapWithAddPropsFalse = cm.getVars().get(2); - assertEquals(mapWithAddPropsFalse.getAdditionalProperties(), null); - assertEquals(mapWithAddPropsFalse.getAdditionalPropertiesIsAnyType(), false); + assertNull(mapWithAddPropsFalse.getAdditionalProperties()); + assertFalse(mapWithAddPropsFalse.getAdditionalPropertiesIsAnyType()); mapWithAddPropsSchema = cm.getVars().get(3); assertEquals(mapWithAddPropsSchema.getAdditionalProperties(), stringCp); - assertEquals(mapWithAddPropsSchema.getAdditionalPropertiesIsAnyType(), false); + assertFalse(mapWithAddPropsSchema.getAdditionalPropertiesIsAnyType()); modelName = "ObjectModelWithAddPropsInProps"; sc = openAPI.getComponents().getSchemas().get(modelName); cm = codegen.fromModel(modelName, sc); mapWithAddPropsUnset = cm.getVars().get(0); assertEquals(mapWithAddPropsUnset.getAdditionalProperties(), anyTypeSchema); - assertEquals(mapWithAddPropsUnset.getAdditionalPropertiesIsAnyType(), true); + assertTrue(mapWithAddPropsUnset.getAdditionalPropertiesIsAnyType()); mapWithAddPropsTrue = cm.getVars().get(1); assertEquals(mapWithAddPropsTrue.getAdditionalProperties(), anyTypeSchema); - assertEquals(mapWithAddPropsTrue.getAdditionalPropertiesIsAnyType(), true); + assertTrue(mapWithAddPropsTrue.getAdditionalPropertiesIsAnyType()); mapWithAddPropsFalse = cm.getVars().get(2); - assertEquals(mapWithAddPropsFalse.getAdditionalProperties(), null); - assertEquals(mapWithAddPropsFalse.getAdditionalPropertiesIsAnyType(), false); + assertNull(mapWithAddPropsFalse.getAdditionalProperties()); + assertFalse(mapWithAddPropsFalse.getAdditionalPropertiesIsAnyType()); mapWithAddPropsSchema = cm.getVars().get(3); assertEquals(mapWithAddPropsSchema.getAdditionalProperties(), stringCp); - assertEquals(mapWithAddPropsSchema.getAdditionalPropertiesIsAnyType(), false); + assertFalse(mapWithAddPropsSchema.getAdditionalPropertiesIsAnyType()); if (isGenerateAliasAsModel) { // restore the setting GlobalSettings.setProperty("generateAliasAsModel", "true"); @@ -2639,32 +2639,32 @@ public class DefaultCodegenTest { co = codegen.fromOperation(path, "POST", operation, null); mapWithAddPropsUnset = co.queryParams.get(0); assertEquals(mapWithAddPropsUnset.getAdditionalProperties(), anyTypeSchema); - assertEquals(mapWithAddPropsUnset.getAdditionalPropertiesIsAnyType(), true); + assertTrue(mapWithAddPropsUnset.getAdditionalPropertiesIsAnyType()); mapWithAddPropsTrue = co.queryParams.get(1); assertEquals(mapWithAddPropsTrue.getAdditionalProperties(), anyTypeSchema); - assertEquals(mapWithAddPropsTrue.getAdditionalPropertiesIsAnyType(), true); + assertTrue(mapWithAddPropsTrue.getAdditionalPropertiesIsAnyType()); mapWithAddPropsFalse = co.queryParams.get(2); - assertEquals(mapWithAddPropsFalse.getAdditionalProperties(), null); - assertEquals(mapWithAddPropsFalse.getAdditionalPropertiesIsAnyType(), false); + assertNull(mapWithAddPropsFalse.getAdditionalProperties()); + assertFalse(mapWithAddPropsFalse.getAdditionalPropertiesIsAnyType()); mapWithAddPropsSchema = co.queryParams.get(3); assertEquals(mapWithAddPropsSchema.getAdditionalProperties(), stringCp); - assertEquals(mapWithAddPropsSchema.getAdditionalPropertiesIsAnyType(), false); + assertFalse(mapWithAddPropsSchema.getAdditionalPropertiesIsAnyType()); path = "/additional_properties/"; operation = openAPI.getPaths().get(path).getPost(); co = codegen.fromOperation(path, "POST", operation, null); mapWithAddPropsUnset = co.queryParams.get(0); assertEquals(mapWithAddPropsUnset.getAdditionalProperties(), anyTypeSchema); - assertEquals(mapWithAddPropsUnset.getAdditionalPropertiesIsAnyType(), true); + assertTrue(mapWithAddPropsUnset.getAdditionalPropertiesIsAnyType()); mapWithAddPropsTrue = co.queryParams.get(1); assertEquals(mapWithAddPropsTrue.getAdditionalProperties(), anyTypeSchema); - assertEquals(mapWithAddPropsTrue.getAdditionalPropertiesIsAnyType(), true); + assertTrue(mapWithAddPropsTrue.getAdditionalPropertiesIsAnyType()); mapWithAddPropsFalse = co.queryParams.get(2); - assertEquals(mapWithAddPropsFalse.getAdditionalProperties(), null); - assertEquals(mapWithAddPropsFalse.getAdditionalPropertiesIsAnyType(), false); + assertNull(mapWithAddPropsFalse.getAdditionalProperties()); + assertFalse(mapWithAddPropsFalse.getAdditionalPropertiesIsAnyType()); mapWithAddPropsSchema = co.queryParams.get(3); assertEquals(mapWithAddPropsSchema.getAdditionalProperties(), stringCp); - assertEquals(mapWithAddPropsSchema.getAdditionalPropertiesIsAnyType(), false); + assertFalse(mapWithAddPropsSchema.getAdditionalPropertiesIsAnyType()); if (isGenerateAliasAsModel) { // restore the setting GlobalSettings.setProperty("generateAliasAsModel", "true"); @@ -2700,32 +2700,32 @@ public class DefaultCodegenTest { co = codegen.fromOperation(path, "POST", operation, null); mapWithAddPropsUnset = co.responses.get(0); assertEquals(mapWithAddPropsUnset.getAdditionalProperties(), anyTypeSchema); - assertEquals(mapWithAddPropsUnset.getAdditionalPropertiesIsAnyType(), true); + assertTrue(mapWithAddPropsUnset.getAdditionalPropertiesIsAnyType()); mapWithAddPropsTrue = co.responses.get(1); assertEquals(mapWithAddPropsTrue.getAdditionalProperties(), anyTypeSchema); - assertEquals(mapWithAddPropsTrue.getAdditionalPropertiesIsAnyType(), true); + assertTrue(mapWithAddPropsTrue.getAdditionalPropertiesIsAnyType()); mapWithAddPropsFalse = co.responses.get(2); - assertEquals(mapWithAddPropsFalse.getAdditionalProperties(), null); - assertEquals(mapWithAddPropsFalse.getAdditionalPropertiesIsAnyType(), false); + assertNull(mapWithAddPropsFalse.getAdditionalProperties()); + assertFalse(mapWithAddPropsFalse.getAdditionalPropertiesIsAnyType()); mapWithAddPropsSchema = co.responses.get(3); assertEquals(mapWithAddPropsSchema.getAdditionalProperties(), stringCp); - assertEquals(mapWithAddPropsSchema.getAdditionalPropertiesIsAnyType(), false); + assertFalse(mapWithAddPropsSchema.getAdditionalPropertiesIsAnyType()); path = "/additional_properties/"; operation = openAPI.getPaths().get(path).getPost(); co = codegen.fromOperation(path, "POST", operation, null); mapWithAddPropsUnset = co.responses.get(0); assertEquals(mapWithAddPropsUnset.getAdditionalProperties(), anyTypeSchema); - assertEquals(mapWithAddPropsUnset.getAdditionalPropertiesIsAnyType(), true); + assertTrue(mapWithAddPropsUnset.getAdditionalPropertiesIsAnyType()); mapWithAddPropsTrue = co.responses.get(1); assertEquals(mapWithAddPropsTrue.getAdditionalProperties(), anyTypeSchema); - assertEquals(mapWithAddPropsTrue.getAdditionalPropertiesIsAnyType(), true); + assertTrue(mapWithAddPropsTrue.getAdditionalPropertiesIsAnyType()); mapWithAddPropsFalse = co.responses.get(2); - assertEquals(mapWithAddPropsFalse.getAdditionalProperties(), null); - assertEquals(mapWithAddPropsFalse.getAdditionalPropertiesIsAnyType(), false); + assertNull(mapWithAddPropsFalse.getAdditionalProperties()); + assertFalse(mapWithAddPropsFalse.getAdditionalPropertiesIsAnyType()); mapWithAddPropsSchema = co.responses.get(3); assertEquals(mapWithAddPropsSchema.getAdditionalProperties(), stringCp); - assertEquals(mapWithAddPropsSchema.getAdditionalPropertiesIsAnyType(), false); + assertFalse(mapWithAddPropsSchema.getAdditionalPropertiesIsAnyType()); if (isGenerateAliasAsModel) { // restore the setting GlobalSettings.setProperty("generateAliasAsModel", "true"); @@ -2745,31 +2745,31 @@ public class DefaultCodegenTest { modelName = "DateWithValidation"; sc = openAPI.getComponents().getSchemas().get(modelName); cm = codegen.fromModel(modelName, sc); - assertEquals(cm.isString, false); - assertEquals(cm.isDate, true); + assertFalse(cm.isString); + assertTrue(cm.isDate); modelName = "NullModel"; sc = openAPI.getComponents().getSchemas().get(modelName); cm = codegen.fromModel(modelName, sc); - assertEquals(cm.isNull, true); + assertTrue(cm.isNull); modelName = "ObjectWithTypeNullProperties"; sc = openAPI.getComponents().getSchemas().get(modelName); cm = codegen.fromModel(modelName, sc); - assertEquals(cm.getVars().get(0).isNull, true); - assertEquals(cm.getVars().get(1).getItems().isNull, true); - assertEquals(cm.getAdditionalProperties().isNull, true); + assertTrue(cm.getVars().get(0).isNull); + assertTrue(cm.getVars().get(1).getItems().isNull); + assertTrue(cm.getAdditionalProperties().isNull); modelName = "ArrayOfNulls"; sc = openAPI.getComponents().getSchemas().get(modelName); cm = codegen.fromModel(modelName, sc); - assertEquals(cm.getItems().isNull, true); + assertTrue(cm.getItems().isNull); modelName = "ObjectWithDateWithValidation"; sc = openAPI.getComponents().getSchemas().get(modelName); cm = codegen.fromModel(modelName, sc); - assertEquals(cm.getVars().get(0).isString, false); - assertEquals(cm.getVars().get(0).isDate, true); + assertFalse(cm.getVars().get(0).isString); + assertTrue(cm.getVars().get(0).isDate); String path; Operation operation; @@ -2778,68 +2778,68 @@ public class DefaultCodegenTest { path = "/ref_date_with_validation/{date}"; operation = openAPI.getPaths().get(path).getPost(); co = codegen.fromOperation(path, "POST", operation, null); - assertEquals(co.pathParams.get(0).isString, false); - assertEquals(co.pathParams.get(0).isDate, true); - assertEquals(co.bodyParams.get(0).isString, false); - assertEquals(co.bodyParams.get(0).isDate, true); - assertEquals(co.responses.get(0).isString, false); - assertEquals(co.responses.get(0).isDate, true); + assertFalse(co.pathParams.get(0).isString); + assertTrue(co.pathParams.get(0).isDate); + assertFalse(co.bodyParams.get(0).isString); + assertTrue(co.bodyParams.get(0).isDate); + assertFalse(co.responses.get(0).isString); + assertTrue(co.responses.get(0).isDate); path = "/date_with_validation/{date}"; operation = openAPI.getPaths().get(path).getPost(); co = codegen.fromOperation(path, "POST", operation, null); - assertEquals(co.pathParams.get(0).isString, false); - assertEquals(co.pathParams.get(0).isDate, true); - assertEquals(co.bodyParams.get(0).isString, false); - assertEquals(co.bodyParams.get(0).isDate, true); - assertEquals(co.responses.get(0).isString, false); - assertEquals(co.responses.get(0).isDate, true); + assertFalse(co.pathParams.get(0).isString); + assertTrue(co.pathParams.get(0).isDate); + assertFalse(co.bodyParams.get(0).isString); + assertTrue(co.bodyParams.get(0).isDate); + assertFalse(co.responses.get(0).isString); + assertTrue(co.responses.get(0).isDate); modelName = "DateTimeWithValidation"; sc = openAPI.getComponents().getSchemas().get(modelName); cm = codegen.fromModel(modelName, sc); - assertEquals(cm.isString, false); - assertEquals(cm.isDateTime, true); + assertFalse(cm.isString); + assertTrue(cm.isDateTime); modelName = "ObjectWithDateTimeWithValidation"; sc = openAPI.getComponents().getSchemas().get(modelName); cm = codegen.fromModel(modelName, sc); - assertEquals(cm.getVars().get(0).isString, false); - assertEquals(cm.getVars().get(0).isDateTime, true); + assertFalse(cm.getVars().get(0).isString); + assertTrue(cm.getVars().get(0).isDateTime); path = "/ref_date_time_with_validation/{dateTime}"; operation = openAPI.getPaths().get(path).getPost(); co = codegen.fromOperation(path, "POST", operation, null); - assertEquals(co.pathParams.get(0).isString, false); - assertEquals(co.pathParams.get(0).isDateTime, true); - assertEquals(co.bodyParams.get(0).isString, false); - assertEquals(co.bodyParams.get(0).isDateTime, true); - assertEquals(co.responses.get(0).isString, false); - assertEquals(co.responses.get(0).isDateTime, true); + assertFalse(co.pathParams.get(0).isString); + assertTrue(co.pathParams.get(0).isDateTime); + assertFalse(co.bodyParams.get(0).isString); + assertTrue(co.bodyParams.get(0).isDateTime); + assertFalse(co.responses.get(0).isString); + assertTrue(co.responses.get(0).isDateTime); path = "/date_time_with_validation/{dateTime}"; operation = openAPI.getPaths().get(path).getPost(); co = codegen.fromOperation(path, "POST", operation, null); - assertEquals(co.pathParams.get(0).isString, false); - assertEquals(co.pathParams.get(0).isDateTime, true); - assertEquals(co.bodyParams.get(0).isString, false); - assertEquals(co.bodyParams.get(0).isDateTime, true); - assertEquals(co.responses.get(0).isString, false); - assertEquals(co.responses.get(0).isDateTime, true); + assertFalse(co.pathParams.get(0).isString); + assertTrue(co.pathParams.get(0).isDateTime); + assertFalse(co.bodyParams.get(0).isString); + assertTrue(co.bodyParams.get(0).isDateTime); + assertFalse(co.responses.get(0).isString); + assertTrue(co.responses.get(0).isDateTime); path = "/null/{param}"; operation = openAPI.getPaths().get(path).getPost(); co = codegen.fromOperation(path, "POST", operation, null); - assertEquals(co.pathParams.get(0).isNull, true); - assertEquals(co.bodyParams.get(0).isNull, true); - assertEquals(co.responses.get(0).isNull, true); + assertTrue(co.pathParams.get(0).isNull); + assertTrue(co.bodyParams.get(0).isNull); + assertTrue(co.responses.get(0).isNull); path = "/ref_null/{param}"; operation = openAPI.getPaths().get(path).getPost(); co = codegen.fromOperation(path, "POST", operation, null); - assertEquals(co.pathParams.get(0).isNull, true); - assertEquals(co.bodyParams.get(0).isNull, true); - assertEquals(co.responses.get(0).isNull, true); + assertTrue(co.pathParams.get(0).isNull); + assertTrue(co.bodyParams.get(0).isNull); + assertTrue(co.responses.get(0).isNull); } @Test @@ -2906,7 +2906,7 @@ public class DefaultCodegenTest { for (String modelName : modelNames) { sc = openAPI.getComponents().getSchemas().get(modelName); cm = codegen.fromModel(modelName, sc); - assertEquals(cm.getHasValidation(), true); + assertTrue(cm.getHasValidation()); } } @@ -2923,7 +2923,7 @@ public class DefaultCodegenTest { List props = cm.getVars(); assertEquals(props.size(), 50); for (CodegenProperty prop : props) { - assertEquals(prop.getHasValidation(), true); + assertTrue(prop.getHasValidation()); } } @@ -2939,7 +2939,7 @@ public class DefaultCodegenTest { List params = co.queryParams; assertEquals(params.size(), 50); for (CodegenParameter param : params) { - assertEquals(param.getHasValidation(), true); + assertTrue(param.getHasValidation()); } } @@ -2955,7 +2955,7 @@ public class DefaultCodegenTest { List params = co.headerParams; assertEquals(params.size(), 50); for (CodegenParameter param : params) { - assertEquals(param.getHasValidation(), true); + assertTrue(param.getHasValidation()); } } @@ -2971,7 +2971,7 @@ public class DefaultCodegenTest { List params = co.cookieParams; assertEquals(params.size(), 50); for (CodegenParameter param : params) { - assertEquals(param.getHasValidation(), true); + assertTrue(param.getHasValidation()); } } @@ -2987,7 +2987,7 @@ public class DefaultCodegenTest { List params = co.pathParams; assertEquals(params.size(), 50); for (CodegenParameter param : params) { - assertEquals(param.getHasValidation(), true); + assertTrue(param.getHasValidation()); } } @@ -3058,8 +3058,8 @@ public class DefaultCodegenTest { path = "/"+modelName; operation = openAPI.getPaths().get(path).getPost(); co = codegen.fromOperation(path, "POST", operation, null); - assertEquals(co.bodyParam.getHasValidation(), true); - assertEquals(co.responses.get(0).getHasValidation(), true); + assertTrue(co.bodyParam.getHasValidation()); + assertTrue(co.responses.get(0).getHasValidation()); } } @@ -3102,7 +3102,7 @@ public class DefaultCodegenTest { assertEquals(co.bodyParams.get(0).requiredVars, requiredVars); // CodegenOperation puts the inline schema into schemas and refs it - assertEquals(co.responses.get(0).isModel, true); + assertTrue(co.responses.get(0).isModel); assertEquals(co.responses.get(0).baseType, "objectData"); modelName = "objectData"; sc = openAPI.getComponents().getSchemas().get(modelName); @@ -3115,7 +3115,7 @@ public class DefaultCodegenTest { sc = openAPI.getComponents().getSchemas().get(modelName); cm = codegen.fromModel(modelName, sc); CodegenProperty cp = cm.getVars().get(0); - assertEquals(cp.isModel, true); + assertTrue(cp.isModel); assertEquals(cp.complexType, "objectData"); } @@ -3141,7 +3141,7 @@ public class DefaultCodegenTest { for (String modelName : modelNames) { sc = openAPI.getComponents().getSchemas().get(modelName); cm = codegen.fromModel(modelName, sc); - assertEquals(cm.getHasVars(), false); + assertFalse(cm.getHasVars()); } modelNames = Arrays.asList( @@ -3153,7 +3153,7 @@ public class DefaultCodegenTest { for (String modelName : modelNames) { sc = openAPI.getComponents().getSchemas().get(modelName); cm = codegen.fromModel(modelName, sc); - assertEquals(cm.getHasVars(), true); + assertTrue(cm.getHasVars()); } } @@ -3177,19 +3177,19 @@ public class DefaultCodegenTest { for (String modelName : modelNames) { sc = openAPI.getComponents().getSchemas().get(modelName); cm = codegen.fromModel(modelName, sc); - assertEquals(cm.vars.get(0).getHasVars(), false); + assertFalse(cm.vars.get(0).getHasVars()); } String modelName; modelName = "ArrayWithObjectWithPropsInItems"; sc = openAPI.getComponents().getSchemas().get(modelName); cm = codegen.fromModel(modelName, sc); - assertEquals(cm.getItems().getHasVars(), true); + assertTrue(cm.getItems().getHasVars()); modelName = "ObjectWithObjectWithPropsInAdditionalProperties"; sc = openAPI.getComponents().getSchemas().get(modelName); cm = codegen.fromModel(modelName, sc); - assertEquals(cm.getAdditionalProperties().getHasVars(), true); + assertTrue(cm.getAdditionalProperties().getHasVars()); } @Test @@ -3206,14 +3206,14 @@ public class DefaultCodegenTest { path = "/array_with_validations_in_items/{items}"; operation = openAPI.getPaths().get(path).getPost(); co = codegen.fromOperation(path, "POST", operation, null); - assertEquals(co.pathParams.get(0).getHasVars(), false); - assertEquals(co.bodyParam.getHasVars(), false); + assertFalse(co.pathParams.get(0).getHasVars()); + assertFalse(co.bodyParam.getHasVars()); path = "/object_with_optional_and_required_props/{objectData}"; operation = openAPI.getPaths().get(path).getPost(); co = codegen.fromOperation(path, "POST", operation, null); - assertEquals(co.pathParams.get(0).getHasVars(), true); - assertEquals(co.bodyParam.getHasVars(), true); + assertTrue(co.pathParams.get(0).getHasVars()); + assertTrue(co.bodyParam.getHasVars()); } @Test @@ -3230,13 +3230,13 @@ public class DefaultCodegenTest { path = "/additional_properties/"; operation = openAPI.getPaths().get(path).getPost(); co = codegen.fromOperation(path, "POST", operation, null); - assertEquals(co.responses.get(0).getHasVars(), false); + assertFalse(co.responses.get(0).getHasVars()); path = "/object_with_optional_and_required_props/{objectData}"; operation = openAPI.getPaths().get(path).getPost(); co = codegen.fromOperation(path, "POST", operation, null); // does not have vars because the inline schema was extracted into a component ref - assertEquals(co.responses.get(0).getHasVars(), false); + assertFalse(co.responses.get(0).getHasVars()); } @Test @@ -3268,7 +3268,7 @@ public class DefaultCodegenTest { for (String modelName : modelNamesWithoutRequired) { sc = openAPI.getComponents().getSchemas().get(modelName); cm = codegen.fromModel(modelName, sc); - assertEquals(cm.getHasRequired(), false); + assertFalse(cm.getHasRequired()); } List modelNamesWithRequired = Arrays.asList( @@ -3284,7 +3284,7 @@ public class DefaultCodegenTest { for (String modelName : modelNamesWithRequired) { sc = openAPI.getComponents().getSchemas().get(modelName); cm = codegen.fromModel(modelName, sc); - assertEquals(cm.getHasRequired(), true); + assertTrue(cm.getHasRequired()); } } @@ -3328,12 +3328,12 @@ public class DefaultCodegenTest { for (CodegenProperty var : cm.getVars()) { boolean hasRequired = var.getHasRequired(); if (modelNamesWithoutRequired.contains(var.name)) { - assertEquals(hasRequired, false); + assertFalse(hasRequired); } else if (modelNamesWithRequired.contains(var.name)) { - assertEquals(hasRequired, true); + assertTrue(hasRequired); } else { // All variables must be in the above sets - assertEquals(true, false); + fail(); } } } @@ -3378,12 +3378,12 @@ public class DefaultCodegenTest { for (CodegenParameter param : co.pathParams) { boolean hasRequired = param.getHasRequired(); if (modelNamesWithoutRequired.contains(param.baseName)) { - assertEquals(hasRequired, false); + assertFalse(hasRequired); } else if (modelNamesWithRequired.contains(param.baseName)) { - assertEquals(hasRequired, true); + assertTrue(hasRequired); } else { // All variables must be in the above sets - assertEquals(true, false); + fail(); } } } @@ -3428,13 +3428,202 @@ public class DefaultCodegenTest { for (CodegenResponse cr : co.responses) { boolean hasRequired = cr.getHasRequired(); if (modelNamesWithoutRequired.contains(cr.message)) { - assertEquals(hasRequired, false); + assertFalse(hasRequired); } else if (modelNamesWithRequired.contains(cr.message)) { - assertEquals(hasRequired, true); + assertTrue(hasRequired); } else { // All variables must be in the above sets - assertEquals(true, false); + fail(); } } } + + @Test + public void testBooleansSetForIntSchemas() { + final OpenAPI openAPI = TestUtils.parseFlattenSpec("src/test/resources/3_0/issue_9447.yaml"); + final DefaultCodegen codegen = new DefaultCodegen(); + codegen.setOpenAPI(openAPI); + codegen.setDisallowAdditionalPropertiesIfNotPresent(false); + + String modelName; + Schema sc; + CodegenModel cm; + + modelName = "UnboundedInteger"; + sc = openAPI.getComponents().getSchemas().get(modelName); + cm = codegen.fromModel(modelName, sc); + assertTrue(cm.isUnboundedInteger); + assertTrue(cm.isInteger); + assertFalse(cm.isShort); + assertFalse(cm.isLong); + + modelName = "Int32"; + sc = openAPI.getComponents().getSchemas().get(modelName); + cm = codegen.fromModel(modelName, sc); + assertFalse(cm.isUnboundedInteger); + assertTrue(cm.isInteger); + assertTrue(cm.isShort); + assertFalse(cm.isLong); + + modelName = "Int64"; + sc = openAPI.getComponents().getSchemas().get(modelName); + cm = codegen.fromModel(modelName, sc); + assertFalse(cm.isUnboundedInteger); + assertFalse(cm.isInteger); + assertFalse(cm.isShort); + assertTrue(cm.isLong); + + modelName = "ObjectModelWithIntegerProps"; + sc = openAPI.getComponents().getSchemas().get(modelName); + cm = codegen.fromModel(modelName, sc); + assertFalse(cm.isUnboundedInteger); + assertFalse(cm.isInteger); + assertFalse(cm.isShort); + assertFalse(cm.isLong); + CodegenProperty cp; + cp = cm.vars.get(0); + assertTrue(cp.isUnboundedInteger); + assertTrue(cp.isInteger); + assertFalse(cp.isShort); + assertFalse(cp.isLong); + cp = cm.vars.get(1); + assertFalse(cp.isUnboundedInteger); + assertTrue(cp.isInteger); + assertTrue(cp.isShort); + assertFalse(cp.isLong); + cp = cm.vars.get(2); + assertFalse(cp.isUnboundedInteger); + assertFalse(cp.isInteger); + assertFalse(cp.isShort); + assertTrue(cp.isLong); + + String path; + Operation operation; + CodegenOperation co; + CodegenParameter cpa; + CodegenResponse cr; + + path = "/UnboundedInteger"; + operation = openAPI.getPaths().get(path).getPost(); + co = codegen.fromOperation(path, "POST", operation, null); + cpa = co.pathParams.get(0); + assertTrue(cpa.isUnboundedInteger); + assertTrue(cpa.isInteger); + assertFalse(cpa.isShort); + assertFalse(cpa.isLong); + cpa = co.bodyParam; + assertTrue(cpa.isUnboundedInteger); + assertTrue(cpa.isInteger); + assertFalse(cpa.isShort); + assertFalse(cpa.isLong); + cr = co.responses.get(0); + assertTrue(cr.isUnboundedInteger); + assertTrue(cr.isInteger); + assertFalse(cr.isShort); + assertFalse(cr.isLong); + + path = "/Int32"; + operation = openAPI.getPaths().get(path).getPost(); + co = codegen.fromOperation(path, "POST", operation, null); + cpa = co.pathParams.get(0); + assertFalse(cpa.isUnboundedInteger); + assertTrue(cpa.isInteger); + assertTrue(cpa.isShort); + assertFalse(cpa.isLong); + cpa = co.bodyParam; + assertFalse(cpa.isUnboundedInteger); + assertTrue(cpa.isInteger); + assertTrue(cpa.isShort); + assertFalse(cpa.isLong); + cr = co.responses.get(0); + assertFalse(cr.isUnboundedInteger); + assertTrue(cr.isInteger); + assertTrue(cr.isShort); + assertFalse(cr.isLong); + + path = "/Int64"; + operation = openAPI.getPaths().get(path).getPost(); + co = codegen.fromOperation(path, "POST", operation, null); + cpa = co.pathParams.get(0); + assertFalse(cpa.isUnboundedInteger); + assertFalse(cpa.isInteger); + assertFalse(cpa.isShort); + assertTrue(cpa.isLong); + cpa = co.bodyParam; + assertFalse(cpa.isUnboundedInteger); + assertFalse(cpa.isInteger); + assertFalse(cpa.isShort); + assertTrue(cpa.isLong); + cr = co.responses.get(0); + assertFalse(cr.isUnboundedInteger); + assertFalse(cr.isInteger); + assertFalse(cr.isShort); + assertTrue(cr.isLong); + } + + @Test + public void testRemoveOperationIdPrefix() { + final OpenAPI openAPI = TestUtils.parseFlattenSpec("src/test/resources/bugs/issue_9719.yaml"); + final DefaultCodegen codegen = new DefaultCodegen(); + codegen.setOpenAPI(openAPI); + codegen.setDisallowAdditionalPropertiesIfNotPresent(false); + + String path; + Operation operation; + CodegenOperation co; + + codegen.additionalProperties().put(CodegenConstants.REMOVE_OPERATION_ID_PREFIX, "True"); + codegen.additionalProperties().put(CodegenConstants.REMOVE_OPERATION_ID_PREFIX_DELIMITER, "."); + codegen.additionalProperties().put(CodegenConstants.REMOVE_OPERATION_ID_PREFIX_COUNT, 2); + codegen.processOpts(); + path = "/dotDelimiter"; + operation = openAPI.getPaths().get(path).getGet(); + co = codegen.fromOperation(path, "GET", operation, null); + assertEquals(co.operationId, "usersGetAll"); + + codegen.additionalProperties().put(CodegenConstants.REMOVE_OPERATION_ID_PREFIX, "True"); + codegen.additionalProperties().put(CodegenConstants.REMOVE_OPERATION_ID_PREFIX_DELIMITER, "."); + codegen.additionalProperties().put(CodegenConstants.REMOVE_OPERATION_ID_PREFIX_COUNT, -1); + codegen.processOpts(); + path = "/dotDelimiter"; + operation = openAPI.getPaths().get(path).getGet(); + co = codegen.fromOperation(path, "GET", operation, null); + assertEquals(co.operationId, "getAll"); + + codegen.additionalProperties().put(CodegenConstants.REMOVE_OPERATION_ID_PREFIX, "True"); + codegen.additionalProperties().put(CodegenConstants.REMOVE_OPERATION_ID_PREFIX_DELIMITER, "."); + codegen.additionalProperties().put(CodegenConstants.REMOVE_OPERATION_ID_PREFIX_COUNT, 10); + codegen.processOpts(); + path = "/dotDelimiter"; + operation = openAPI.getPaths().get(path).getGet(); + co = codegen.fromOperation(path, "GET", operation, null); + assertEquals(co.operationId, "getAll"); + + codegen.additionalProperties().put(CodegenConstants.REMOVE_OPERATION_ID_PREFIX, "True"); + codegen.additionalProperties().put(CodegenConstants.REMOVE_OPERATION_ID_PREFIX_DELIMITER, "_"); + codegen.additionalProperties().put(CodegenConstants.REMOVE_OPERATION_ID_PREFIX_COUNT, 2); + codegen.processOpts(); + path = "/underscoreDelimiter"; + operation = openAPI.getPaths().get(path).getGet(); + co = codegen.fromOperation(path, "GET", operation, null); + assertEquals(co.operationId, "usersGetAll"); + + codegen.additionalProperties().put(CodegenConstants.REMOVE_OPERATION_ID_PREFIX, "True"); + codegen.additionalProperties().put(CodegenConstants.REMOVE_OPERATION_ID_PREFIX_DELIMITER, "_"); + codegen.additionalProperties().put(CodegenConstants.REMOVE_OPERATION_ID_PREFIX_COUNT, -1); + codegen.processOpts(); + path = "/underscoreDelimiter"; + operation = openAPI.getPaths().get(path).getGet(); + co = codegen.fromOperation(path, "GET", operation, null); + assertEquals(co.operationId, "getAll"); + + codegen.additionalProperties().put(CodegenConstants.REMOVE_OPERATION_ID_PREFIX, "True"); + codegen.additionalProperties().put(CodegenConstants.REMOVE_OPERATION_ID_PREFIX_DELIMITER, "_"); + codegen.additionalProperties().put(CodegenConstants.REMOVE_OPERATION_ID_PREFIX_COUNT, 10); + codegen.processOpts(); + path = "/underscoreDelimiter"; + operation = openAPI.getPaths().get(path).getGet(); + co = codegen.fromOperation(path, "GET", operation, null); + assertEquals(co.operationId, "getAll"); + } } diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/DefaultGeneratorTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/DefaultGeneratorTest.java index 7e6a986bb32..81869d78f91 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/DefaultGeneratorTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/DefaultGeneratorTest.java @@ -662,5 +662,62 @@ public class DefaultGeneratorTest { Assert.assertEquals(servers.get(1).url, "http://trailingshlash.io:80/v1"); Assert.assertEquals(servers.get(2).url, "http://notrailingslash.io:80/v2"); } -} + @Test + public void testProcessUserDefinedTemplatesWithConfig() throws IOException { + Path target = Files.createTempDirectory("test"); + Path templates = Files.createTempDirectory("templates"); + File output = target.toFile(); + try { + // Create custom template + File customTemplate = new File(templates.toFile(), "README.mustache"); + new File(customTemplate.getParent()).mkdirs(); + Files.write(customTemplate.toPath(), + "# {{someKey}}".getBytes(StandardCharsets.UTF_8), + StandardOpenOption.CREATE); + + final CodegenConfigurator configurator = new CodegenConfigurator() + .setGeneratorName("python") + .setInputSpec("src/test/resources/3_0/petstore.yaml") + .setPackageName("io.something") + .setTemplateDir(templates.toAbsolutePath().toString()) + .addAdditionalProperty("files", "src/test/resources/sampleConfig.json:\n\t folder: supportingjson "+ + "\n\t destinationFilename: supportingconfig.json \n\t templateType: SupportingFiles") + .setSkipOverwrite(false) + .setOutputDir(target.toAbsolutePath().toString()); + + final ClientOptInput clientOptInput = configurator.toClientOptInput(); + DefaultGenerator generator = new DefaultGenerator(false); + + generator.setGeneratorPropertyDefault(CodegenConstants.MODELS, "true"); + generator.setGeneratorPropertyDefault(CodegenConstants.MODEL_DOCS, "false"); + generator.setGeneratorPropertyDefault(CodegenConstants.APIS, "true"); + generator.setGeneratorPropertyDefault(CodegenConstants.SUPPORTING_FILES, "true"); + generator.setGeneratorPropertyDefault(CodegenConstants.API_DOCS, "false"); + generator.setGeneratorPropertyDefault(CodegenConstants.MODEL_TESTS, "false"); + generator.setGeneratorPropertyDefault(CodegenConstants.API_TESTS, "false"); + + List files = generator.opts(clientOptInput).generate(); + + // remove commented code based on review - files does not seem to be supported in CodegenConfigurator + // supporting files sanity check + // TestUtils.ensureContainsFile(files, output, "sampleConfig.json"); + // Assert.assertTrue(new File(output, "sampleConfig.json").exists()); + + // Generator should report api_client.py as a generated file + TestUtils.ensureContainsFile(files, output, "io/something/api_client.py"); + + // Generated file should exist on the filesystem after generation + File apiClient = new File(output, "io/something/api_client.py"); + Assert.assertTrue(apiClient.exists()); + + // Generated file should contain our custom packageName + TestUtils.assertFileContains(apiClient.toPath(), + "from io.something import rest" + ); + } finally { + output.delete(); + templates.toFile().delete(); + } + } +} 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 214df7effa4..f5ede0eb5a9 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 @@ -30,7 +30,7 @@ public class AndroidClientCodegenTest { codegen.processOpts(); Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP), Boolean.TRUE); - Assert.assertEquals(codegen.isHideGenerationTimestamp(), true); + Assert.assertTrue(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.apiPackage(), "org.openapitools.client.api"); diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/asciidoc/AsciidocGeneratorTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/asciidoc/AsciidocGeneratorTest.java index 0933a120a35..c5f01e4b74d 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/asciidoc/AsciidocGeneratorTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/asciidoc/AsciidocGeneratorTest.java @@ -85,7 +85,7 @@ public class AsciidocGeneratorTest { public void testAdditionalDirectoriesGeneratedIntoHeaderAttributes() throws Exception { File output = Files.createTempDirectory("test").toFile(); - LOGGER.info("test: generating sample markup " + output.getAbsolutePath()); + LOGGER.info("test: generating sample markup {}", output.getAbsolutePath()); Map props = new TreeMap(); props.put("specDir", "spec"); @@ -117,7 +117,7 @@ public class AsciidocGeneratorTest { public void testHeaderAttributesFlagRemovesAttributesFromMarkupHeaderSection() throws Exception { File output = Files.createTempDirectory("test").toFile(); - LOGGER.info("test: generating sample markup " + output.getAbsolutePath()); + LOGGER.info("test: generating sample markup {}", output.getAbsolutePath()); Map props = new TreeMap(); props.put("specDir", "spec"); diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/csharp/CSharpClientCodegenTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/csharp/CSharpClientCodegenTest.java index 96555ccb25b..5529f6d611f 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/csharp/CSharpClientCodegenTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/csharp/CSharpClientCodegenTest.java @@ -30,7 +30,7 @@ public class CSharpClientCodegenTest { codegen.processOpts(); Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP), Boolean.TRUE); - Assert.assertEquals(codegen.isHideGenerationTimestamp(), true); + Assert.assertTrue(codegen.isHideGenerationTimestamp()); } @Test @@ -40,7 +40,7 @@ public class CSharpClientCodegenTest { codegen.processOpts(); Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP), Boolean.FALSE); - Assert.assertEquals(codegen.isHideGenerationTimestamp(), false); + Assert.assertFalse(codegen.isHideGenerationTimestamp()); } @Test @@ -50,7 +50,7 @@ public class CSharpClientCodegenTest { codegen.processOpts(); Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP), Boolean.FALSE); - Assert.assertEquals(codegen.isHideGenerationTimestamp(), false); + Assert.assertFalse(codegen.isHideGenerationTimestamp()); } } diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/csharp/CSharpModelTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/csharp/CSharpModelTest.java index 40ebe302315..5384570b9d1 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/csharp/CSharpModelTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/csharp/CSharpModelTest.java @@ -21,10 +21,12 @@ import com.google.common.collect.Sets; import io.swagger.v3.oas.models.OpenAPI; import io.swagger.v3.oas.models.media.*; import io.swagger.v3.parser.util.SchemaTypeUtil; +import org.openapitools.codegen.CodegenConstants; import org.openapitools.codegen.CodegenModel; import org.openapitools.codegen.CodegenProperty; import org.openapitools.codegen.DefaultCodegen; import org.openapitools.codegen.TestUtils; +import org.openapitools.codegen.languages.AspNetCoreServerCodegen; import org.openapitools.codegen.languages.CSharpClientCodegen; import org.testng.Assert; import org.testng.annotations.Test; @@ -76,7 +78,7 @@ public class CSharpModelTest { final CodegenProperty property = generated.vars.get(1); Assert.assertEquals(property.baseName, "examples"); Assert.assertEquals(property.name, "Examples"); - Assert.assertEquals(property.defaultValue, null); + Assert.assertNull(property.defaultValue); Assert.assertEquals(property.dataType, "Collection"); Assert.assertEquals(property.baseType, "Collection"); Assert.assertEquals(property.containerType, "array"); @@ -264,6 +266,126 @@ public class CSharpModelTest { Assert.assertTrue(property3.isPrimitiveType); } + @Test(description = "convert a model with a nullable property without nullable annotation") + public void nullablePropertyWithoutNullableReferenceTypesTest() { + final Schema model = new Schema() + .description("a sample model") + .addProperties("id", new IntegerSchema().format(SchemaTypeUtil.INTEGER64_FORMAT).nullable(true)) + .addProperties("urls", new ArraySchema() + .items(new StringSchema()).nullable(true)) + .addProperties("name", new StringSchema().nullable(true)) + .addProperties("subObject", new Schema().addProperties("name", new StringSchema()).nullable(true)) + .addRequiredItem("id"); + final DefaultCodegen codegen = new AspNetCoreServerCodegen(); + OpenAPI openAPI = TestUtils.createOpenAPIWithOneSchema("sample", model); + codegen.setOpenAPI(openAPI); + final CodegenModel cm = codegen.fromModel("sample", model); + + Assert.assertEquals(cm.name, "sample"); + Assert.assertEquals(cm.classname, "Sample"); + Assert.assertEquals(cm.description, "a sample model"); + Assert.assertEquals(cm.vars.size(), 4); + + final CodegenProperty property1 = cm.vars.get(0); + Assert.assertEquals(property1.baseName, "id"); + Assert.assertEquals(property1.dataType, "long?"); + Assert.assertEquals(property1.name, "Id"); + Assert.assertNull(property1.defaultValue); + Assert.assertEquals(property1.baseType, "long?"); + Assert.assertTrue(property1.required); + Assert.assertTrue(property1.isPrimitiveType); + + final CodegenProperty property2 = cm.vars.get(1); + Assert.assertEquals(property2.baseName, "urls"); + Assert.assertEquals(property2.dataType, "List"); + Assert.assertEquals(property2.name, "Urls"); + Assert.assertNull(property2.defaultValue); + Assert.assertEquals(property2.baseType, "List"); + Assert.assertEquals(property2.containerType, "array"); + Assert.assertFalse(property2.required); + Assert.assertTrue(property2.isPrimitiveType); + Assert.assertTrue(property2.isContainer); + + final CodegenProperty property3 = cm.vars.get(2); + Assert.assertEquals(property3.baseName, "name"); + Assert.assertEquals(property3.dataType, "string"); + Assert.assertEquals(property3.name, "Name"); + Assert.assertNull(property3.defaultValue); + Assert.assertEquals(property3.baseType, "string"); + Assert.assertFalse(property3.required); + Assert.assertTrue(property3.isPrimitiveType); + + final CodegenProperty property4 = cm.vars.get(3); + Assert.assertEquals(property4.baseName, "subObject"); + Assert.assertEquals(property4.dataType, "Object"); + Assert.assertEquals(property4.name, "SubObject"); + Assert.assertNull(property4.defaultValue); + Assert.assertEquals(property4.baseType, "Object"); + Assert.assertFalse(property4.required); + Assert.assertTrue(property4.isPrimitiveType); + } + + @Test(description = "convert a model with a nullable property using nullable annotation") + public void nullablePropertyWithNullableReferenceTypesTest() { + final Schema model = new Schema() + .description("a sample model") + .addProperties("id", new IntegerSchema().format(SchemaTypeUtil.INTEGER64_FORMAT).nullable(true)) + .addProperties("urls", new ArraySchema() + .items(new StringSchema()).nullable(true)) + .addProperties("name", new StringSchema().nullable(true)) + .addProperties("subObject", new Schema().addProperties("name", new StringSchema()).nullable(true)) + .addRequiredItem("id"); + final DefaultCodegen codegen = new AspNetCoreServerCodegen(); + codegen.additionalProperties().put(CodegenConstants.NULLABLE_REFERENCE_TYPES, true); + codegen.processOpts(); + OpenAPI openAPI = TestUtils.createOpenAPIWithOneSchema("sample", model); + codegen.setOpenAPI(openAPI); + final CodegenModel cm = codegen.fromModel("sample", model); + + Assert.assertEquals(cm.name, "sample"); + Assert.assertEquals(cm.classname, "Sample"); + Assert.assertEquals(cm.description, "a sample model"); + Assert.assertEquals(cm.vars.size(), 4); + + final CodegenProperty property1 = cm.vars.get(0); + Assert.assertEquals(property1.baseName, "id"); + Assert.assertEquals(property1.dataType, "long?"); + Assert.assertEquals(property1.name, "Id"); + Assert.assertNull(property1.defaultValue); + Assert.assertEquals(property1.baseType, "long?"); + Assert.assertTrue(property1.required); + Assert.assertTrue(property1.isPrimitiveType); + + final CodegenProperty property2 = cm.vars.get(1); + Assert.assertEquals(property2.baseName, "urls"); + Assert.assertEquals(property2.dataType, "List"); + Assert.assertEquals(property2.name, "Urls"); + Assert.assertNull(property2.defaultValue); + Assert.assertEquals(property2.baseType, "List?"); + Assert.assertEquals(property2.containerType, "array"); + Assert.assertFalse(property2.required); + Assert.assertTrue(property2.isPrimitiveType); + Assert.assertTrue(property2.isContainer); + + final CodegenProperty property3 = cm.vars.get(2); + Assert.assertEquals(property3.baseName, "name"); + Assert.assertEquals(property3.dataType, "string?"); + Assert.assertEquals(property3.name, "Name"); + Assert.assertNull(property3.defaultValue); + Assert.assertEquals(property3.baseType, "string?"); + Assert.assertFalse(property3.required); + Assert.assertFalse(property3.isPrimitiveType); + + final CodegenProperty property4 = cm.vars.get(3); + Assert.assertEquals(property4.baseName, "subObject"); + Assert.assertEquals(property4.dataType, "Object?"); + Assert.assertEquals(property4.name, "SubObject"); + Assert.assertNull(property4.defaultValue); + Assert.assertEquals(property4.baseType, "Object?"); + Assert.assertFalse(property4.required); + Assert.assertFalse(property4.isPrimitiveType); + } + @Test(description = "convert a model with list property") public void listPropertyTest() { final Schema model = new Schema() diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/dart/DartClientCodegenTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/dart/DartClientCodegenTest.java index d69f5f71122..a49ee4e825c 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/dart/DartClientCodegenTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/dart/DartClientCodegenTest.java @@ -38,7 +38,7 @@ public class DartClientCodegenTest { codegen.processOpts(); Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP), Boolean.TRUE); - Assert.assertEquals(codegen.isHideGenerationTimestamp(), true); + Assert.assertTrue(codegen.isHideGenerationTimestamp()); } @Test @@ -48,7 +48,7 @@ public class DartClientCodegenTest { codegen.processOpts(); Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP), Boolean.FALSE); - Assert.assertEquals(codegen.isHideGenerationTimestamp(), false); + Assert.assertFalse(codegen.isHideGenerationTimestamp()); } @Test @@ -58,7 +58,7 @@ public class DartClientCodegenTest { codegen.processOpts(); Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP), Boolean.FALSE); - Assert.assertEquals(codegen.isHideGenerationTimestamp(), false); + Assert.assertFalse(codegen.isHideGenerationTimestamp()); } @Test @@ -77,11 +77,11 @@ public class DartClientCodegenTest { Assert.fail(errorString, e); } - Assert.assertEquals(reservedWordsList.size() > 20, true); - Assert.assertEquals(codegen.reservedWords().size() == reservedWordsList.size(), true); + Assert.assertTrue(reservedWordsList.size() > 20); + Assert.assertEquals(codegen.reservedWords().size(), reservedWordsList.size()); for(String keyword : reservedWordsList) { // reserved words are stored in lowercase - Assert.assertEquals(codegen.reservedWords().contains(keyword.toLowerCase(Locale.ROOT)), true, String.format(Locale.ROOT, "%s, part of %s, was not found in %s", keyword, reservedWordsList, codegen.reservedWords().toString())); + Assert.assertTrue(codegen.reservedWords().contains(keyword.toLowerCase(Locale.ROOT)), String.format(Locale.ROOT, "%s, part of %s, was not found in %s", keyword, reservedWordsList, codegen.reservedWords().toString())); } } diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/dart/dio/DartDioClientCodegenTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/dart/dio/DartDioClientCodegenTest.java index e0ad1e14e8a..95a47ba87fe 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/dart/dio/DartDioClientCodegenTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/dart/dio/DartDioClientCodegenTest.java @@ -37,7 +37,7 @@ public class DartDioClientCodegenTest { codegen.processOpts(); Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP), Boolean.TRUE); - Assert.assertEquals(codegen.isHideGenerationTimestamp(), true); + Assert.assertTrue(codegen.isHideGenerationTimestamp()); } @Test @@ -47,7 +47,7 @@ public class DartDioClientCodegenTest { codegen.processOpts(); Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP), Boolean.FALSE); - Assert.assertEquals(codegen.isHideGenerationTimestamp(), false); + Assert.assertFalse(codegen.isHideGenerationTimestamp()); } @Test @@ -57,7 +57,7 @@ public class DartDioClientCodegenTest { codegen.processOpts(); Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP), Boolean.FALSE); - Assert.assertEquals(codegen.isHideGenerationTimestamp(), false); + Assert.assertFalse(codegen.isHideGenerationTimestamp()); } @Test @@ -74,11 +74,11 @@ public class DartDioClientCodegenTest { Assert.fail(errorString, e); } - Assert.assertEquals(reservedWordsList.size() > 20, true); - Assert.assertEquals(codegen.reservedWords().size() == reservedWordsList.size(), true); + Assert.assertTrue(reservedWordsList.size() > 20); + Assert.assertEquals(codegen.reservedWords().size(), reservedWordsList.size()); for(String keyword : reservedWordsList) { // reserved words are stored in lowercase - Assert.assertEquals(codegen.reservedWords().contains(keyword.toLowerCase(Locale.ROOT)), true, String.format(Locale.ROOT, "%s, part of %s, was not found in %s", keyword, reservedWordsList, codegen.reservedWords().toString())); + Assert.assertTrue(codegen.reservedWords().contains(keyword.toLowerCase(Locale.ROOT)), String.format(Locale.ROOT, "%s, part of %s, was not found in %s", keyword, reservedWordsList, codegen.reservedWords().toString())); } } diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/dart/dio/DartDioNextClientCodegenTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/dart/dio/DartDioNextClientCodegenTest.java index 3886a252193..805d9dd03e3 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/dart/dio/DartDioNextClientCodegenTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/dart/dio/DartDioNextClientCodegenTest.java @@ -38,7 +38,7 @@ public class DartDioNextClientCodegenTest { codegen.processOpts(); Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP), Boolean.TRUE); - Assert.assertEquals(codegen.isHideGenerationTimestamp(), true); + Assert.assertTrue(codegen.isHideGenerationTimestamp()); } @Test @@ -48,7 +48,7 @@ public class DartDioNextClientCodegenTest { codegen.processOpts(); Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP), Boolean.FALSE); - Assert.assertEquals(codegen.isHideGenerationTimestamp(), false); + Assert.assertFalse(codegen.isHideGenerationTimestamp()); } @Test @@ -58,7 +58,7 @@ public class DartDioNextClientCodegenTest { codegen.processOpts(); Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP), Boolean.FALSE); - Assert.assertEquals(codegen.isHideGenerationTimestamp(), false); + Assert.assertFalse(codegen.isHideGenerationTimestamp()); } @Test @@ -75,11 +75,11 @@ public class DartDioNextClientCodegenTest { Assert.fail(errorString, e); } - Assert.assertEquals(reservedWordsList.size() > 20, true); - Assert.assertEquals(codegen.reservedWords().size() == reservedWordsList.size(), true); + Assert.assertTrue(reservedWordsList.size() > 20); + Assert.assertEquals(codegen.reservedWords().size(), reservedWordsList.size()); for(String keyword : reservedWordsList) { // reserved words are stored in lowercase - Assert.assertEquals(codegen.reservedWords().contains(keyword.toLowerCase(Locale.ROOT)), true, String.format(Locale.ROOT, "%s, part of %s, was not found in %s", keyword, reservedWordsList, codegen.reservedWords().toString())); + Assert.assertTrue(codegen.reservedWords().contains(keyword.toLowerCase(Locale.ROOT)), String.format(Locale.ROOT, "%s, part of %s, was not found in %s", keyword, reservedWordsList, codegen.reservedWords().toString())); } } diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/eiffel/AbstractEiffelCodegenTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/eiffel/AbstractEiffelCodegenTest.java index 1a2bcaeeb1b..e0b2dc42507 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/eiffel/AbstractEiffelCodegenTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/eiffel/AbstractEiffelCodegenTest.java @@ -31,7 +31,7 @@ public class AbstractEiffelCodegenTest { codegen.processOpts(); Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP), Boolean.FALSE); - Assert.assertEquals(codegen.isHideGenerationTimestamp(), false); + Assert.assertFalse(codegen.isHideGenerationTimestamp()); } @Test @@ -41,7 +41,7 @@ public class AbstractEiffelCodegenTest { codegen.processOpts(); Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP), Boolean.TRUE); - Assert.assertEquals(codegen.isHideGenerationTimestamp(), true); + Assert.assertTrue(codegen.isHideGenerationTimestamp()); } @Test @@ -51,7 +51,7 @@ public class AbstractEiffelCodegenTest { codegen.processOpts(); Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP), Boolean.TRUE); - Assert.assertEquals(codegen.isHideGenerationTimestamp(), true); + Assert.assertTrue(codegen.isHideGenerationTimestamp()); } private static class P_AbstractEiffelCodegen extends AbstractEiffelCodegen { diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/eiffel/EiffelClientCodegenTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/eiffel/EiffelClientCodegenTest.java index 9cbea46c024..f470a48e3ce 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/eiffel/EiffelClientCodegenTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/eiffel/EiffelClientCodegenTest.java @@ -30,7 +30,7 @@ public class EiffelClientCodegenTest { codegen.processOpts(); Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP), Boolean.TRUE); - Assert.assertEquals(codegen.isHideGenerationTimestamp(), true); + Assert.assertTrue(codegen.isHideGenerationTimestamp()); } @Test @@ -40,7 +40,7 @@ public class EiffelClientCodegenTest { codegen.processOpts(); Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP), Boolean.FALSE); - Assert.assertEquals(codegen.isHideGenerationTimestamp(), false); + Assert.assertFalse(codegen.isHideGenerationTimestamp()); } @Test @@ -50,7 +50,7 @@ public class EiffelClientCodegenTest { codegen.processOpts(); Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP), Boolean.FALSE); - Assert.assertEquals(codegen.isHideGenerationTimestamp(), false); + Assert.assertFalse(codegen.isHideGenerationTimestamp()); } } diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/fsharp/FSharpServerCodegenTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/fsharp/FSharpServerCodegenTest.java index 47c23b2ea73..fb822ec2df8 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/fsharp/FSharpServerCodegenTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/fsharp/FSharpServerCodegenTest.java @@ -65,7 +65,7 @@ public class FSharpServerCodegenTest { Object[] keys = sorted.keySet().toArray(); - Assert.assertTrue("wheel".equals(keys[0])); + Assert.assertEquals(keys[0], "wheel"); Assert.assertTrue("bike".equals(keys[1]) || "car".equals(keys[1])); Assert.assertTrue("bike".equals(keys[2]) || "car".equals(keys[2])); Assert.assertEquals(keys[3], "parent"); diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/go/AbstractGoCodegenTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/go/AbstractGoCodegenTest.java index f5b730e1ccf..4bb8762268d 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/go/AbstractGoCodegenTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/go/AbstractGoCodegenTest.java @@ -38,7 +38,7 @@ public class AbstractGoCodegenTest { codegen.processOpts(); Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP), Boolean.FALSE); - Assert.assertEquals(codegen.isHideGenerationTimestamp(), false); + Assert.assertFalse(codegen.isHideGenerationTimestamp()); } @Test @@ -48,7 +48,7 @@ public class AbstractGoCodegenTest { codegen.processOpts(); Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP), Boolean.TRUE); - Assert.assertEquals(codegen.isHideGenerationTimestamp(), true); + Assert.assertTrue(codegen.isHideGenerationTimestamp()); } @Test @@ -58,7 +58,7 @@ public class AbstractGoCodegenTest { codegen.processOpts(); Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP), Boolean.TRUE); - Assert.assertEquals(codegen.isHideGenerationTimestamp(), true); + Assert.assertTrue(codegen.isHideGenerationTimestamp()); } @Test 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 9c5763e9e0a..b6df5e72e00 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 @@ -36,7 +36,7 @@ public class GoClientCodegenTest { codegen.processOpts(); Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP), Boolean.TRUE); - Assert.assertEquals(codegen.isHideGenerationTimestamp(), true); + Assert.assertTrue(codegen.isHideGenerationTimestamp()); } @Test @@ -46,7 +46,7 @@ public class GoClientCodegenTest { codegen.processOpts(); Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP), Boolean.FALSE); - Assert.assertEquals(codegen.isHideGenerationTimestamp(), false); + Assert.assertFalse(codegen.isHideGenerationTimestamp()); } @Test @@ -56,7 +56,7 @@ public class GoClientCodegenTest { codegen.processOpts(); Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP), Boolean.FALSE); - Assert.assertEquals(codegen.isHideGenerationTimestamp(), false); + Assert.assertFalse(codegen.isHideGenerationTimestamp()); } @Test(description = "test example value for body parameter") diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/haskellhttpclient/HaskellHttpClientCodegenTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/haskellhttpclient/HaskellHttpClientCodegenTest.java index 7c5e50459a0..403000c1955 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/haskellhttpclient/HaskellHttpClientCodegenTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/haskellhttpclient/HaskellHttpClientCodegenTest.java @@ -30,7 +30,7 @@ public class HaskellHttpClientCodegenTest { codegen.processOpts(); Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP), Boolean.TRUE); - Assert.assertEquals(codegen.isHideGenerationTimestamp(), true); + Assert.assertTrue(codegen.isHideGenerationTimestamp()); } @Test @@ -40,7 +40,7 @@ public class HaskellHttpClientCodegenTest { codegen.processOpts(); Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP), Boolean.FALSE); - Assert.assertEquals(codegen.isHideGenerationTimestamp(), false); + Assert.assertFalse(codegen.isHideGenerationTimestamp()); } @Test @@ -50,7 +50,7 @@ public class HaskellHttpClientCodegenTest { codegen.processOpts(); Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP), Boolean.FALSE); - Assert.assertEquals(codegen.isHideGenerationTimestamp(), false); + Assert.assertFalse(codegen.isHideGenerationTimestamp()); } } diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/haskellservant/HaskellModelTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/haskellservant/HaskellModelTest.java index 55896b6ecfa..82e4f915fde 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/haskellservant/HaskellModelTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/haskellservant/HaskellModelTest.java @@ -24,6 +24,5 @@ public class HaskellModelTest { @Test(description = "convert a haskell model with dots") public void modelTest() { - Assert.assertEquals(true, true); } } 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 362f4cc3da0..5cfeb03d57f 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 @@ -131,7 +131,7 @@ public class AbstractJavaCodegenTest { codegen.preprocessOpenAPI(openAPI); Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP), Boolean.FALSE); - Assert.assertEquals(codegen.isHideGenerationTimestamp(), false); + Assert.assertFalse(codegen.isHideGenerationTimestamp()); Assert.assertEquals(codegen.modelPackage(), "invalidPackageName"); Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.MODEL_PACKAGE), "invalidPackageName"); Assert.assertEquals(codegen.apiPackage(), "invalidPackageName"); @@ -160,7 +160,7 @@ public class AbstractJavaCodegenTest { codegen.preprocessOpenAPI(openAPI); Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP), Boolean.TRUE); - Assert.assertEquals(codegen.isHideGenerationTimestamp(), 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.apiPackage(), "xyz.yyyyy.zzzzzzz.api"); @@ -188,7 +188,7 @@ public class AbstractJavaCodegenTest { Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP), Boolean.FALSE); - Assert.assertEquals(codegen.isHideGenerationTimestamp(), false); + Assert.assertFalse(codegen.isHideGenerationTimestamp()); Assert.assertEquals(codegen.modelPackage(), "xyz.yyyyy.model.oooooo"); Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.MODEL_PACKAGE), "xyz.yyyyy.model.oooooo"); Assert.assertEquals(codegen.apiPackage(), "xyz.yyyyy.api.oooooo"); diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/JavaCXFClientCodegenTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/JavaCXFClientCodegenTest.java index 02f3d81f6ff..9f1bc6f7e60 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/JavaCXFClientCodegenTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/JavaCXFClientCodegenTest.java @@ -79,7 +79,7 @@ public class JavaCXFClientCodegenTest { codegen.processOpts(); Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP), Boolean.FALSE); - Assert.assertEquals(codegen.isHideGenerationTimestamp(), false); + Assert.assertFalse(codegen.isHideGenerationTimestamp()); Assert.assertEquals(codegen.modelPackage(), "org.openapitools.model"); Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.MODEL_PACKAGE), "org.openapitools.model"); @@ -97,7 +97,7 @@ public class JavaCXFClientCodegenTest { codegen.processOpts(); Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP), Boolean.TRUE); - Assert.assertEquals(codegen.isHideGenerationTimestamp(), true); + Assert.assertTrue(codegen.isHideGenerationTimestamp()); Assert.assertEquals(codegen.modelPackage(), "org.openapitools.model"); Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.MODEL_PACKAGE), "org.openapitools.model"); Assert.assertEquals(codegen.apiPackage(), "org.openapitools.api"); @@ -114,7 +114,7 @@ public class JavaCXFClientCodegenTest { codegen.processOpts(); Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP), Boolean.FALSE); - Assert.assertEquals(codegen.isHideGenerationTimestamp(), false); + Assert.assertFalse(codegen.isHideGenerationTimestamp()); Assert.assertEquals(codegen.modelPackage(), "org.openapitools.model"); Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.MODEL_PACKAGE), "org.openapitools.model"); Assert.assertEquals(codegen.apiPackage(), "org.openapitools.api"); 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 3a7636d631c..48fa9cadcfb 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 @@ -146,7 +146,7 @@ public class JavaClientCodegenTest { codegen.processOpts(); Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP), Boolean.FALSE); - Assert.assertEquals(codegen.isHideGenerationTimestamp(), false); + Assert.assertFalse(codegen.isHideGenerationTimestamp()); Assert.assertEquals(codegen.modelPackage(), "org.openapitools.client.model"); Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.MODEL_PACKAGE), "org.openapitools.client.model"); @@ -168,7 +168,7 @@ public class JavaClientCodegenTest { codegen.processOpts(); Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP), Boolean.TRUE); - Assert.assertEquals(codegen.isHideGenerationTimestamp(), 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.apiPackage(), "xyz.yyyyy.zzzzzzz.api"); @@ -190,7 +190,7 @@ public class JavaClientCodegenTest { codegen.processOpts(); Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP), Boolean.TRUE); - Assert.assertEquals(codegen.isHideGenerationTimestamp(), 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.apiPackage(), "xyz.yyyyy.zzzzzzz.aaaaa.api"); @@ -526,10 +526,10 @@ public class JavaClientCodegenTest { ApiResponse ok_200 = openAPI.getComponents().getResponses().get("OK_200"); CodegenResponse response = codegen.fromResponse("200", ok_200); - Assert.assertEquals(1, response.headers.size()); + Assert.assertEquals(response.headers.size(), 1); CodegenProperty header = response.headers.get(0); - Assert.assertEquals("UUID", header.dataType); - Assert.assertEquals("Request", header.baseName); + Assert.assertEquals(header.dataType, "UUID"); + Assert.assertEquals(header.baseName, "Request"); } @Test @@ -746,9 +746,9 @@ public class JavaClientCodegenTest { @Test public void escapeName() { final JavaClientCodegen codegen = new JavaClientCodegen(); - assertEquals("_default", codegen.toApiVarName("Default")); - assertEquals("_int", codegen.toApiVarName("int")); - assertEquals("pony", codegen.toApiVarName("pony")); + assertEquals(codegen.toApiVarName("Default"), "_default"); + assertEquals(codegen.toApiVarName("int"), "_int"); + assertEquals(codegen.toApiVarName("pony"), "pony"); } @Test @@ -1028,18 +1028,18 @@ public class JavaClientCodegenTest { 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)", + "multipartArray(java.util.Collection files)", + "multipartArrayWithHttpInfo(java.util.Collection files)", "formParams.addAll(\"files\", files.stream().collect(Collectors.toList()));", //mixed - "multipartMixed(org.springframework.web.multipart.MultipartFile file, MultipartMixedMarker marker)", - "multipartMixedWithHttpInfo(org.springframework.web.multipart.MultipartFile file, MultipartMixedMarker marker)", + "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.web.multipart.MultipartFile file)", - "multipartSingleWithHttpInfo(org.springframework.web.multipart.MultipartFile file)", + "multipartSingle(org.springframework.core.io.Resource file)", + "multipartSingleWithHttpInfo(org.springframework.core.io.Resource file)", "formParams.add(\"file\", file);" ); } diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/JavaModelEnumTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/JavaModelEnumTest.java index f108ce00b50..11c39751450 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/JavaModelEnumTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/JavaModelEnumTest.java @@ -52,7 +52,7 @@ public class JavaModelEnumTest { Assert.assertEquals(enumVar.dataType, "String"); Assert.assertEquals(enumVar.datatypeWithEnum, "NameEnum"); Assert.assertEquals(enumVar.name, "name"); - Assert.assertEquals(enumVar.defaultValue, null); + Assert.assertNull(enumVar.defaultValue); Assert.assertEquals(enumVar.baseType, "String"); Assert.assertTrue(enumVar.isEnum); } @@ -83,7 +83,7 @@ public class JavaModelEnumTest { Assert.assertEquals(enumVar.mostInnerItems.dataType, "String"); Assert.assertEquals(enumVar.mostInnerItems.datatypeWithEnum, "NameEnum"); Assert.assertEquals(enumVar.mostInnerItems.name, "name"); - Assert.assertEquals(enumVar.mostInnerItems.defaultValue, null); + Assert.assertNull(enumVar.mostInnerItems.defaultValue); Assert.assertEquals(enumVar.mostInnerItems.baseType, "String"); Assert.assertEquals(enumVar.mostInnerItems.baseType, enumVar.items.baseType); @@ -116,7 +116,7 @@ public class JavaModelEnumTest { Assert.assertEquals(enumVar.mostInnerItems.dataType, "String"); Assert.assertEquals(enumVar.mostInnerItems.datatypeWithEnum, "NameEnum"); Assert.assertEquals(enumVar.mostInnerItems.name, "name"); - Assert.assertEquals(enumVar.mostInnerItems.defaultValue, null); + Assert.assertNull(enumVar.mostInnerItems.defaultValue); Assert.assertEquals(enumVar.mostInnerItems.baseType, "String"); Assert.assertEquals(enumVar.mostInnerItems.baseType, enumVar.items.items.baseType); diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/JavaModelTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/JavaModelTest.java index 74beee0159a..8827229bfad 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/JavaModelTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/JavaModelTest.java @@ -71,7 +71,7 @@ public class JavaModelTest { Assert.assertEquals(property1.setter, "setId"); Assert.assertEquals(property1.dataType, "Long"); Assert.assertEquals(property1.name, "id"); - Assert.assertEquals(property1.defaultValue, null); + Assert.assertNull(property1.defaultValue); Assert.assertEquals(property1.baseType, "Long"); Assert.assertTrue(property1.required); Assert.assertFalse(property1.isContainer); @@ -84,7 +84,7 @@ public class JavaModelTest { Assert.assertEquals(property2.setter, "setName"); Assert.assertEquals(property2.dataType, "String"); Assert.assertEquals(property2.name, "name"); - Assert.assertEquals(property2.defaultValue, null); + Assert.assertNull(property2.defaultValue); Assert.assertEquals(property2.baseType, "String"); Assert.assertEquals(property2.example, "Tony"); Assert.assertTrue(property2.required); @@ -98,7 +98,7 @@ public class JavaModelTest { Assert.assertEquals(property3.setter, "setCreatedAt"); Assert.assertEquals(property3.dataType, "Date"); Assert.assertEquals(property3.name, "createdAt"); - Assert.assertEquals(property3.defaultValue, null); + Assert.assertNull(property3.defaultValue); Assert.assertEquals(property3.baseType, "Date"); Assert.assertFalse(property3.required); Assert.assertFalse(property3.isContainer); @@ -274,7 +274,7 @@ public class JavaModelTest { Assert.assertEquals(property.setter, "setAtSomeColonRestrictedPercentCharactersHashToExclamationHandlePlus"); Assert.assertEquals(property.dataType, "Boolean"); Assert.assertEquals(property.name, "atSomeColonRestrictedPercentCharactersHashToExclamationHandlePlus"); - Assert.assertEquals(property.defaultValue, null); + Assert.assertNull(property.defaultValue); Assert.assertEquals(property.baseType, "Boolean"); Assert.assertFalse(property.required); Assert.assertFalse(property.isContainer); @@ -491,7 +491,7 @@ public class JavaModelTest { Assert.assertEquals(property.setter, "setNAME"); Assert.assertEquals(property.dataType, "String"); Assert.assertEquals(property.name, "NAME"); - Assert.assertEquals(property.defaultValue, null); + Assert.assertNull(property.defaultValue); Assert.assertEquals(property.baseType, "String"); Assert.assertTrue(property.required); Assert.assertFalse(property.isContainer); @@ -518,7 +518,7 @@ public class JavaModelTest { Assert.assertEquals(property.setter, "setNAME1"); Assert.assertEquals(property.dataType, "String"); Assert.assertEquals(property.name, "NAME1"); - Assert.assertEquals(property.defaultValue, null); + Assert.assertNull(property.defaultValue); Assert.assertEquals(property.baseType, "String"); Assert.assertTrue(property.required); Assert.assertFalse(property.isContainer); @@ -545,7 +545,7 @@ public class JavaModelTest { Assert.assertEquals(property.setter, "setpId"); Assert.assertEquals(property.dataType, "String"); Assert.assertEquals(property.name, "pId"); - Assert.assertEquals(property.defaultValue, null); + Assert.assertNull(property.defaultValue); Assert.assertEquals(property.baseType, "String"); Assert.assertTrue(property.required); Assert.assertFalse(property.isContainer); @@ -572,7 +572,7 @@ public class JavaModelTest { Assert.assertEquals(property.setter, "setAtTName"); Assert.assertEquals(property.dataType, "String"); Assert.assertEquals(property.name, "atTName"); - Assert.assertEquals(property.defaultValue, null); + Assert.assertNull(property.defaultValue); Assert.assertEquals(property.baseType, "String"); Assert.assertTrue(property.required); Assert.assertFalse(property.isContainer); @@ -599,7 +599,7 @@ public class JavaModelTest { Assert.assertEquals(property.setter, "setATTNAME"); Assert.assertEquals(property.dataType, "String"); Assert.assertEquals(property.name, "ATT_NAME"); - Assert.assertEquals(property.defaultValue, null); + Assert.assertNull(property.defaultValue); Assert.assertEquals(property.baseType, "String"); Assert.assertTrue(property.required); Assert.assertFalse(property.isContainer); @@ -668,7 +668,7 @@ public class JavaModelTest { Assert.assertEquals(property.setter, "setInputBinaryData"); Assert.assertEquals(property.dataType, "byte[]"); Assert.assertEquals(property.name, "inputBinaryData"); - Assert.assertEquals(property.defaultValue, null); + Assert.assertNull(property.defaultValue); Assert.assertEquals(property.baseType, "byte[]"); Assert.assertFalse(property.required); Assert.assertFalse(property.isContainer); @@ -694,7 +694,7 @@ public class JavaModelTest { Assert.assertEquals(property.setter, "setU"); Assert.assertEquals(property.dataType, "String"); Assert.assertEquals(property.name, "u"); - Assert.assertEquals(property.defaultValue, null); + Assert.assertNull(property.defaultValue); Assert.assertEquals(property.baseType, "String"); Assert.assertFalse(property.isContainer); } @@ -839,7 +839,7 @@ public class JavaModelTest { Assert.assertEquals(property2.setter, "setName"); Assert.assertEquals(property2.dataType, "String"); Assert.assertEquals(property2.name, "name"); - Assert.assertEquals(property2.defaultValue, null); + Assert.assertNull(property2.defaultValue); Assert.assertEquals(property2.baseType, "String"); Assert.assertEquals(property2.example, "Tony"); Assert.assertTrue(property2.required); @@ -854,7 +854,7 @@ public class JavaModelTest { Assert.assertEquals(property3.setter, "setCreatedAt"); Assert.assertEquals(property3.dataType, "Date"); Assert.assertEquals(property3.name, "createdAt"); - Assert.assertEquals(property3.defaultValue, null); + Assert.assertNull(property3.defaultValue); Assert.assertEquals(property3.baseType, "Date"); Assert.assertFalse(property3.required); Assert.assertFalse(property3.isContainer); diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/jaxrs/AbstractJavaJAXRSServerCodegenTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/jaxrs/AbstractJavaJAXRSServerCodegenTest.java index 7aaf1ac6c38..bd10d0beffc 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/jaxrs/AbstractJavaJAXRSServerCodegenTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/jaxrs/AbstractJavaJAXRSServerCodegenTest.java @@ -51,7 +51,7 @@ public class AbstractJavaJAXRSServerCodegenTest { codegen.preprocessOpenAPI(openAPI); Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP), Boolean.FALSE); - Assert.assertEquals(codegen.isHideGenerationTimestamp(), false); + Assert.assertFalse(codegen.isHideGenerationTimestamp()); Assert.assertEquals(codegen.modelPackage(), "org.openapitools.model"); Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.MODEL_PACKAGE), "org.openapitools.model"); Assert.assertEquals(codegen.apiPackage(), "org.openapitools.api"); @@ -71,7 +71,7 @@ public class AbstractJavaJAXRSServerCodegenTest { codegen.processOpts(); Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP), Boolean.TRUE); - Assert.assertEquals(codegen.isHideGenerationTimestamp(), true); + Assert.assertTrue(codegen.isHideGenerationTimestamp()); Assert.assertEquals(codegen.modelPackage(), "xx.yyyyyyyy.model"); Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.MODEL_PACKAGE), "xx.yyyyyyyy.model"); Assert.assertEquals(codegen.apiPackage(), "xx.yyyyyyyy.api"); @@ -95,7 +95,7 @@ public class AbstractJavaJAXRSServerCodegenTest { codegen.preprocessOpenAPI(openAPI); Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP), Boolean.TRUE); - Assert.assertEquals(codegen.isHideGenerationTimestamp(), true); + Assert.assertTrue(codegen.isHideGenerationTimestamp()); Assert.assertEquals(codegen.modelPackage(), "xyz.yyyyy.mmmmm.model"); Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.MODEL_PACKAGE), "xyz.yyyyy.mmmmm.model"); Assert.assertEquals(codegen.apiPackage(), "xyz.yyyyy.aaaaa.api"); diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/kotlin/KotlinModelCodegenTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/kotlin/KotlinModelCodegenTest.java index 19829496e23..af675c8913d 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/kotlin/KotlinModelCodegenTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/kotlin/KotlinModelCodegenTest.java @@ -52,12 +52,17 @@ public class KotlinModelCodegenTest { } private void checkModel(AbstractKotlinCodegen codegen, boolean mutable, String... props) throws IOException { + String outputPath = generateModels(codegen, "src/test/resources/3_0/generic.yaml", mutable); + assertFileContains(Paths.get(outputPath + "/src/main/kotlin/models/Animal.kt"), props); + } + + private String generateModels(AbstractKotlinCodegen codegen, String fileName, boolean mutable) 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/generic.yaml", null, new ParseOptions()).getOpenAPI(); + .readLocation(fileName, null, new ParseOptions()).getOpenAPI(); codegen.setOutputDir(output.getAbsolutePath()); codegen.additionalProperties().put(CodegenConstants.MODEL_PACKAGE, "models"); @@ -77,6 +82,34 @@ public class KotlinModelCodegenTest { generator.opts(input).generate(); - assertFileContains(Paths.get(outputPath + "/src/main/kotlin/models/Animal.kt"), props); + return outputPath; + } + + @Test(dataProvider = "generators") + public void valuesArrayWithUniqueItems(AbstractKotlinCodegen codegen) throws IOException { + String outputPath = generateModels(codegen, "src/test/resources/3_0/issue_9848.yaml", false); + + assertFileContains(Paths.get(outputPath + "/src/main/kotlin/models/NonUniqueArray.kt"), + codegen instanceof KotlinVertxServerCodegen || codegen instanceof KotlinServerDeprecatedCodegen + ? "val array: kotlin.Array" + : "val array: kotlin.collections.List" + ); + + assertFileContains(Paths.get(outputPath + "/src/main/kotlin/models/UniqueArray.kt"), + "val array: kotlin.collections.Set"); + } + + @Test(dataProvider = "generators") + public void mutableArrayWithUniqueItems(AbstractKotlinCodegen codegen) throws IOException { + String outputPath = generateModels(codegen, "src/test/resources/3_0/issue_9848.yaml", true); + + assertFileContains(Paths.get(outputPath + "/src/main/kotlin/models/NonUniqueArray.kt"), + codegen instanceof KotlinVertxServerCodegen || codegen instanceof KotlinServerDeprecatedCodegen + ? "var array: kotlin.Array" + : "var array: kotlin.collections.List" + ); + + assertFileContains(Paths.get(outputPath + "/src/main/kotlin/models/UniqueArray.kt"), + "var array: kotlin.collections.Set"); } } diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/kotlin/KotlinReservedWordsTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/kotlin/KotlinReservedWordsTest.java index 58727aa3803..914ed814da8 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/kotlin/KotlinReservedWordsTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/kotlin/KotlinReservedWordsTest.java @@ -48,7 +48,10 @@ public class KotlinReservedWordsTest { {"val"}, {"var"}, {"when"}, - {"while"} + {"while"}, + {"open"}, + {"external"}, + {"internal"} }; } diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/Swift5OptionsProvider.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/Swift5OptionsProvider.java index 9e2a4a3b36f..fa562df6d7f 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/Swift5OptionsProvider.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/Swift5OptionsProvider.java @@ -47,6 +47,8 @@ public class Swift5OptionsProvider implements OptionsProvider { public static final String READONLY_PROPERTIES_VALUE = "false"; public static final String SWIFT_USE_API_NAMESPACE_VALUE = "swiftUseApiNamespace"; public static final String USE_BACKTICKS_ESCAPES_VALUE = "false"; + public static final String GENERATE_MODEL_ADDITIONAL_PROPERTIES_VALUE = "true"; + public static final String HASHABLE_MODELS_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 LIBRARY_VALUE = "alamofire"; @@ -91,6 +93,10 @@ public class Swift5OptionsProvider implements OptionsProvider { .put(CodegenConstants.DISALLOW_ADDITIONAL_PROPERTIES_IF_NOT_PRESENT, "true") .put(Swift5ClientCodegen.USE_SPM_FILE_STRUCTURE, USE_SPM_FILE_STRUCTURE_VALUE) .put(Swift5ClientCodegen.SWIFT_PACKAGE_PATH, SWIFT_PACKAGE_PATH_VALUE) + .put(Swift5ClientCodegen.GENERATE_MODEL_ADDITIONAL_PROPERTIES, GENERATE_MODEL_ADDITIONAL_PROPERTIES_VALUE) + .put(Swift5ClientCodegen.HASHABLE_MODELS, HASHABLE_MODELS_VALUE) + .put(Swift5ClientCodegen.MAP_FILE_BINARY_TO_DATA, "false") + .put(Swift5ClientCodegen.USE_CLASSES, "false") .build(); } diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/TypeScriptAngularClientOptionsProvider.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/TypeScriptAngularClientOptionsProvider.java index eb8d90a468b..aa67286b978 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/TypeScriptAngularClientOptionsProvider.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/TypeScriptAngularClientOptionsProvider.java @@ -34,6 +34,7 @@ public class TypeScriptAngularClientOptionsProvider implements OptionsProvider { public static final String ENSURE_UNIQUE_PARAMS_VALUE = "true"; public static final String ENUM_PROPERTY_NAMING_VALUE = "PascalCase"; public static final String MODEL_PROPERTY_NAMING_VALUE = "camelCase"; + public static final String PARAM_NAMING_VALUE = "camelCase"; private static final String NPM_NAME = "npmName"; private static final String NPM_VERSION = "1.1.2"; private static final String NPM_REPOSITORY = "https://registry.npmjs.org"; @@ -63,6 +64,7 @@ public class TypeScriptAngularClientOptionsProvider implements OptionsProvider { .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE) .put(CodegenConstants.ENUM_PROPERTY_NAMING, ENUM_PROPERTY_NAMING_VALUE) .put(CodegenConstants.MODEL_PROPERTY_NAMING, MODEL_PROPERTY_NAMING_VALUE) + .put(CodegenConstants.PARAM_NAMING, PARAM_NAMING_VALUE) .put(CodegenConstants.SUPPORTS_ES6, SUPPORTS_ES6_VALUE) .put(AbstractTypeScriptClientCodegen.NULL_SAFE_ADDITIONAL_PROPS, NULL_SAFE_ADDITIONAL_PROPS_VALUE) .put(CodegenConstants.ENUM_NAME_SUFFIX, ENUM_NAME_SUFFIX) diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/TypeScriptAngularJsClientOptionsProvider.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/TypeScriptAngularJsClientOptionsProvider.java index 2c56e0c1268..1b9c8a58e17 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/TypeScriptAngularJsClientOptionsProvider.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/TypeScriptAngularJsClientOptionsProvider.java @@ -31,6 +31,7 @@ public class TypeScriptAngularJsClientOptionsProvider implements OptionsProvider public static final String SORT_MODEL_PROPERTIES_VALUE = "false"; public static final String ENSURE_UNIQUE_PARAMS_VALUE = "true"; public static final String MODEL_PROPERTY_NAMING_VALUE = "camelCase"; + public static final String PARAM_NAMING_VALUE = "camelCase"; public static final String ENUM_PROPERTY_NAMING_VALUE = "PascalCase"; public static final String ALLOW_UNICODE_IDENTIFIERS_VALUE = "false"; public static final String PREPEND_FORM_OR_BODY_PARAMETERS_VALUE = "true"; @@ -51,6 +52,7 @@ public class TypeScriptAngularJsClientOptionsProvider implements OptionsProvider .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE) .put(CodegenConstants.ENUM_PROPERTY_NAMING, ENUM_PROPERTY_NAMING_VALUE) .put(CodegenConstants.MODEL_PROPERTY_NAMING, MODEL_PROPERTY_NAMING_VALUE) + .put(CodegenConstants.PARAM_NAMING, PARAM_NAMING_VALUE) .put(CodegenConstants.ALLOW_UNICODE_IDENTIFIERS, ALLOW_UNICODE_IDENTIFIERS_VALUE) .put(CodegenConstants.PREPEND_FORM_OR_BODY_PARAMETERS, PREPEND_FORM_OR_BODY_PARAMETERS_VALUE) .put(CodegenConstants.LEGACY_DISCRIMINATOR_BEHAVIOR, "true") diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/TypeScriptAureliaClientOptionsProvider.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/TypeScriptAureliaClientOptionsProvider.java index cae9790d8da..939a0fad979 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/TypeScriptAureliaClientOptionsProvider.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/TypeScriptAureliaClientOptionsProvider.java @@ -33,6 +33,7 @@ public class TypeScriptAureliaClientOptionsProvider implements OptionsProvider { public static final String ENUM_NAME_SUFFIX = "Enum"; public static final String ENUM_PROPERTY_NAMING_VALUE = "PascalCase"; public static final String MODEL_PROPERTY_NAMING_VALUE = "camelCase"; + public static final String PARAM_NAMING_VALUE = "camelCase"; private static final String NPM_NAME = "npmName"; private static final String NPM_VERSION = "1.0.0"; public static final String ALLOW_UNICODE_IDENTIFIERS_VALUE = "false"; @@ -51,6 +52,7 @@ public class TypeScriptAureliaClientOptionsProvider implements OptionsProvider { .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE) .put(CodegenConstants.ENUM_PROPERTY_NAMING, ENUM_PROPERTY_NAMING_VALUE) .put(CodegenConstants.MODEL_PROPERTY_NAMING, MODEL_PROPERTY_NAMING_VALUE) + .put(CodegenConstants.PARAM_NAMING, PARAM_NAMING_VALUE) .put(CodegenConstants.SUPPORTS_ES6, String.valueOf(SUPPORTS_ES6_VALUE)) .put(AbstractTypeScriptClientCodegen.NULL_SAFE_ADDITIONAL_PROPS, String.valueOf(NULL_SAFE_ADDITIONAL_PROPS_VALUE)) .put(CodegenConstants.ENUM_NAME_SUFFIX, ENUM_NAME_SUFFIX) diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/TypeScriptFetchClientOptionsProvider.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/TypeScriptFetchClientOptionsProvider.java index be8e06e79fe..f33f1c437d6 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/TypeScriptFetchClientOptionsProvider.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/TypeScriptFetchClientOptionsProvider.java @@ -32,6 +32,7 @@ public class TypeScriptFetchClientOptionsProvider implements OptionsProvider { public static final Boolean NULL_SAFE_ADDITIONAL_PROPS_VALUE = false; public static final String ENUM_NAME_SUFFIX = "Enum"; public static final String MODEL_PROPERTY_NAMING_VALUE = "camelCase"; + public static final String PARAM_NAMING_VALUE = "camelCase"; public static final String ENUM_PROPERTY_NAMING_VALUE = "PascalCase"; private static final String NMP_NAME = "npmName"; private static final String NMP_VERSION = "1.0.0"; @@ -40,6 +41,7 @@ public class TypeScriptFetchClientOptionsProvider implements OptionsProvider { public static final String PREPEND_FORM_OR_BODY_PARAMETERS_VALUE = "true"; public static final String TYPESCRIPT_THREE_PLUS = "true"; public static final String WITHOUT_RUNTIME_CHECKS = "true"; + public static final String SAGAS_AND_RECORDS = "false"; @Override public String getLanguage() { @@ -54,6 +56,7 @@ public class TypeScriptFetchClientOptionsProvider implements OptionsProvider { .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE) .put(CodegenConstants.ENUM_PROPERTY_NAMING, ENUM_PROPERTY_NAMING_VALUE) .put(CodegenConstants.MODEL_PROPERTY_NAMING, MODEL_PROPERTY_NAMING_VALUE) + .put(CodegenConstants.PARAM_NAMING, PARAM_NAMING_VALUE) .put(CodegenConstants.SUPPORTS_ES6, String.valueOf(SUPPORTS_ES6_VALUE)) .put(AbstractTypeScriptClientCodegen.NULL_SAFE_ADDITIONAL_PROPS, String.valueOf(NULL_SAFE_ADDITIONAL_PROPS_VALUE)) .put(CodegenConstants.ENUM_NAME_SUFFIX, ENUM_NAME_SUFFIX) @@ -66,6 +69,7 @@ public class TypeScriptFetchClientOptionsProvider implements OptionsProvider { .put(TypeScriptFetchClientCodegen.PREFIX_PARAMETER_INTERFACES, Boolean.FALSE.toString()) .put(TypeScriptFetchClientCodegen.TYPESCRIPT_THREE_PLUS, TYPESCRIPT_THREE_PLUS) .put(TypeScriptFetchClientCodegen.WITHOUT_RUNTIME_CHECKS, WITHOUT_RUNTIME_CHECKS) + .put(TypeScriptFetchClientCodegen.SAGAS_AND_RECORDS, SAGAS_AND_RECORDS) .put(CodegenConstants.ALLOW_UNICODE_IDENTIFIERS, ALLOW_UNICODE_IDENTIFIERS_VALUE) .put(CodegenConstants.PREPEND_FORM_OR_BODY_PARAMETERS, PREPEND_FORM_OR_BODY_PARAMETERS_VALUE) .put(CodegenConstants.LEGACY_DISCRIMINATOR_BEHAVIOR, "true") diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/TypeScriptNestjsClientOptionsProvider.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/TypeScriptNestjsClientOptionsProvider.java index ee49aa17dd8..d86f586e15c 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/TypeScriptNestjsClientOptionsProvider.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/TypeScriptNestjsClientOptionsProvider.java @@ -33,6 +33,7 @@ public class TypeScriptNestjsClientOptionsProvider implements OptionsProvider { public static final String ENSURE_UNIQUE_PARAMS_VALUE = "true"; public static final String ENUM_PROPERTY_NAMING_VALUE = "PascalCase"; public static final String MODEL_PROPERTY_NAMING_VALUE = "camelCase"; + public static final String PARAM_NAMING_VALUE = "camelCase"; private static final String NMP_NAME = "npmName"; private static final String NMP_VERSION = "1.1.2"; private static final String NPM_REPOSITORY = "https://registry.npmjs.org"; @@ -59,6 +60,7 @@ public class TypeScriptNestjsClientOptionsProvider implements OptionsProvider { .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE) .put(CodegenConstants.ENUM_PROPERTY_NAMING, ENUM_PROPERTY_NAMING_VALUE) .put(CodegenConstants.MODEL_PROPERTY_NAMING, MODEL_PROPERTY_NAMING_VALUE) + .put(CodegenConstants.PARAM_NAMING, PARAM_NAMING_VALUE) .put(CodegenConstants.SUPPORTS_ES6, SUPPORTS_ES6_VALUE) .put(AbstractTypeScriptClientCodegen.NULL_SAFE_ADDITIONAL_PROPS, NULL_SAFE_ADDITIONAL_PROPS_VALUE) .put(CodegenConstants.ENUM_NAME_SUFFIX, ENUM_NAME_SUFFIX) diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/TypeScriptNodeClientOptionsProvider.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/TypeScriptNodeClientOptionsProvider.java index 0600f14838c..fb2b6a741dc 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/TypeScriptNodeClientOptionsProvider.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/TypeScriptNodeClientOptionsProvider.java @@ -33,6 +33,7 @@ public class TypeScriptNodeClientOptionsProvider implements OptionsProvider { public static final String SORT_MODEL_PROPERTIES_VALUE = "false"; public static final String ENSURE_UNIQUE_PARAMS_VALUE = "true"; public static final String MODEL_PROPERTY_NAMING_VALUE = "camelCase"; + public static final String PARAM_NAMING_VALUE = "camelCase"; public static final String ENUM_PROPERTY_NAMING_VALUE = "PascalCase"; public static final String NMP_NAME = "npmName"; public static final String NMP_VERSION = "1.1.2"; @@ -57,6 +58,7 @@ public class TypeScriptNodeClientOptionsProvider implements OptionsProvider { .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE) .put(CodegenConstants.ENUM_PROPERTY_NAMING, ENUM_PROPERTY_NAMING_VALUE) .put(CodegenConstants.MODEL_PROPERTY_NAMING, MODEL_PROPERTY_NAMING_VALUE) + .put(CodegenConstants.PARAM_NAMING, PARAM_NAMING_VALUE) .put(TypeScriptAngularClientCodegen.NPM_NAME, NMP_NAME) .put(TypeScriptAngularClientCodegen.NPM_VERSION, NMP_VERSION) .put(TypeScriptAngularClientCodegen.SNAPSHOT, Boolean.FALSE.toString()) diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/python/AbstractPythonConnexionServerCodegenTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/python/AbstractPythonConnexionServerCodegenTest.java new file mode 100644 index 00000000000..0e1e46c347f --- /dev/null +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/python/AbstractPythonConnexionServerCodegenTest.java @@ -0,0 +1,114 @@ +package org.openapitools.codegen.python; + +import static org.openapitools.codegen.languages.AbstractPythonConnexionServerCodegen.PYTHON_SRC_ROOT; +import static org.openapitools.codegen.languages.AbstractPythonConnexionServerCodegen.USE_PYTHON_SRC_ROOT_IN_IMPORTS; + +import java.io.File; +import java.util.Collections; +import java.util.Map; +import java.util.Objects; + +import com.google.common.collect.ImmutableMap; +import org.apache.commons.lang3.ObjectUtils; +import org.apache.commons.lang3.StringUtils; +import org.openapitools.codegen.CodegenConstants; +import org.openapitools.codegen.languages.AbstractPythonConnexionServerCodegen; +import org.testng.Assert; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; + +public class AbstractPythonConnexionServerCodegenTest { + + /** + * Passing "description" as first param to succinctly identify the significance of test parameters. + */ + @Test(dataProvider = "data") + public void test(String description, Map additionalProperties, String modelName, + ExpectedValues expectedValues) { + AbstractPythonConnexionServerCodegen codegen = new MockAbstractPythonConnexionServerCodegen("", false); + codegen.additionalProperties().putAll(additionalProperties); + codegen.processOpts(); + String pythonSrcRoot = Objects.toString(codegen.additionalProperties().get(PYTHON_SRC_ROOT), null); + Assert.assertEquals(pythonSrcRoot, expectedValues.pythonSrcRoot); + Assert.assertEquals(codegen.apiPackage(), expectedValues.expectedApiPackage); + Assert.assertEquals(codegen.modelFileFolder(), expectedValues.expectedModelFileFolder); + Assert.assertEquals(codegen.apiFileFolder(), expectedValues.expectedApiFileFolder); + Assert.assertEquals(codegen.toModelImport(modelName), expectedValues.expectedImport); + } + + @DataProvider + public Object[][] data() { + return new Object[][]{ + new Object[]{ + "Default setup", + Collections.emptyMap(), + "TestModel", + new ExpectedValues("from openapi_server.models.test_model import TestModel", + "openapi_server.controllers", + platformAgnosticPath("generated-code", "connexion", "openapi_server", "models"), + platformAgnosticPath("generated-code", "connexion", "openapi_server", "controllers"), + null) + }, + new Object[]{ + "Default setup with Python src root", + ImmutableMap.of(PYTHON_SRC_ROOT, "test_root"), + "TestModel", + new ExpectedValues("from openapi_server.models.test_model import TestModel", + "openapi_server.controllers", + platformAgnosticPath("generated-code", "connexion", "test_root", "openapi_server", "models"), + platformAgnosticPath("generated-code", "connexion", "test_root", "openapi_server", "controllers"), + "test_root") + }, + new Object[]{ + "Python src in import", + ImmutableMap.of(PYTHON_SRC_ROOT, "test_root", USE_PYTHON_SRC_ROOT_IN_IMPORTS, "true"), + "TestModel", + new ExpectedValues("from test_root.openapi_server.models.test_model import TestModel", + "test_root.openapi_server.controllers", + platformAgnosticPath("generated-code", "connexion", "test_root", "openapi_server", "models"), + platformAgnosticPath("generated-code", "connexion", "test_root", "openapi_server", "controllers"), + null) + }, + new Object[]{ + "Python src in import with specified package", + ImmutableMap.of(PYTHON_SRC_ROOT, "test_root", + USE_PYTHON_SRC_ROOT_IN_IMPORTS, "true", + CodegenConstants.PACKAGE_NAME, "test_package"), + "TestModel", + new ExpectedValues("from test_root.test_package.models.test_model import TestModel", + "test_root.test_package.controllers", + platformAgnosticPath("generated-code", "connexion", "test_root", "test_package", "models"), + platformAgnosticPath("generated-code", "connexion", "test_root", "test_package", "controllers"), + null) + } + }; + } + + private static String platformAgnosticPath(String... nodes) { + return StringUtils.join(nodes, File.separatorChar); + } + + private static class MockAbstractPythonConnexionServerCodegen extends AbstractPythonConnexionServerCodegen { + public MockAbstractPythonConnexionServerCodegen(String templateDirectory, boolean fixBodyNameValue) { + super(templateDirectory, fixBodyNameValue); + } + } + + private static class ExpectedValues { + public final String expectedImport; + public final String expectedApiPackage; + public final String expectedModelFileFolder; + public final String expectedApiFileFolder; + public final String pythonSrcRoot; + + public ExpectedValues(String expectedImport, String expectedApiPackage, String expectedModelFileFolder, + String expectedApiFileFolder, String pythonSrcRoot) { + this.expectedImport = expectedImport; + this.expectedApiPackage = expectedApiPackage; + this.expectedModelFileFolder = expectedModelFileFolder; + this.expectedApiFileFolder = expectedApiFileFolder; + this.pythonSrcRoot = pythonSrcRoot != null ? pythonSrcRoot + File.separatorChar : null; + } + } + +} diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/swift5/Swift5OptionsTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/swift5/Swift5OptionsTest.java index 65e97494cfa..268d52bed28 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/swift5/Swift5OptionsTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/swift5/Swift5OptionsTest.java @@ -48,5 +48,7 @@ public class Swift5OptionsTest extends AbstractOptionsTest { verify(clientCodegen).setLenientTypeCast(Boolean.parseBoolean(Swift5OptionsProvider.LENIENT_TYPE_CAST_VALUE)); verify(clientCodegen).setPrependFormOrBodyParameters(Boolean.valueOf(Swift5OptionsProvider.PREPEND_FORM_OR_BODY_PARAMETERS_VALUE)); verify(clientCodegen).setReadonlyProperties(Boolean.parseBoolean(Swift5OptionsProvider.READONLY_PROPERTIES_VALUE)); + verify(clientCodegen).setGenerateModelAdditionalProperties(Boolean.parseBoolean(Swift5OptionsProvider.GENERATE_MODEL_ADDITIONAL_PROPERTIES_VALUE)); + verify(clientCodegen).setHashableModels(Boolean.parseBoolean(Swift5OptionsProvider.HASHABLE_MODELS_VALUE)); } } diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/SharedTypeScriptTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/SharedTypeScriptTest.java index 9062d738689..f4e024142a5 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/SharedTypeScriptTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/SharedTypeScriptTest.java @@ -12,6 +12,8 @@ import org.testng.annotations.Test; import java.io.File; import java.io.IOException; import java.util.List; +import java.util.Map; +import java.util.HashMap; public class SharedTypeScriptTest { @Test @@ -69,4 +71,25 @@ public class SharedTypeScriptTest { FileUtils.deleteDirectory(new File("src/test/resources/oldImportsStillPresentTest/")); } + + /* + #8000 + Test that primatives are not returned by toModelImportMap + */ + @Test + public void toModelImportMapTest() { + TypeScriptAxiosClientCodegen codegen = new TypeScriptAxiosClientCodegen(); + + Map types = new HashMap() {{ + put("Schema & AnotherSchema", new String[]{ "Schema", "AnotherSchema" }); + put("Schema | AnotherSchema", new String[]{ "Schema", "AnotherSchema" }); + put("Schema & object", new String[]{ "Schema" }); + put("Schema | object", new String[]{ "Schema" }); + }}; + + for (Map.Entry entry : types.entrySet()) { + String[] mapped = codegen.toModelImportMap(entry.getKey()).values().toArray(new String[0]); + Assert.assertEquals(mapped, entry.getValue()); + } + } } \ No newline at end of file diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/TypeScriptClientModelTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/TypeScriptClientModelTest.java new file mode 100644 index 00000000000..5a8333b5e5e --- /dev/null +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/TypeScriptClientModelTest.java @@ -0,0 +1,57 @@ +package org.openapitools.codegen.typescript; + +import io.swagger.v3.oas.models.OpenAPI; +import io.swagger.v3.oas.models.media.*; +import org.openapitools.codegen.CodegenModel; +import org.openapitools.codegen.DefaultCodegen; +import org.openapitools.codegen.TestUtils; +import org.openapitools.codegen.languages.TypeScriptClientCodegen; +import org.openapitools.codegen.utils.ModelUtils; +import org.testng.Assert; +import org.testng.annotations.Test; + + +public class TypeScriptClientModelTest { + + @Test(description = "convert an array oneof model") + public void arrayOneOfModelTest() { + final Schema schema = new ArraySchema() + .items(new ComposedSchema() + .addOneOfItem(new StringSchema()) + .addOneOfItem(new IntegerSchema().format("int64"))) + .description("an array oneof model"); + final DefaultCodegen codegen = new TypeScriptClientCodegen(); + OpenAPI openAPI = TestUtils.createOpenAPIWithOneSchema("sample", schema); + codegen.setOpenAPI(openAPI); + final CodegenModel cm = codegen.fromModel("sample", schema); + + + Assert.assertEquals(cm.name, "sample"); + Assert.assertEquals(cm.classname, "Sample"); + Assert.assertEquals(cm.description, "an array oneof model"); + Assert.assertEquals(cm.arrayModelType, "string | number"); + Assert.assertEquals(cm.vars.size(), 0); + } + + @Test(description = "convert an any of with array oneof model") + public void objectPropertyAnyOfWithArrayOneOfModelTest() { + final Schema schema = new ObjectSchema().addProperties("value", + new ComposedSchema().addAnyOfItem(new StringSchema()).addAnyOfItem(new ArraySchema() + .items(new ComposedSchema() + .addOneOfItem(new StringSchema()) + .addOneOfItem(new IntegerSchema().format("int64"))))) + .description("an any of with array oneof model"); + final DefaultCodegen codegen = new TypeScriptClientCodegen(); + OpenAPI openAPI = TestUtils.createOpenAPIWithOneSchema("sample", schema); + codegen.setOpenAPI(openAPI); + final CodegenModel cm = codegen.fromModel("sample", schema); + + String s = codegen.getSchemaType((Schema)schema.getProperties().get("value")); + + Assert.assertEquals(cm.name, "sample"); + Assert.assertEquals(cm.classname, "Sample"); + Assert.assertEquals(cm.description, "an any of with array oneof model"); + Assert.assertEquals(cm.vars.size(), 1); + Assert.assertEquals(s, "string | Array"); + } +} diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/aurelia/TypeScriptAureliaClientOptionsTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/aurelia/TypeScriptAureliaClientOptionsTest.java index c8e6a379abd..cd247de1190 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/aurelia/TypeScriptAureliaClientOptionsTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/aurelia/TypeScriptAureliaClientOptionsTest.java @@ -42,6 +42,7 @@ public class TypeScriptAureliaClientOptionsTest extends AbstractOptionsTest { protected void verifyOptions() { verify(clientCodegen).setSortParamsByRequiredFlag(Boolean.valueOf(TypeScriptAureliaClientOptionsProvider.SORT_PARAMS_VALUE)); verify(clientCodegen).setModelPropertyNaming(TypeScriptAureliaClientOptionsProvider.MODEL_PROPERTY_NAMING_VALUE); + verify(clientCodegen).setParamNaming(TypeScriptAureliaClientOptionsProvider.PARAM_NAMING_VALUE); verify(clientCodegen).setSupportsES6(TypeScriptAureliaClientOptionsProvider.SUPPORTS_ES6_VALUE); verify(clientCodegen).setPrependFormOrBodyParameters(Boolean.valueOf(TypeScriptAureliaClientOptionsProvider.PREPEND_FORM_OR_BODY_PARAMETERS_VALUE)); } diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/fetch/TypeScriptFetchClientOptionsTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/fetch/TypeScriptFetchClientOptionsTest.java index 6bc2631f6e6..7b29653b31a 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/fetch/TypeScriptFetchClientOptionsTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/fetch/TypeScriptFetchClientOptionsTest.java @@ -42,9 +42,11 @@ public class TypeScriptFetchClientOptionsTest extends AbstractOptionsTest { protected void verifyOptions() { verify(clientCodegen).setSortParamsByRequiredFlag(Boolean.valueOf(TypeScriptFetchClientOptionsProvider.SORT_PARAMS_VALUE)); verify(clientCodegen).setModelPropertyNaming(TypeScriptFetchClientOptionsProvider.MODEL_PROPERTY_NAMING_VALUE); + verify(clientCodegen).setParamNaming(TypeScriptFetchClientOptionsProvider.PARAM_NAMING_VALUE); verify(clientCodegen).setSupportsES6(TypeScriptFetchClientOptionsProvider.SUPPORTS_ES6_VALUE); verify(clientCodegen).setPrependFormOrBodyParameters(Boolean.valueOf(TypeScriptFetchClientOptionsProvider.PREPEND_FORM_OR_BODY_PARAMETERS_VALUE)); verify(clientCodegen).setTypescriptThreePlus(Boolean.valueOf(TypeScriptFetchClientOptionsProvider.TYPESCRIPT_THREE_PLUS)); verify(clientCodegen).setWithoutRuntimeChecks(Boolean.valueOf(TypeScriptFetchClientOptionsProvider.WITHOUT_RUNTIME_CHECKS)); + verify(clientCodegen).setSagasAndRecords(Boolean.valueOf(TypeScriptFetchClientOptionsProvider.SAGAS_AND_RECORDS)); } } diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/typescriptangular/TypeScriptAngularClientCodegenTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/typescriptangular/TypeScriptAngularClientCodegenTest.java index 059e5004ad4..07e2216710b 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/typescriptangular/TypeScriptAngularClientCodegenTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/typescriptangular/TypeScriptAngularClientCodegenTest.java @@ -231,4 +231,31 @@ public class TypeScriptAngularClientCodegenTest { Assert.assertEquals(codegen.toModelImport(modelName), "model/foo-response-links"); Assert.assertEquals(codegen.toModelFilename(modelName), "./foo-response-links"); } + + @Test + public void testToParamNaming() { + TypeScriptAngularClientCodegen codegen = new TypeScriptAngularClientCodegen(); + // unspecified option should default to camelcase + codegen.processOpts(); + Assert.assertEquals(codegen.toParamName("valid_id"), "validId"); + Assert.assertEquals(codegen.toParamName("illegal-id+"), "illegalId"); + + codegen = new TypeScriptAngularClientCodegen(); + codegen.additionalProperties().put(CodegenConstants.PARAM_NAMING, CodegenConstants.PARAM_NAMING_TYPE.original.name()); + codegen.processOpts(); + Assert.assertEquals(codegen.toParamName("valid_id"), "valid_id"); + Assert.assertEquals(codegen.toParamName("illegal-id+"), "illegal_id"); + + codegen = new TypeScriptAngularClientCodegen(); + codegen.additionalProperties().put(CodegenConstants.PARAM_NAMING, CodegenConstants.PARAM_NAMING_TYPE.snake_case.name()); + codegen.processOpts(); + Assert.assertEquals(codegen.toParamName("valid_ID"), "valid_id"); + Assert.assertEquals(codegen.toParamName("Illegal-Id+"), "illegal_id"); + + codegen = new TypeScriptAngularClientCodegen(); + codegen.additionalProperties().put(CodegenConstants.PARAM_NAMING, CodegenConstants.PARAM_NAMING_TYPE.PascalCase.name()); + codegen.processOpts(); + Assert.assertEquals(codegen.toParamName("valid_id"), "ValidId"); + Assert.assertEquals(codegen.toParamName("illegal-id+"), "IllegalId"); + } } diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/typescriptangular/TypeScriptAngularClientOptionsTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/typescriptangular/TypeScriptAngularClientOptionsTest.java index 9bc5eafb1bd..5359b81e6a5 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/typescriptangular/TypeScriptAngularClientOptionsTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/typescriptangular/TypeScriptAngularClientOptionsTest.java @@ -46,5 +46,6 @@ public class TypeScriptAngularClientOptionsTest extends AbstractOptionsTest { verify(clientCodegen).setStringEnums(Boolean.parseBoolean(TypeScriptAngularClientOptionsProvider.STRING_ENUMS_VALUE)); verify(clientCodegen).setPrependFormOrBodyParameters(Boolean.valueOf(TypeScriptAngularClientOptionsProvider.PREPEND_FORM_OR_BODY_PARAMETERS_VALUE)); verify(clientCodegen).setQueryParamObjectFormat(TypeScriptAngularClientOptionsProvider.QUERY_PARAM_OBJECT_FORMAT_VALUE); + verify(clientCodegen).setParamNaming(TypeScriptAngularClientOptionsProvider.PARAM_NAMING_VALUE); } } diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/typescriptangularjs/TypeScriptAngularJsClientOptionsTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/typescriptangularjs/TypeScriptAngularJsClientOptionsTest.java index f966d40b21c..54710992d91 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/typescriptangularjs/TypeScriptAngularJsClientOptionsTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/typescriptangularjs/TypeScriptAngularJsClientOptionsTest.java @@ -42,6 +42,7 @@ public class TypeScriptAngularJsClientOptionsTest extends AbstractOptionsTest { protected void verifyOptions() { verify(clientCodegen).setSortParamsByRequiredFlag(Boolean.valueOf(TypeScriptAngularJsClientOptionsProvider.SORT_PARAMS_VALUE)); verify(clientCodegen).setModelPropertyNaming(TypeScriptAngularJsClientOptionsProvider.MODEL_PROPERTY_NAMING_VALUE); + verify(clientCodegen).setParamNaming(TypeScriptAngularJsClientOptionsProvider.PARAM_NAMING_VALUE); verify(clientCodegen).setSupportsES6(Boolean.valueOf(TypeScriptAngularJsClientOptionsProvider.SUPPORTS_ES6_VALUE)); verify(clientCodegen).setPrependFormOrBodyParameters(Boolean.valueOf(TypeScriptAngularJsClientOptionsProvider.PREPEND_FORM_OR_BODY_PARAMETERS_VALUE)); } diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/typescriptnestjs/TypeScriptNestjsClientOptionsTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/typescriptnestjs/TypeScriptNestjsClientOptionsTest.java index a2d137537fb..5f2138a66c2 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/typescriptnestjs/TypeScriptNestjsClientOptionsTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/typescriptnestjs/TypeScriptNestjsClientOptionsTest.java @@ -42,6 +42,7 @@ public class TypeScriptNestjsClientOptionsTest extends AbstractOptionsTest { protected void verifyOptions() { verify(clientCodegen).setSortParamsByRequiredFlag(Boolean.valueOf(TypeScriptNestjsClientOptionsProvider.SORT_PARAMS_VALUE)); verify(clientCodegen).setModelPropertyNaming(TypeScriptNestjsClientOptionsProvider.MODEL_PROPERTY_NAMING_VALUE); + verify(clientCodegen).setParamNaming(TypeScriptNestjsClientOptionsProvider.PARAM_NAMING_VALUE); verify(clientCodegen).setSupportsES6(Boolean.valueOf(TypeScriptNestjsClientOptionsProvider.SUPPORTS_ES6_VALUE)); verify(clientCodegen).setStringEnums(Boolean.parseBoolean(TypeScriptNestjsClientOptionsProvider.STRING_ENUMS_VALUE)); verify(clientCodegen).setPrependFormOrBodyParameters(Boolean.valueOf(TypeScriptNestjsClientOptionsProvider.PREPEND_FORM_OR_BODY_PARAMETERS_VALUE)); diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/typescriptnode/TypeScriptNodeClientOptionsTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/typescriptnode/TypeScriptNodeClientOptionsTest.java index bf7e0509925..414c63dd279 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/typescriptnode/TypeScriptNodeClientOptionsTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/typescriptnode/TypeScriptNodeClientOptionsTest.java @@ -42,6 +42,7 @@ public class TypeScriptNodeClientOptionsTest extends AbstractOptionsTest { protected void verifyOptions() { verify(clientCodegen).setSortParamsByRequiredFlag(Boolean.valueOf(TypeScriptNodeClientOptionsProvider.SORT_PARAMS_VALUE)); verify(clientCodegen).setModelPropertyNaming(TypeScriptNodeClientOptionsProvider.MODEL_PROPERTY_NAMING_VALUE); + verify(clientCodegen).setParamNaming(TypeScriptNodeClientOptionsProvider.PARAM_NAMING_VALUE); verify(clientCodegen).setSupportsES6(Boolean.valueOf(TypeScriptNodeClientOptionsProvider.SUPPORTS_ES6_VALUE)); verify(clientCodegen).setPrependFormOrBodyParameters(Boolean.valueOf(TypeScriptNodeClientOptionsProvider.PREPEND_FORM_OR_BODY_PARAMETERS_VALUE)); } diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/wsdl/WsdlSchemaCodegenTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/wsdl/WsdlSchemaCodegenTest.java new file mode 100644 index 00000000000..6cb452dae1c --- /dev/null +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/wsdl/WsdlSchemaCodegenTest.java @@ -0,0 +1,266 @@ +package org.openapitools.codegen.wsdl; + +import io.swagger.v3.oas.models.OpenAPI; +import io.swagger.v3.oas.models.Operation; +import org.apache.commons.io.FileUtils; +import org.openapitools.codegen.ClientOptInput; +import org.openapitools.codegen.CodegenOperation; +import org.openapitools.codegen.DefaultGenerator; +import org.openapitools.codegen.TestUtils; +import org.openapitools.codegen.languages.WsdlSchemaCodegen; +import org.testng.Assert; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.List; + +import static org.openapitools.codegen.TestUtils.assertFileContains; +import static org.openapitools.codegen.TestUtils.ensureContainsFile; + +public class WsdlSchemaCodegenTest { + private OpenAPI openAPI; + private File outputDirectory; + private String outputPath; + private List listOfFiles; + + @BeforeClass + public void setUp() throws IOException { + this.openAPI = TestUtils.parseFlattenSpec("src/test/resources/3_0/wsdl/petstore.yaml"); + this.outputDirectory = Files.createTempDirectory("test").toFile().getCanonicalFile(); + this.outputPath = this.outputDirectory.getAbsolutePath().replace('\\', '/'); + + WsdlSchemaCodegen codegen = new WsdlSchemaCodegen(); + codegen.setOutputDir(this.outputDirectory.getAbsolutePath()); + + ClientOptInput input = new ClientOptInput() + .openAPI(this.openAPI) + .config(codegen); + + DefaultGenerator generator = new DefaultGenerator(); + this.listOfFiles = generator.opts(input).generate(); + } + + @Test(description = "ensure that the operationid has been generated correctly") + public void testOperationIdGeneration() { + final OpenAPI openAPI = this.openAPI; + WsdlSchemaCodegen codegen = new WsdlSchemaCodegen(); + codegen.setOpenAPI(openAPI); + + String requestPathWithId = "/store/order/{orderId}"; + Operation textOperationGet = openAPI.getPaths().get(requestPathWithId).getGet(); + CodegenOperation opGet = codegen.fromOperation(requestPathWithId, "get", textOperationGet, null); + String newOperationIdWithId = codegen.generateOperationId(opGet); + + String requestPathWithoutId = "/store/order"; + Operation textOperationPost = openAPI.getPaths().get(requestPathWithoutId).getPost(); + CodegenOperation opPost = codegen.fromOperation(requestPathWithoutId, "post", textOperationPost, null); + String newOperationIdWithoutId = codegen.generateOperationId(opPost); + + Assert.assertEquals(newOperationIdWithId, "GetStoreOrderByOrderid"); + Assert.assertEquals(newOperationIdWithoutId, "PostStoreOrder"); + } + + @Test(description = "Ensure that passed strings are processed correcly by this method") + public void testLowerCaseStringExceptFirstLetter() { + WsdlSchemaCodegen codegen = new WsdlSchemaCodegen(); + String value = codegen.lowerCaseStringExceptFirstLetter("uploadPetByPathId"); + + Assert.assertEquals(value, "Uploadpetbypathid"); + } + + @Test(description = "Check if element tags has been created for an operation ") + public void testIfElementTagsExist() { + String xsElementRequestMessage = + ""; + String xsElementResponseMessage = + ""; + String xsElementErrorResponse = + " \n" + + " \n" + + " Invalid input\n" + + " \n" + + " \n"; + + assertFileContains(Paths.get(this.outputPath + "/service.wsdl"), xsElementRequestMessage); + assertFileContains(Paths.get(this.outputPath + "/service.wsdl"), xsElementResponseMessage); + assertFileContains(Paths.get(this.outputPath + "/service.wsdl"), xsElementErrorResponse); + } + + @Test(description = "Check if complexType input- and output-message has been created for an operation ") + public void testIfInputAndResponseMessageExist() { + String complexTypeRequestMessage = + " \n" + + " \n" + + " \n" + + " \n" + + " ID of pet to return\n" + + " \n" + + " \n" + + " \n" + + " \n"; + + String complexTypeResponseMessage = + " \n" + + " \n" + + " \n" + + " \n" + + " successful operation\n" + + " \n" + + " \n" + + " \n" + + " \n"; + + assertFileContains(Paths.get(this.outputPath + "/service.wsdl"), complexTypeRequestMessage); + assertFileContains(Paths.get(this.outputPath + "/service.wsdl"), complexTypeResponseMessage); + } + + @Test(description = + "Check if complexType RequestMessage with minimum and maximum restriction has been created for an operation ") + public void testIfRequestMessageMinimumExists() { + String complexTypeRequestMessageMinimum = + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " ID of pet that needs to be fetched\n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n"; + + assertFileContains(Paths.get(this.outputPath + "/service.wsdl"), complexTypeRequestMessageMinimum); + } + + @Test(description = "Check if complexType model has been created for an openapi model schema") + public void testIfComplexTypeModelExists() { + String complexTypeModel = + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " pet status in the store\n" + + " \n" + + " \n" + + " \n" + + " \n"; + + assertFileContains(Paths.get(this.outputPath + "/service.wsdl"), complexTypeModel); + } + + @Test(description = "Check if message and part tags has been created for an operation ") + public void testIfMessageTagsAndContentExist() { + String messageRequestMessage = + " \n" + + " \n" + + " "; + + String messageError = + " \n" + + " \n" + + " \n"; + + assertFileContains(Paths.get(this.outputPath + "/service.wsdl"), messageRequestMessage); + assertFileContains(Paths.get(this.outputPath + "/service.wsdl"), messageError); + } + + @Test(description = "Check if portType tag and portType operation has been generated") + public void testIfPorttypeOperationExists() { + String portType = ""; + + String portTypeOperation = + " \n" + + " Returns a single pet\n" + + " \n" + + " \n" + + " successful operation\n" + + " \n" + + " \n" + + " Invalid ID supplied\n" + + " \n" + + " \n" + + " Pet not found\n" + + " \n" + + " \n"; + + assertFileContains(Paths.get(this.outputPath + "/service.wsdl"), portType); + assertFileContains(Paths.get(this.outputPath + "/service.wsdl"), portTypeOperation); + } + + @Test(description = "Check if portType tag and portType operation has been generated") + public void testIfBindingOperationExists() { + String binding = ""; + + String bindingOperation = + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n"; + + assertFileContains(Paths.get(this.outputPath + "/service.wsdl"), binding); + assertFileContains(Paths.get(this.outputPath + "/service.wsdl"), bindingOperation); + } + + @Test(description = "Ensure that all files have been correctly generated") + public void testFileGeneration() throws Exception { + Assert.assertEquals(this.listOfFiles.size(), 5); + ensureContainsFile(this.listOfFiles, this.outputDirectory, ".openapi-generator-ignore"); + ensureContainsFile(this.listOfFiles, this.outputDirectory, ".openapi-generator/FILES"); + ensureContainsFile(this.listOfFiles, this.outputDirectory, ".openapi-generator/VERSION"); + ensureContainsFile(this.listOfFiles, this.outputDirectory, "service.wsdl"); + ensureContainsFile(this.listOfFiles, this.outputDirectory, "jaxb-customization.xml"); + } + + @Test(description = "Ensure that default description is set if it doesn't exist") + public void testOpenapiDescriptionWasNotProvided() throws IOException { + final OpenAPI openAPI = TestUtils.parseFlattenSpec("src/test/resources/3_0/ping.yaml"); + File outputDirectory = Files.createTempDirectory("test").toFile().getCanonicalFile(); + String outputPath = this.outputDirectory.getAbsolutePath().replace('\\', '/'); + + WsdlSchemaCodegen codegen = new WsdlSchemaCodegen(); + codegen.setOutputDir(this.outputDirectory.getAbsolutePath()); + + ClientOptInput input = new ClientOptInput().openAPI(openAPI).config(codegen); + + DefaultGenerator generator = new DefaultGenerator(); + generator.opts(input).generate(); + + String value = "No description provided"; + assertFileContains(Paths.get(outputPath + "/service.wsdl"), value); + + FileUtils.deleteDirectory(outputDirectory); + } + + + @AfterClass + public void cleanUp() throws Exception { + // Delete temp folder + FileUtils.deleteDirectory(this.outputDirectory); + } +} diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/yaml/YamlGeneratorTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/yaml/YamlGeneratorTest.java index c264a8a251c..cc4e74ade5d 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/yaml/YamlGeneratorTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/yaml/YamlGeneratorTest.java @@ -17,6 +17,7 @@ package org.openapitools.codegen.yaml; +import io.swagger.v3.oas.models.OpenAPI; import org.openapitools.codegen.ClientOptInput; import org.openapitools.codegen.DefaultGenerator; import org.openapitools.codegen.TestUtils; @@ -85,4 +86,36 @@ public class YamlGeneratorTest { output.deleteOnExit(); } + + @Test + public void testIssue9086() throws Exception { + Map properties = new HashMap<>(); + properties.put(OpenAPIYamlGenerator.OUTPUT_NAME, "issue_9086.yaml"); + + File output = Files.createTempDirectory("issue_9086").toFile(); + output.deleteOnExit(); + + final CodegenConfigurator configurator = new CodegenConfigurator() + .setGeneratorName("openapi-yaml") + .setAdditionalProperties(properties) + .setInputSpec("src/test/resources/2_0/issue_9086.yaml") + .setOutputDir(output.getAbsolutePath().replace("\\", "/")); + + final ClientOptInput clientOptInput = configurator.toClientOptInput(); + DefaultGenerator generator = new DefaultGenerator(); + List files = generator.opts(clientOptInput).generate(); + Assert.assertEquals(files.size(), 5); + TestUtils.ensureContainsFile(files, output, "issue_9086.yaml"); + + TestUtils.ensureContainsFile(files, output, "README.md"); + TestUtils.ensureContainsFile(files, output, ".openapi-generator-ignore"); + TestUtils.ensureContainsFile(files, output, ".openapi-generator/FILES"); + TestUtils.ensureContainsFile(files, output, ".openapi-generator/VERSION"); + + OpenAPI generated = TestUtils.parseSpec(new File(output, "issue_9086.yaml").getPath()); + OpenAPI expected = TestUtils.parseSpec("src/test/resources/2_0/issue_9086_expected.yaml"); + + // use #toString because the equals methods is a little stricter than necessary for this test + Assert.assertEquals(expected.toString(), generated.toString()); + } } diff --git a/modules/openapi-generator/src/test/resources/2_0/issue_9086.yaml b/modules/openapi-generator/src/test/resources/2_0/issue_9086.yaml new file mode 100644 index 00000000000..3210031ade3 --- /dev/null +++ b/modules/openapi-generator/src/test/resources/2_0/issue_9086.yaml @@ -0,0 +1,34 @@ +swagger: '2.0' +info: + title: 'Buggy Api' + version: '1.0' +consumes: + - application/json +paths: + /foo/bar: + post: + responses: + '200': + description: ok + schema: + type: object + additionalProperties: false + properties: + n: + type: number + example: 1.23 + /foo/bar2: + post: + responses: + '200': + description: ok + schema: + $ref: '#/definitions/bar2' +definitions: + bar2: + type: object + additionalProperties: false + properties: + n: + type: number + example: 4.56 diff --git a/modules/openapi-generator/src/test/resources/2_0/issue_9086_expected.yaml b/modules/openapi-generator/src/test/resources/2_0/issue_9086_expected.yaml new file mode 100644 index 00000000000..cce682ee053 --- /dev/null +++ b/modules/openapi-generator/src/test/resources/2_0/issue_9086_expected.yaml @@ -0,0 +1,40 @@ +openapi: 3.0.1 +info: + title: 'Buggy Api' + version: '1.0' +paths: + /foo/bar: + post: + responses: + '200': + description: ok + content: + '*/*': + schema: + $ref: '#/components/schemas/inline_response_200' + + /foo/bar2: + post: + responses: + '200': + description: ok + content: + '*/*': + schema: + $ref: '#/components/schemas/bar2' +components: + schemas: + bar2: + type: object + example: { n: 4.56 } + properties: + n: + type: number + example: 4.56 + inline_response_200: + type: object + example: { n: 1.23 } + properties: + n: + type: number + example: 1.23 diff --git a/modules/openapi-generator/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing-saga-and-records.yaml b/modules/openapi-generator/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing-saga-and-records.yaml new file mode 100644 index 00000000000..81124e9578e --- /dev/null +++ b/modules/openapi-generator/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing-saga-and-records.yaml @@ -0,0 +1,1175 @@ +swagger: '2.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.' + version: 1.0.0 + title: OpenAPI Petstore + license: + name: Apache-2.0 + url: 'https://www.apache.org/licenses/LICENSE-2.0.html' +host: petstore.swagger.io +basePath: /v2 +tags: + - name: pet + description: Everything about your Pets + - name: store + description: Access to Petstore orders + - name: user + description: Operations about user +schemes: + - http +parameters: + fake_petPart-id: + in: path + name: fake_petPart-id + required: true + type: integer + format: int64 +paths: + /fake_behavior/{behavior-id}/type: + get: + tags: + - Behavior + summary: Get the type of behavior + operationId: getBehaviorType + parameters: + - in: path + name: behavior-id + required: true + type: integer + format: int64 + responses: + 200: + description: OK + schema: + $ref: "#/definitions/GetBehaviorTypeResponse" + /fake_behavior/{behavior-id}/permissions: + get: + tags: + - Behavior + summary: Get permissions for the behavior + operationId: getBehaviorPermissions + parameters: + - in: path + name: behavior-id + required: true + type: integer + format: int64 + responses: + 200: + description: OK + schema: + $ref: "#/definitions/GetBehaviorPermissionsResponse" + + /fake_petParts/{fake_petPart-id}/part-type: + get: + tags: + - PetPart + summary: Returns single pet part type for the petPart id. + operationId: getFakePetPartType + parameters: + - $ref: "#/definitions/fake_petPart-id" + responses: + 200: + description: OK + schema: + $ref: "#/definitions/GetPetPartTypeResponse" + /fake_petParts/{fake_petPart-id}/matching-parts: + get: + tags: + - PetPart + summary: Get the matching parts for the given pet part. + operationId: getMatchingParts + parameters: + - $ref: "#/parameters/fake_petPart-id" + - in: query + name: long + required: true + type: boolean + - in: query + name: smooth + required: true + type: boolean + - in: query + name: name + required: false + type: string + - in: query + name: connected-part + required: false + type: string + - in: query + name: short + required: true + type: boolean + responses: + 200: + description: OK + schema: + $ref: "#/definitions/GetMatchingPartsResponse" + /pet: + post: + tags: + - pet + summary: Add a new pet to the store + description: '' + operationId: addPet + consumes: + - application/json + - application/xml + produces: + - application/xml + - application/json + parameters: + - in: body + name: dummyCat + description: dummy category for testing + required: true + schema: + $ref: "#/definitions/Category" + responses: + '405': + description: Invalid input + security: + - petstore_auth: + - 'write:pets' + - 'read:pets' + put: + tags: + - pet + summary: Update an existing pet + description: '' + operationId: updatePet + consumes: + - application/json + - application/xml + produces: + - application/xml + - application/json + parameters: + - in: body + name: body + description: Pet object that needs to be updated in the store + required: true + schema: + $ref: '#/definitions/Pet' + responses: + '400': + description: Invalid ID supplied + '404': + description: Pet not found + '405': + description: Validation exception + security: + - petstore_auth: + - 'write:pets' + - 'read:pets' + /pet/findByStatus: + get: + tags: + - pet + summary: Finds Pets by status + description: Multiple status values can be provided with comma separated strings + operationId: findPetsByStatus + produces: + - application/xml + - application/json + parameters: + - name: status + in: query + description: Status values that need to be considered for filter + required: true + type: array + items: + type: string + enum: + - available + - pending + - sold + default: available + collectionFormat: csv + responses: + '200': + description: successful operation + schema: + $ref: "#/definitions/FindPetsByStatusResponse" + '400': + description: Invalid status value + security: + - petstore_auth: + - 'write:pets' + - 'read:pets' + /pet/findByUserIds: + get: + tags: + - pet + summary: Finds Pets by user ids + description: 'Multiple ids can be provided with comma separated strings.' + operationId: findPetsByUserIds + produces: + - application/xml + - application/json + parameters: + - name: ids + in: query + description: Ids to filter by + required: true + type: array + items: + type: number + collectionFormat: csv + responses: + '200': + description: successful operation + schema: + $ref: "#/definitions/FindPetsByUserResponse" + '400': + description: Invalid status value + security: + - petstore_auth: + - 'write:pets' + - 'read:pets' + deprecated: true + /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 + produces: + - application/xml + - application/json + parameters: + - name: tags + in: query + description: Tags to filter by + required: true + type: array + items: + type: string + collectionFormat: csv + responses: + '200': + description: successful operation + schema: + type: array + items: + $ref: '#/definitions/Pet' + '400': + description: Invalid tag value + security: + - petstore_auth: + - 'write:pets' + - 'read:pets' + deprecated: true + /pet/findByIds: + get: + tags: + - pet + summary: Finds Pets by ids + description: 'Multiple ids can be provided with comma separated strings.' + operationId: findPetsByIds + produces: + - application/xml + - application/json + parameters: + - name: ids + in: query + description: Ids to filter by + required: true + type: array + items: + type: number + collectionFormat: csv + responses: + '200': + description: successful operation + schema: + type: array + items: + $ref: '#/definitions/Pet' + '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 + produces: + - application/xml + - application/json + parameters: + - name: petId + in: path + description: ID of pet to return + required: true + type: integer + format: int64 + responses: + '200': + description: successful operation + schema: + $ref: '#/definitions/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 + consumes: + - application/x-www-form-urlencoded + produces: + - application/xml + - application/json + parameters: + - name: petId + in: path + description: ID of pet that needs to be updated + required: true + type: integer + format: int64 + - name: name + in: formData + description: Updated name of the pet + required: false + type: string + - name: status + in: formData + description: Updated status of the pet + required: false + type: string + responses: + '405': + description: Invalid input + security: + - petstore_auth: + - 'write:pets' + - 'read:pets' + delete: + tags: + - pet + summary: Deletes a pet + description: '' + operationId: deletePet + produces: + - application/xml + - application/json + parameters: + - name: api_key + in: header + required: false + type: string + - name: petId + in: path + description: Pet id to delete + required: true + 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 + consumes: + - multipart/form-data + produces: + - application/json + parameters: + - name: petId + in: path + description: ID of pet to update + required: true + type: integer + format: int64 + - name: additionalMetadata + in: formData + description: Additional data to pass to server + required: false + type: string + - name: file + in: formData + description: file to upload + required: false + type: file + responses: + '200': + description: successful operation + schema: + $ref: '#/definitions/ApiResponse' + security: + - petstore_auth: + - 'write:pets' + - 'read:pets' + /store/inventory: + get: + tags: + - store + summary: Returns pet inventories by status + description: Returns a map of status codes to quantities + operationId: getInventory + produces: + - application/json + parameters: [] + responses: + '200': + description: successful operation + 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 + produces: + - application/xml + - application/json + parameters: + - in: body + name: body + description: order placed for purchasing the pet + required: true + schema: + $ref: '#/definitions/Order' + responses: + '200': + description: successful operation + schema: + $ref: '#/definitions/Order' + '400': + description: Invalid Order + '/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 generated exceptions' + operationId: getOrderById + produces: + - application/xml + - application/json + parameters: + - name: orderId + in: path + description: ID of pet that needs to be fetched + required: true + type: integer + maximum: 5 + minimum: 1 + format: int64 + responses: + '200': + description: successful operation + schema: + $ref: '#/definitions/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 + produces: + - application/xml + - application/json + parameters: + - name: orderId + in: path + description: ID of the order that needs to be deleted + required: true + 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 + produces: + - application/xml + - application/json + parameters: + - in: body + name: body + description: Created user object + required: true + schema: + $ref: '#/definitions/User' + responses: + default: + description: successful operation + /user/createWithArray: + post: + tags: + - user + summary: Creates list of users with given input array + description: '' + operationId: createUsersWithArrayInput + produces: + - application/xml + - application/json + parameters: + - in: body + name: body + description: List of user object + required: true + schema: + type: array + items: + $ref: '#/definitions/User' + responses: + default: + description: successful operation + /user/createWithList: + post: + tags: + - user + summary: Creates list of users with given input array + description: '' + operationId: createUsersWithListInput + produces: + - application/xml + - application/json + parameters: + - in: body + name: body + description: List of user object + required: true + schema: + type: array + items: + $ref: '#/definitions/User' + responses: + default: + description: successful operation + /user/login: + get: + tags: + - user + summary: Logs user into the system + description: '' + operationId: loginUser + produces: + - application/xml + - application/json + parameters: + - name: username + in: query + description: The user name for login + required: true + type: string + - name: password + in: query + description: The password for login in clear text + required: true + type: string + responses: + '200': + description: successful operation + schema: + type: string + headers: + X-Rate-Limit: + type: integer + format: int32 + description: calls per hour allowed by the user + X-Expires-After: + type: string + format: date-time + description: date in UTC when toekn expires + '400': + description: Invalid username/password supplied + /user/logout: + get: + tags: + - user + summary: Logs out current logged in user session + description: '' + operationId: logoutUser + produces: + - application/xml + - application/json + parameters: [] + responses: + default: + description: successful operation + '/user/{username}': + get: + tags: + - user + summary: Get user by user name + description: '' + operationId: getUserByName + produces: + - application/xml + - application/json + parameters: + - name: username + in: path + description: 'The name that needs to be fetched. Use user1 for testing.' + required: true + type: string + responses: + '200': + description: successful operation + schema: + $ref: '#/definitions/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 + produces: + - application/xml + - application/json + parameters: + - name: username + in: path + description: name that need to be deleted + required: true + type: string + - in: body + name: body + description: Updated user object + required: true + schema: + $ref: '#/definitions/User' + responses: + '200': + description: successful operation + schema: + $ref: '#/definitions/DefaultMetaOnlyResponse' + '400': + description: Invalid user supplied + '404': + description: User not found + delete: + tags: + - user + summary: Delete user + description: This can only be done by the logged in user. + operationId: deleteUser + produces: + - application/xml + - application/json + parameters: + - name: username + in: path + description: The name that needs to be deleted + required: true + type: string + responses: + '400': + description: Invalid username supplied + '404': + description: User not found +securityDefinitions: + petstore_auth: + type: oauth2 + authorizationUrl: 'http://petstore.swagger.io/api/oauth/dialog' + flow: implicit + scopes: + 'write:pets': modify pets in your account + 'read:pets': read your pets + api_key: + type: apiKey + name: api_key + in: header +definitions: + 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 + x-isUniqueId: false + quantity: + type: integer + format: int32 + shipDate: + type: string + format: date-time + status: + type: string + description: Order Status + enum: + - placed + - approved + - delivered + default: approved + 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 + xml: + name: Category + User: + title: a User + description: A User who is purchasing from the pet store + type: object + x-keepAsJSObject: "subUser,subUser2" + required: + - id + - subUser2 + 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 + subUser: + $ref: '#/definitions/User' + subUser2: + $ref: '#/definitions/User' + 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: + - id + - category + - name + - photoUrls + - tags + - status + - alternateStatus + - otherDepStatuses + - friendAge + - age + - isHappy + - isTall + - warningStatus + - otherFriendIds + properties: + id: + type: integer + format: int64 + friendId: + type: integer + format: int64 + otherFriendIds: + type: array + items: + type: integer + format: int64 + friendAge: + type: integer + format: int64 + age: + type: integer + format: int64 + default: 2 + isHappy: + type: boolean + default: true + isTall: + type: boolean + category: + $ref: '#/definitions/Category' + optionalCategory: + $ref: '#/definitions/Category' + name: + type: string + example: doggie + entries: + type: array + items: + $ref: "#/definitions/Category" + surname: + type: string + example: woofy + photoUrls: + type: array + xml: + name: photoUrl + wrapped: true + items: + type: string + warningStatus: + $ref: "#/definitions/WarningCode" + depStatus: + $ref: "#/definitions/DeploymentRequestStatus" + alternateStatus: + $ref: "#/definitions/DeploymentRequestStatus" + otherDepStatuses: + type: array + items: + $ref: "#/definitions/DeploymentRequestStatus" + tags: + type: array + xml: + name: tag + wrapped: true + items: + $ref: '#/definitions/Tag' + optionalTags: + type: array + xml: + name: tag + wrapped: true + items: + $ref: '#/definitions/Tag' + status: + type: string + description: pet status in the store + enum: + - available + - pending + - sold + default: pending + 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 + WarningCode: + type: string + description: "Warning code returned when a potential problem is detected" + enum: + - Reduce_Volume_Range_To_Avoid_Large_Steps + - Raise_Amplifier_Volume + - No_Volume_Range_Specified + DeploymentRequestStatus: + type: string + enum: + - New + - Prepared + - Printed + - Tested + - Completed + - Cancelled + - Promoted + - Assigned + - Ready + - Packaged + - Pairing + - Paired + description: "Status of the deployment request" + example: New +################ Responses ################ + ResponseMeta: + type: object + description: "Mandatory part of each response given by our API" + x-keepAsJSObject: "errors" + required: + - code + properties: + code: + type: string + description: "Code returned by the function" + default: Ok + enum: + - Ok + - Generic_Exception + - Field_Error_Exception + - Image_Validation_Exception + - Invalid_Container_Creation_With_No_Default_Asset_Exception + - Invalid_Override_Mode_Exception + - Invalid_Tag_Exception + - Item_Use_Exception + - Missing_Platform_For_Software_Exception + - Missing_Software_For_Platform_Exception + - Platform_Not_Supported_Exception + - Refresh_Data_Exception + - Role_Assignment_Exception + - Task_Already_Running_Exception + - Logged_Out_Exception + - Authorization_Exception + - Unauthorized_Action_For_Current_User_Exception + - User_Already_Exists_But_Is_Not_Authenticated_Exception + - User_Already_Has_Active_Or_Closed_Galaxie_Api_Product_Exception + - User_Already_Has_Multiple_Galaxie_Api_Products_Exception + - Recurly_Api_Exception + - Recurly_Transaction_Error_Exception + - Galaxie_Api_Exception + example: Ok + detail: + type: string + description: "Explanation of what went wrong" + example: "this is some detail about the error or the success" + exception: + type: string + description: "Message of the exception that will help developer to debug this problem if needed" + example: "IOException + stack trace" + type: + type: string + description: "Type of error" + example: "Invalid Token" + errorCode: + $ref: "#/definitions/ErrorCode" + errors: + type: array + description: "An array of all the specific error encountered during the request" + items: + $ref: "#/definitions/Error" + Error: + type: object + description: "This represent an error normally linked to a specific item from a previous request" + required: + - type + properties: + type: + type: string + description: "Usually contains the simple name of the exception" + default: "GenericException" + example: "GenericException" + itemInfo: + $ref: "#/definitions/ItemId" + details: + type: string + description: "Simple explanation of the error" + example: "Could not update that field" + exception: + type: string + description: "Message of the exception that will help developer to debug this problem if needed" + example: "DBException + stack trace" + ErrorCode: + type: string + description: "Error code returned when an error occurs" + enum: + - Volume_Range_At_Lowest_Value + - Music_Volume_Blocks_Volume_Range_Decrease + - Volume_Range_At_Highest_Value + - Maximum_Volume_Blocks_Volume_Range_Increase + - Music_Volume_Blocks_Maximum_Volume_Decrease + - Maximum_Volume_At_Lowest_Value + - Volume_Range_Blocks_Maximum_Volume_Decrease + - Maximum_Volume_At_Highest_Value + - Message_Gain_Blocks_Maximum_Volume_Increase + - Music_Volume_Blocks_Maximum_Volume_Increase + - Maximum_Volume_Blocks_Message_Gain_Decrease + - Message_Gain_At_Highest_Value + - Music_Volume_Blocks_Message_Gain + - Maximum_Message_Gain_Lower_Than_Minimum + - Maximum_Message_Gain_Higher_Than_Maximum + - Maximum_Message_Gain_Lower_Than_Message_Gain + - Minimum_Volume_Blocks_Music_Volume_Decrease + - Maximum_Volume_Blocks_Music_Volume_Increase + ItemId: + type: object + description: "Simplified identifier of an item" + required: + - id + - type + properties: + id: + type: string + description: "Unique identifier of the item" + example: "45" + type: + type: string + description: "playlist" + example: "5667" + DefaultMetaOnlyResponse: + type: object + required: + - meta + properties: + meta: + $ref: "#/definitions/ResponseMeta" + FindPetsByStatusResponse: + type: object + required: + - meta + properties: + meta: + $ref: "#/definitions/ResponseMeta" + data: + type: array + items: + $ref: "#/definitions/Pet" + FindPetsByUserResponse: + type: object + required: + - meta + properties: + meta: + $ref: "#/definitions/ResponseMeta" + data: + type: array + items: + $ref: "#/definitions/User" + GetBehaviorTypeResponse: + type: object + required: + - meta + properties: + meta: + $ref: "#/definitions/ResponseMeta" + data: + $ref: "#/definitions/BehaviorType" + BehaviorType: + type: string + enum: + - Voluntary + - Involuntary + - Overt + description: "Behavior type of a pet" + example: Published + GetBehaviorPermissionsResponse: + type: object + required: + - meta + properties: + meta: + $ref: "#/definitions/ResponseMeta" + data: + $ref: "#/definitions/StringBooleanMap" + GetPetPartTypeResponse: + type: object + required: + - meta + properties: + meta: + $ref: "#/definitions/ResponseMeta" + data: + $ref: "#/definitions/PetPartType" + + PetPartType: + type: string + enum: + - Curved + - Smooth + - Long + description: "Type of pet part" + example: Linear + GetMatchingPartsResponse: + type: object + required: + - meta + properties: + meta: + $ref: "#/definitions/ResponseMeta" + data: + $ref: "#/definitions/MatchingParts" + MatchingParts: + type: object + description: "Contains all the matching parts" + required: + - connected + - related + properties: + connected: + type: array + items: + $ref: "#/definitions/Part" + description: "List of all the connected parts" + related: + type: array + items: + $ref: "#/definitions/Part" + description: "List of all the related parts" + Part: + type: object + description: "Contains all the info about a pet part" + x-entityId: "" + required: + - id + - name + properties: + id: + type: integer + format: int64 + description: "Unique identifier from the database" + example: 1 + name: + type: string + description: "Name of the part" + example: "head" + StringBooleanMap: + additionalProperties: + type: boolean diff --git a/modules/openapi-generator/src/test/resources/2_0/swift/petstore-with-fake-endpoints-models-for-testing.yaml b/modules/openapi-generator/src/test/resources/2_0/swift/petstore-with-fake-endpoints-models-for-testing.yaml index 38797a5bf10..6fa25c30218 100644 --- a/modules/openapi-generator/src/test/resources/2_0/swift/petstore-with-fake-endpoints-models-for-testing.yaml +++ b/modules/openapi-generator/src/test/resources/2_0/swift/petstore-with-fake-endpoints-models-for-testing.yaml @@ -1086,6 +1086,7 @@ definitions: xml: name: Order Category: + x-swift-hashable: true type: object required: - name diff --git a/modules/openapi-generator/src/test/resources/3_0/issue_9447.yaml b/modules/openapi-generator/src/test/resources/3_0/issue_9447.yaml new file mode 100644 index 00000000000..7cfa010c37f --- /dev/null +++ b/modules/openapi-generator/src/test/resources/3_0/issue_9447.yaml @@ -0,0 +1,106 @@ +openapi: 3.0.1 +info: + title: OpenAPI Petstore + description: "sample to vet integer handling" + license: + name: Apache-2.0 + url: https://www.apache.org/licenses/LICENSE-2.0.html + version: 1.0.0 +servers: + - url: http://petstore.swagger.io:80/v2 +tags: [] +paths: + /UnboundedInteger: + post: + operationId: UnboundedInteger + parameters: + - name: UnboundedInteger + in: path + required: true + schema: + type: integer + requestBody: + content: + application/json: + schema: + type: integer + required: true + responses: + 200: + description: success + content: + application/json: + schema: + type: integer + /Int64: + post: + operationId: Int64 + parameters: + - name: Int64 + in: path + required: true + schema: + type: integer + format: int64 + requestBody: + content: + application/json: + schema: + type: integer + format: int64 + required: true + responses: + 200: + description: success + content: + application/json: + schema: + type: integer + format: int64 + /Int32: + post: + operationId: Int32 + parameters: + - name: Int32 + in: path + required: true + schema: + type: integer + format: int32 + requestBody: + content: + application/json: + schema: + type: integer + format: int32 + required: true + responses: + 200: + description: success + content: + application/json: + schema: + type: integer + format: int32 +components: + schemas: + UnboundedInteger: + type: integer + Int32: + type: integer + format: int32 + Int64: + type: integer + format: int64 + ObjectModelWithIntegerProps: + type: object + properties: + UnboundedInteger: + type: integer + Int32: + type: integer + format: int32 + Int64: + type: integer + format: int64 + securitySchemes: {} \ No newline at end of file diff --git a/modules/openapi-generator/src/test/resources/3_0/issue_9848.yaml b/modules/openapi-generator/src/test/resources/3_0/issue_9848.yaml new file mode 100644 index 00000000000..5fc12434df5 --- /dev/null +++ b/modules/openapi-generator/src/test/resources/3_0/issue_9848.yaml @@ -0,0 +1,50 @@ +openapi: 3.0.1 +info: + title: OpenAPI Petstore + description: "sample spec" + license: + name: Apache-2.0 + url: https://www.apache.org/licenses/LICENSE-2.0.html + version: 1.0.0 +servers: + - url: http://petstore.swagger.io:80/v2 +tags: + - name: isX + description: an api that ensures that isX properties are present on Schema classes +paths: + /uniqueTypes: + get: + responses: + '200': + description: 'unique array' + content: + application/json: + schema: + $ref: '#/components/schemas/uniqueArray' + /nonUniqueTypes: + get: + responses: + '200': + description: 'non-unique array' + content: + application/json: + schema: + $ref: '#/components/schemas/nonUniqueArray' +components: + schemas: + uniqueArray: + type: object + properties: + array: + type: array + items: + type: string + uniqueItems: true + nonUniqueArray: + type: object + properties: + array: + type: array + items: + type: string + uniqueItems: false diff --git a/modules/openapi-generator/src/test/resources/3_0/kotlin/reserved_words.yaml b/modules/openapi-generator/src/test/resources/3_0/kotlin/reserved_words.yaml index c4022711783..881ffe49499 100644 --- a/modules/openapi-generator/src/test/resources/3_0/kotlin/reserved_words.yaml +++ b/modules/openapi-generator/src/test/resources/3_0/kotlin/reserved_words.yaml @@ -120,6 +120,18 @@ paths: in: header schema: type: string + - name: open + in: header + schema: + type: string + - name: external + in: header + schema: + type: string + - name: internal + in: header + schema: + type: string responses: '200': $ref: "#/components/schemas/Good" @@ -186,6 +198,12 @@ components: type: string while: type: string + open: + type: string + external: + type: string + internal: + type: string linked: $ref: '#/components/schemas/Linked' @@ -249,7 +267,12 @@ components: $ref: '#/components/schemas/when' while: $ref: '#/components/schemas/while' - + open: + $ref: '#/components/schemas/open' + external: + $ref: '#/components/schemas/external' + internal: + $ref: '#/components/schemas/internal' as: title: Testing reserved word 'as' type: object @@ -469,6 +492,30 @@ components: while: title: Testing reserved word 'while' type: object + properties: + id: + type: integer + format: int64 + + open: + title: Testing reserved word 'open' + type: object + properties: + id: + type: integer + format: int64 + + external: + title: Testing reserved word 'external' + type: object + properties: + id: + type: integer + format: int64 + + internal: + title: Testing reserved word 'internal' + type: object properties: id: type: integer diff --git a/modules/openapi-generator/src/test/resources/3_0/oneOfArrayMapImport.yaml b/modules/openapi-generator/src/test/resources/3_0/oneOfArrayMapImport.yaml new file mode 100644 index 00000000000..9fb06fc38f0 --- /dev/null +++ b/modules/openapi-generator/src/test/resources/3_0/oneOfArrayMapImport.yaml @@ -0,0 +1,49 @@ +openapi: 3.0.1 +info: + title: fruity + version: 0.0.1 +paths: + /: + get: + responses: + '200': + description: desc + content: + application/json: + schema: + $ref: '#/components/schemas/fruit' +components: + schemas: + fruit: + title: fruit + properties: + color: + type: string + oneOf: + - $ref: '#/components/schemas/apples' + - $ref: '#/components/schemas/grapes' + # additionalProperties: + # type: string + # uncomment this when https://github.com/swagger-api/swagger-parser/issues/1252 is resolved + apple: + title: apple + type: object + properties: + kind: + type: string + apples: + title: apples + type: object + additionalProperties: + $ref: '#/components/schemas/apple' + grape: + title: grape + type: object + properties: + color: + type: string + grapes: + title: grapes + type: array + items: + $ref: '#/components/schemas/grape' 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 431dd54b031..9dac77c2fa4 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 @@ -1008,7 +1008,7 @@ paths: tags: - fake description: >- - For this test, the body for this request much reference a schema named + For this test, the body for this request must reference a schema named `File`. operationId: testBodyWithFileSchema responses: @@ -1020,6 +1020,25 @@ paths: 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-paramters: put: tags: @@ -1030,6 +1049,7 @@ paths: - name: pipe in: query required: true + style: pipeDelimited schema: type: array items: diff --git a/modules/openapi-generator/src/test/resources/3_0/python/petstore-with-fake-endpoints-models-for-testing-with-http-signature.yaml b/modules/openapi-generator/src/test/resources/3_0/python/petstore-with-fake-endpoints-models-for-testing-with-http-signature.yaml index 683641e5a86..4efbc9cc028 100644 --- a/modules/openapi-generator/src/test/resources/3_0/python/petstore-with-fake-endpoints-models-for-testing-with-http-signature.yaml +++ b/modules/openapi-generator/src/test/resources/3_0/python/petstore-with-fake-endpoints-models-for-testing-with-http-signature.yaml @@ -1288,11 +1288,11 @@ paths: application/json: schema: $ref: '#/components/schemas/HealthCheckResult' - /fake/getInlineAdditionalPropertiesRefPayload: - get: + /fake/postInlineAdditionalPropertiesRefPayload: + post: tags: - fake - operationId: getInlineAdditionalPropertiesRefPayload + operationId: postInlineAdditionalPropertiesRefPayload responses: 200: description: InlineAdditionalPropertiesRefPayload @@ -1305,11 +1305,11 @@ paths: application/json: schema: $ref: '#/components/schemas/InlineAdditionalPropertiesRefPayload' - /fake/getInlineAdditionalPropertiesPayload: - get: + /fake/postInlineAdditionalPropertiesPayload: + post: tags: - fake - operationId: getInlineAdditionalPropertiesPayload + operationId: postInlineAdditionalPropertiesPayload responses: 200: description: InlineAdditionalPropertiesPayload diff --git a/modules/openapi-generator/src/test/resources/3_0/wsdl/petstore.yaml b/modules/openapi-generator/src/test/resources/3_0/wsdl/petstore.yaml new file mode 100644 index 00000000000..83ccdf1c611 --- /dev/null +++ b/modules/openapi-generator/src/test/resources/3_0/wsdl/petstore.yaml @@ -0,0 +1,728 @@ +openapi: 3.0.1 +info: + title: Swagger Petstore + description: 'This is a sample server Petstore server. You can find out more about Swagger + at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For + this sample, you can use the api key `special-key` to test the authorization filters.' + termsOfService: http://swagger.io/terms/ + contact: + email: apiteam@swagger.io + license: + name: Apache 2.0 + url: http://www.apache.org/licenses/LICENSE-2.0.html + version: 1.0.0 +externalDocs: + description: Find out more about Swagger + url: http://swagger.io +servers: +- url: https://petstore.swagger.io/v2 +- url: http://petstore.swagger.io/v2 +tags: +- name: pet + description: Everything about your Pets + externalDocs: + description: Find out more + url: http://swagger.io +- name: store + description: Access to Petstore orders +- name: user + description: Operations about user + externalDocs: + description: Find out more about our store + url: http://swagger.io +paths: + /pet: + put: + tags: + - pet + summary: Update an existing pet + operationId: updatePet + requestBody: + description: Pet object that needs to be added to the store + content: + application/json: + schema: + $ref: '#/components/schemas/Pet' + application/xml: + schema: + $ref: '#/components/schemas/Pet' + required: true + responses: + 400: + description: Invalid ID supplied + content: {} + 404: + description: Pet not found + content: {} + 405: + description: Validation exception + content: {} + security: + - petstore_auth: + - write:pets + - read:pets + x-codegen-request-body-name: body + post: + tags: + - pet + summary: Add a new pet to the store + operationId: addPet + requestBody: + description: Pet object that needs to be added to the store + content: + application/json: + schema: + $ref: '#/components/schemas/Pet' + application/xml: + schema: + $ref: '#/components/schemas/Pet' + required: true + responses: + 405: + description: Invalid input + content: {} + security: + - petstore_auth: + - write:pets + - read:pets + x-codegen-request-body-name: body + /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: true + schema: + type: array + items: + type: string + default: available + enum: + - available + - pending + - sold + 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 + content: {} + security: + - petstore_auth: + - write:pets + - read:pets + /pet/findByTags: + get: + tags: + - pet + summary: Finds Pets by tags + description: Muliple 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: true + 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 + content: {} + deprecated: true + security: + - petstore_auth: + - write:pets + - read:pets + /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 + content: {} + 404: + description: Pet not found + content: {} + security: + - api_key: [] + post: + tags: + - pet + summary: Updates a pet in the store with form data + operationId: updatePetWithForm + parameters: + - name: petId + in: path + description: ID of pet that needs to be updated + required: true + schema: + type: integer + format: int64 + requestBody: + content: + application/x-www-form-urlencoded: + schema: + properties: + name: + type: string + description: Updated name of the pet + status: + type: string + description: Updated status of the pet + responses: + 405: + description: Invalid input + content: {} + security: + - petstore_auth: + - write:pets + - read:pets + delete: + tags: + - pet + summary: Deletes a pet + operationId: deletePet + parameters: + - name: api_key + in: header + schema: + type: string + - name: petId + in: path + description: Pet id to delete + required: true + schema: + type: integer + format: int64 + responses: + 400: + description: Invalid ID supplied + content: {} + 404: + description: Pet not found + content: {} + security: + - petstore_auth: + - write:pets + - read:pets + /pet/{petId}/uploadImage: + post: + tags: + - pet + summary: uploads an image + operationId: uploadFile + parameters: + - name: petId + in: path + description: ID of pet to update + required: true + schema: + type: integer + format: int64 + requestBody: + content: + multipart/form-data: + schema: + properties: + additionalMetadata: + type: string + description: Additional data to pass to server + file: + type: string + description: file to upload + format: binary + responses: + 200: + description: successful operation + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + security: + - petstore_auth: + - write:pets + - read:pets + /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 + operationId: placeOrder + requestBody: + description: order placed for purchasing the pet + content: + '*/*': + schema: + $ref: '#/components/schemas/Order' + required: true + responses: + 200: + description: successful operation + content: + application/xml: + schema: + $ref: '#/components/schemas/Order' + application/json: + schema: + $ref: '#/components/schemas/Order' + 400: + description: Invalid Order + content: {} + x-codegen-request-body-name: body + /store/order/{orderId}: + get: + tags: + - store + summary: Find purchase order by ID + description: For valid response try integer IDs with value >= 1 and <= 10. Other + values will generated exceptions + operationId: getOrderById + parameters: + - name: orderId + in: path + description: ID of pet that needs to be fetched + required: true + schema: + maximum: 10.0 + minimum: 1.0 + type: integer + format: int64 + 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 + content: {} + 404: + description: Order not found + content: {} + delete: + tags: + - store + summary: Delete purchase order by ID + description: For valid response try integer IDs with positive integer value. Negative + or non-integer values will generate API errors + operationId: deleteOrder + parameters: + - name: orderId + in: path + description: ID of the order that needs to be deleted + required: true + schema: + minimum: 1.0 + type: integer + format: int64 + responses: + 400: + description: Invalid ID supplied + content: {} + 404: + description: Order not found + content: {} + /user: + post: + tags: + - user + summary: Create user + description: This can only be done by the logged in user. + operationId: createUser + requestBody: + description: Created user object + content: + '*/*': + schema: + $ref: '#/components/schemas/User' + required: true + responses: + default: + description: successful operation + content: {} + x-codegen-request-body-name: body + /user/createWithArray: + post: + tags: + - user + summary: Creates list of users with given input array + operationId: createUsersWithArrayInput + requestBody: + description: List of user object + content: + '*/*': + schema: + type: array + items: + $ref: '#/components/schemas/User' + required: true + responses: + default: + description: successful operation + content: {} + x-codegen-request-body-name: body + /user/createWithList: + post: + tags: + - user + summary: Creates list of users with given input array + operationId: createUsersWithListInput + requestBody: + description: List of user object + content: + '*/*': + schema: + type: array + items: + $ref: '#/components/schemas/User' + required: true + responses: + default: + description: successful operation + content: {} + x-codegen-request-body-name: body + /user/login: + get: + tags: + - user + summary: Logs user into the system + 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 + content: {} + /user/logout: + get: + tags: + - user + summary: Logs out current logged in user session + operationId: logoutUser + responses: + default: + description: successful operation + content: {} + /user/{username}: + get: + tags: + - user + summary: Get user by user name + 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 + content: {} + 404: + description: User not found + content: {} + 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 updated + required: true + schema: + type: string + requestBody: + description: Updated user object + content: + '*/*': + schema: + $ref: '#/components/schemas/User' + required: true + responses: + 400: + description: Invalid user supplied + content: {} + 404: + description: User not found + content: {} + x-codegen-request-body-name: body + 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 + content: {} + 404: + description: User not found + content: {} +components: + schemas: + 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 + properties: + id: + type: integer + format: int64 + name: + type: string + xml: + name: Category + User: + 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 + description: User Status + format: int32 + xml: + name: User + Tag: + type: object + properties: + id: + type: integer + format: int64 + name: + type: string + xml: + name: Tag + Pet: + required: + - name + - photoUrls + type: object + 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: + type: object + properties: + code: + type: integer + format: int32 + type: + type: string + message: + type: string + securitySchemes: + petstore_auth: + type: oauth2 + flows: + implicit: + authorizationUrl: http://petstore.swagger.io/oauth/dialog + scopes: + write:pets: modify pets in your account + read:pets: read your pets + api_key: + type: apiKey + name: api_key + in: header diff --git a/modules/openapi-generator/src/test/resources/bugs/issue_9719.yaml b/modules/openapi-generator/src/test/resources/bugs/issue_9719.yaml new file mode 100644 index 00000000000..4685794206c --- /dev/null +++ b/modules/openapi-generator/src/test/resources/bugs/issue_9719.yaml @@ -0,0 +1,48 @@ +openapi: 3.0.1 +info: + title: OpenAPI Petstore + description: "sample to vet integer handling" + license: + name: Apache-2.0 + url: https://www.apache.org/licenses/LICENSE-2.0.html + version: 1.0.0 +servers: + - url: http://petstore.swagger.io:80/v2 +tags: [] +paths: + /dotDelimiter: + get: + summary: List all users + operationId: petstore.api.users.get_all + tags: + - users + responses: + '200': + description: A paged array of users + headers: + x-next: + description: A link to the next page of responses + schema: + type: string + content: + application/json: + schema: + type: string + /underscoreDelimiter: + get: + summary: List all users + operationId: petstore_api_users_getAll + tags: + - users + responses: + '200': + description: A paged array of users + headers: + x-next: + description: A link to the next page of responses + schema: + type: string + content: + application/json: + schema: + type: string \ No newline at end of file diff --git a/pom.xml b/pom.xml index fbc5805d35c..c58b7a50f5a 100644 --- a/pom.xml +++ b/pom.xml @@ -1187,18 +1187,22 @@ samples/server/petstore/python-aiohttp samples/server/petstore/python-aiohttp-srclayout + samples/server/petstore/python-fastapi samples/server/petstore/python-flask + samples/server/petstore/rust-server samples/client/petstore/ruby-faraday samples/client/petstore/ruby + + samples/client/petstore/cpp-qt samples/client/petstore/rust samples/client/petstore/rust/reqwest/petstore samples/client/petstore/rust/reqwest/petstore-async @@ -1219,7 +1223,8 @@ 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/tests/inversify + samples/openapi3/client/petstore/typescript/tests/deno samples/client/petstore/typescript-fetch/builds/default samples/client/petstore/typescript-fetch/builds/es6-target @@ -1415,18 +1420,40 @@ - samples/openapi3/client/petstore/dart2/petstore_client_lib - samples/openapi3/client/petstore/dart2/petstore - samples/openapi3/client/petstore/dart-dio/petstore_client_lib - samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake - samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake - samples/client/petstore/R + + samples.dart-2.13 + + + env + samples.dart-2.13 + + + + samples/openapi3/client/petstore/dart2/petstore_client_lib + samples/openapi3/client/petstore/dart2/petstore + + samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake + + + + samples.dart-2.10 + + + env + samples.dart-2.10 + + + + samples/openapi3/client/petstore/dart-dio/petstore_client_lib + samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake + + samples.ios @@ -1472,15 +1499,24 @@ samples/client/petstore/objc/core-data/SwaggerClientTests--> + + openapi-generator + + true + + !integration-test + + + + modules/openapi-generator-core + modules/openapi-generator + modules/openapi-generator-cli + modules/openapi-generator-maven-plugin + modules/openapi-generator-gradle-plugin + modules/openapi-generator-online + + - - modules/openapi-generator-core - modules/openapi-generator - modules/openapi-generator-cli - modules/openapi-generator-maven-plugin - modules/openapi-generator-gradle-plugin - modules/openapi-generator-online - target/site @@ -1541,7 +1577,7 @@ 1.8 2.1.2 io.swagger.parser.v3 - 2.0.24 + 2.0.26 3.3.1 2.4 1.2 diff --git a/samples/client/petstore/R/.openapi-generator/VERSION b/samples/client/petstore/R/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/client/petstore/R/.openapi-generator/VERSION +++ b/samples/client/petstore/R/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/client/petstore/R/R/category.R b/samples/client/petstore/R/R/category.R index 7c74320d1ac..059b64e3748 100644 --- a/samples/client/petstore/R/R/category.R +++ b/samples/client/petstore/R/R/category.R @@ -89,4 +89,3 @@ Category <- R6::R6Class( } ) ) - diff --git a/samples/client/petstore/R/R/model_api_response.R b/samples/client/petstore/R/R/model_api_response.R index c7cdbb76c2a..a1c16133557 100644 --- a/samples/client/petstore/R/R/model_api_response.R +++ b/samples/client/petstore/R/R/model_api_response.R @@ -111,4 +111,3 @@ ModelApiResponse <- R6::R6Class( } ) ) - diff --git a/samples/client/petstore/R/R/order.R b/samples/client/petstore/R/R/order.R index 3218835cc35..d3e2e46b493 100644 --- a/samples/client/petstore/R/R/order.R +++ b/samples/client/petstore/R/R/order.R @@ -62,6 +62,7 @@ Order <- R6::R6Class( self$`status` <- `status` } if (!is.null(`complete`)) { + stopifnot(is.logical(`complete`), length(`complete`) == 1) self$`complete` <- `complete` } }, @@ -156,9 +157,9 @@ Order <- R6::R6Class( if (!is.null(self$`complete`)) { sprintf( '"complete": - "%s" + %s ', - self$`complete` + tolower(self$`complete`) )} ) jsoncontent <- paste(jsoncontent, collapse = ",") @@ -176,4 +177,3 @@ Order <- R6::R6Class( } ) ) - diff --git a/samples/client/petstore/R/R/pet.R b/samples/client/petstore/R/R/pet.R index 509d16934e1..1960b16906a 100644 --- a/samples/client/petstore/R/R/pet.R +++ b/samples/client/petstore/R/R/pet.R @@ -181,4 +181,3 @@ Pet <- R6::R6Class( } ) ) - diff --git a/samples/client/petstore/R/R/tag.R b/samples/client/petstore/R/R/tag.R index 56b89c6b425..ba2def34c43 100644 --- a/samples/client/petstore/R/R/tag.R +++ b/samples/client/petstore/R/R/tag.R @@ -89,4 +89,3 @@ Tag <- R6::R6Class( } ) ) - diff --git a/samples/client/petstore/R/R/user.R b/samples/client/petstore/R/R/user.R index bf88bee4027..47ffaea0d88 100644 --- a/samples/client/petstore/R/R/user.R +++ b/samples/client/petstore/R/R/user.R @@ -221,4 +221,3 @@ User <- R6::R6Class( } ) ) - diff --git a/samples/client/petstore/android/httpclient/.openapi-generator/FILES b/samples/client/petstore/android/httpclient/.openapi-generator/FILES new file mode 100644 index 00000000000..9b30755ee5b --- /dev/null +++ b/samples/client/petstore/android/httpclient/.openapi-generator/FILES @@ -0,0 +1,34 @@ +.gitignore +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 +git_push.sh +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/ApiException.java +src/main/java/org/openapitools/client/ApiInvoker.java +src/main/java/org/openapitools/client/HttpPatch.java +src/main/java/org/openapitools/client/JsonUtil.java +src/main/java/org/openapitools/client/Pair.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/ApiResponse.java +src/main/java/org/openapitools/client/model/Category.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/android/httpclient/.openapi-generator/VERSION b/samples/client/petstore/android/httpclient/.openapi-generator/VERSION index afa63656064..6555596f931 100644 --- a/samples/client/petstore/android/httpclient/.openapi-generator/VERSION +++ b/samples/client/petstore/android/httpclient/.openapi-generator/VERSION @@ -1 +1 @@ -4.0.0-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/android/httpclient/README.md b/samples/client/petstore/android/httpclient/README.md index 309ba5d7811..325ce22b90c 100644 --- a/samples/client/petstore/android/httpclient/README.md +++ b/samples/client/petstore/android/httpclient/README.md @@ -49,8 +49,8 @@ At first generate the JAR by executing: Then manually install the following JARs: -* target/openapi-android-client-1.0.0.jar -* target/lib/*.jar +- target/openapi-android-client-1.0.0.jar +- target/lib/*.jar ## Getting Started @@ -64,9 +64,9 @@ public class PetApiExample { public static void main(String[] args) { PetApi apiInstance = new PetApi(); - Pet pet = new Pet(); // Pet | Pet object that needs to be added to the store + Pet body = new Pet(); // Pet | Pet object that needs to be added to the store try { - apiInstance.addPet(pet); + apiInstance.addPet(body); } catch (ApiException e) { System.err.println("Exception when calling PetApi#addPet"); e.printStackTrace(); @@ -120,11 +120,13 @@ Authentication schemes defined for the API: ### api_key - **Type**: API key + - **API key parameter name**: api_key - **Location**: HTTP header ### petstore_auth + - **Type**: OAuth - **Flow**: implicit - **Authorization URL**: http://petstore.swagger.io/api/oauth/dialog diff --git a/samples/client/petstore/android/httpclient/build.gradle b/samples/client/petstore/android/httpclient/build.gradle index 6be898ef01d..5f4c815d2ed 100644 --- a/samples/client/petstore/android/httpclient/build.gradle +++ b/samples/client/petstore/android/httpclient/build.gradle @@ -3,7 +3,7 @@ project.version = '1.0.0' buildscript { repositories { - mavenCentral() + maven { url "https://repo1.maven.org/maven2" } jcenter() } dependencies { @@ -51,7 +51,7 @@ android { ext { swagger_annotations_version = "1.5.0" gson_version = "2.3.1" - httpclient_version = "4.5.2" + httpclient_version = "4.5.13" httpcore_version = "4.4.4" junit_version = "4.13" } diff --git a/samples/client/petstore/android/httpclient/docs/ApiResponse.md b/samples/client/petstore/android/httpclient/docs/ApiResponse.md index 1c17767c2b7..a169bf232e1 100644 --- a/samples/client/petstore/android/httpclient/docs/ApiResponse.md +++ b/samples/client/petstore/android/httpclient/docs/ApiResponse.md @@ -1,7 +1,9 @@ + # ApiResponse ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **code** | **Integer** | | [optional] @@ -10,3 +12,4 @@ Name | Type | Description | Notes + diff --git a/samples/client/petstore/android/httpclient/docs/Category.md b/samples/client/petstore/android/httpclient/docs/Category.md index e2df0803278..53c9fedc8bc 100644 --- a/samples/client/petstore/android/httpclient/docs/Category.md +++ b/samples/client/petstore/android/httpclient/docs/Category.md @@ -1,7 +1,9 @@ + # Category ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **id** | **Long** | | [optional] @@ -9,3 +11,4 @@ Name | Type | Description | Notes + diff --git a/samples/client/petstore/android/httpclient/docs/Order.md b/samples/client/petstore/android/httpclient/docs/Order.md index 5746ce97fad..f49e8704e08 100644 --- a/samples/client/petstore/android/httpclient/docs/Order.md +++ b/samples/client/petstore/android/httpclient/docs/Order.md @@ -1,7 +1,9 @@ + # Order ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **id** | **Long** | | [optional] @@ -12,10 +14,11 @@ Name | Type | Description | Notes **complete** | **Boolean** | | [optional] - ## Enum: StatusEnum + Name | Value ---- | ----- + diff --git a/samples/client/petstore/android/httpclient/docs/Pet.md b/samples/client/petstore/android/httpclient/docs/Pet.md index a4daa24feb6..72e3338dfb8 100644 --- a/samples/client/petstore/android/httpclient/docs/Pet.md +++ b/samples/client/petstore/android/httpclient/docs/Pet.md @@ -1,7 +1,9 @@ + # Pet ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **id** | **Long** | | [optional] @@ -12,10 +14,11 @@ Name | Type | Description | Notes **status** | [**StatusEnum**](#StatusEnum) | pet status in the store | [optional] - ## Enum: StatusEnum + Name | Value ---- | ----- + diff --git a/samples/client/petstore/android/httpclient/docs/PetApi.md b/samples/client/petstore/android/httpclient/docs/PetApi.md index 7cf076f29c5..4f91f08bc47 100644 --- a/samples/client/petstore/android/httpclient/docs/PetApi.md +++ b/samples/client/petstore/android/httpclient/docs/PetApi.md @@ -14,21 +14,23 @@ Method | HTTP request | Description [**uploadFile**](PetApi.md#uploadFile) | **POST** /pet/{petId}/uploadImage | uploads an image - -# **addPet** -> addPet(pet) + +## addPet + +> addPet(body) Add a new pet to the store ### Example + ```java // Import classes: //import org.openapitools.client.api.PetApi; PetApi apiInstance = new PetApi(); -Pet pet = new Pet(); // Pet | Pet object that needs to be added to the store +Pet body = new Pet(); // Pet | Pet object that needs to be added to the store try { - apiInstance.addPet(pet); + apiInstance.addPet(body); } catch (ApiException e) { System.err.println("Exception when calling PetApi#addPet"); e.printStackTrace(); @@ -37,9 +39,10 @@ try { ### Parameters + Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **pet** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | + **body** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | ### Return type @@ -51,16 +54,18 @@ null (empty response body) ### HTTP request headers - - **Content-Type**: application/json, application/xml - - **Accept**: Not defined +- **Content-Type**: application/json, application/xml +- **Accept**: Not defined + + +## deletePet - -# **deletePet** > deletePet(petId, apiKey) Deletes a pet ### Example + ```java // Import classes: //import org.openapitools.client.api.PetApi; @@ -78,6 +83,7 @@ try { ### Parameters + Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **petId** | **Long**| Pet id to delete | [default to null] @@ -93,11 +99,12 @@ null (empty response body) ### HTTP request headers - - **Content-Type**: Not defined - - **Accept**: Not defined +- **Content-Type**: Not defined +- **Accept**: Not defined + + +## findPetsByStatus - -# **findPetsByStatus** > List<Pet> findPetsByStatus(status) Finds Pets by status @@ -105,6 +112,7 @@ Finds Pets by status Multiple status values can be provided with comma separated strings ### Example + ```java // Import classes: //import org.openapitools.client.api.PetApi; @@ -122,6 +130,7 @@ try { ### Parameters + Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **status** | [**List<String>**](String.md)| Status values that need to be considered for filter | [default to null] [enum: available, pending, sold] @@ -136,11 +145,12 @@ Name | Type | Description | Notes ### HTTP request headers - - **Content-Type**: Not defined - - **Accept**: application/xml, application/json +- **Content-Type**: Not defined +- **Accept**: application/xml, application/json + + +## findPetsByTags - -# **findPetsByTags** > List<Pet> findPetsByTags(tags) Finds Pets by tags @@ -148,6 +158,7 @@ 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.api.PetApi; @@ -165,6 +176,7 @@ try { ### Parameters + Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **tags** | [**List<String>**](String.md)| Tags to filter by | [default to null] @@ -179,11 +191,12 @@ Name | Type | Description | Notes ### HTTP request headers - - **Content-Type**: Not defined - - **Accept**: application/xml, application/json +- **Content-Type**: Not defined +- **Accept**: application/xml, application/json + + +## getPetById - -# **getPetById** > Pet getPetById(petId) Find pet by ID @@ -191,6 +204,7 @@ Find pet by ID Returns a single pet ### Example + ```java // Import classes: //import org.openapitools.client.api.PetApi; @@ -208,6 +222,7 @@ try { ### Parameters + Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **petId** | **Long**| ID of pet to return | [default to null] @@ -222,24 +237,26 @@ Name | Type | Description | Notes ### HTTP request headers - - **Content-Type**: Not defined - - **Accept**: application/xml, application/json +- **Content-Type**: Not defined +- **Accept**: application/xml, application/json - -# **updatePet** -> updatePet(pet) + +## updatePet + +> updatePet(body) Update an existing pet ### Example + ```java // Import classes: //import org.openapitools.client.api.PetApi; PetApi apiInstance = new PetApi(); -Pet pet = new Pet(); // Pet | Pet object that needs to be added to the store +Pet body = new Pet(); // Pet | Pet object that needs to be added to the store try { - apiInstance.updatePet(pet); + apiInstance.updatePet(body); } catch (ApiException e) { System.err.println("Exception when calling PetApi#updatePet"); e.printStackTrace(); @@ -248,9 +265,10 @@ try { ### Parameters + Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **pet** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | + **body** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | ### Return type @@ -262,16 +280,18 @@ null (empty response body) ### HTTP request headers - - **Content-Type**: application/json, application/xml - - **Accept**: Not defined +- **Content-Type**: application/json, application/xml +- **Accept**: Not defined + + +## updatePetWithForm - -# **updatePetWithForm** > updatePetWithForm(petId, name, status) Updates a pet in the store with form data ### Example + ```java // Import classes: //import org.openapitools.client.api.PetApi; @@ -290,6 +310,7 @@ try { ### Parameters + Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **petId** | **Long**| ID of pet that needs to be updated | [default to null] @@ -306,16 +327,18 @@ null (empty response body) ### HTTP request headers - - **Content-Type**: application/x-www-form-urlencoded - - **Accept**: Not defined +- **Content-Type**: application/x-www-form-urlencoded +- **Accept**: Not defined + + +## uploadFile - -# **uploadFile** > ApiResponse uploadFile(petId, additionalMetadata, file) uploads an image ### Example + ```java // Import classes: //import org.openapitools.client.api.PetApi; @@ -335,6 +358,7 @@ try { ### Parameters + Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **petId** | **Long**| ID of pet to update | [default to null] @@ -351,6 +375,6 @@ Name | Type | Description | Notes ### HTTP request headers - - **Content-Type**: multipart/form-data - - **Accept**: application/json +- **Content-Type**: multipart/form-data +- **Accept**: application/json diff --git a/samples/client/petstore/android/httpclient/docs/StoreApi.md b/samples/client/petstore/android/httpclient/docs/StoreApi.md index b768ad5ba98..d2229bfd71f 100644 --- a/samples/client/petstore/android/httpclient/docs/StoreApi.md +++ b/samples/client/petstore/android/httpclient/docs/StoreApi.md @@ -10,8 +10,9 @@ Method | HTTP request | Description [**placeOrder**](StoreApi.md#placeOrder) | **POST** /store/order | Place an order for a pet - -# **deleteOrder** + +## deleteOrder + > deleteOrder(orderId) Delete purchase order by ID @@ -19,6 +20,7 @@ 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.api.StoreApi; @@ -35,6 +37,7 @@ try { ### Parameters + Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **orderId** | **String**| ID of the order that needs to be deleted | [default to null] @@ -49,11 +52,12 @@ No authorization required ### HTTP request headers - - **Content-Type**: Not defined - - **Accept**: Not defined +- **Content-Type**: Not defined +- **Accept**: Not defined + + +## getInventory - -# **getInventory** > Map<String, Integer> getInventory() Returns pet inventories by status @@ -61,6 +65,7 @@ Returns pet inventories by status Returns a map of status codes to quantities ### Example + ```java // Import classes: //import org.openapitools.client.api.StoreApi; @@ -76,6 +81,7 @@ try { ``` ### Parameters + This endpoint does not need any parameter. ### Return type @@ -88,11 +94,12 @@ This endpoint does not need any parameter. ### HTTP request headers - - **Content-Type**: Not defined - - **Accept**: application/json +- **Content-Type**: Not defined +- **Accept**: application/json + + +## getOrderById - -# **getOrderById** > Order getOrderById(orderId) Find purchase order by ID @@ -100,6 +107,7 @@ Find purchase order by ID For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions ### Example + ```java // Import classes: //import org.openapitools.client.api.StoreApi; @@ -117,6 +125,7 @@ try { ### Parameters + Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **orderId** | **Long**| ID of pet that needs to be fetched | [default to null] @@ -131,24 +140,26 @@ No authorization required ### HTTP request headers - - **Content-Type**: Not defined - - **Accept**: application/xml, application/json +- **Content-Type**: Not defined +- **Accept**: application/xml, application/json - -# **placeOrder** -> Order placeOrder(order) + +## placeOrder + +> Order placeOrder(body) Place an order for a pet ### Example + ```java // Import classes: //import org.openapitools.client.api.StoreApi; StoreApi apiInstance = new StoreApi(); -Order order = new Order(); // Order | order placed for purchasing the pet +Order body = new Order(); // Order | order placed for purchasing the pet try { - Order result = apiInstance.placeOrder(order); + Order result = apiInstance.placeOrder(body); System.out.println(result); } catch (ApiException e) { System.err.println("Exception when calling StoreApi#placeOrder"); @@ -158,9 +169,10 @@ try { ### Parameters + Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **order** | [**Order**](Order.md)| order placed for purchasing the pet | + **body** | [**Order**](Order.md)| order placed for purchasing the pet | ### Return type @@ -172,6 +184,6 @@ No authorization required ### HTTP request headers - - **Content-Type**: Not defined - - **Accept**: application/xml, application/json +- **Content-Type**: Not defined +- **Accept**: application/xml, application/json diff --git a/samples/client/petstore/android/httpclient/docs/Tag.md b/samples/client/petstore/android/httpclient/docs/Tag.md index de6814b55d5..b540cab453f 100644 --- a/samples/client/petstore/android/httpclient/docs/Tag.md +++ b/samples/client/petstore/android/httpclient/docs/Tag.md @@ -1,7 +1,9 @@ + # Tag ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **id** | **Long** | | [optional] @@ -9,3 +11,4 @@ Name | Type | Description | Notes + diff --git a/samples/client/petstore/android/httpclient/docs/User.md b/samples/client/petstore/android/httpclient/docs/User.md index 8b6753dd284..5e51c05150c 100644 --- a/samples/client/petstore/android/httpclient/docs/User.md +++ b/samples/client/petstore/android/httpclient/docs/User.md @@ -1,7 +1,9 @@ + # User ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **id** | **Long** | | [optional] @@ -15,3 +17,4 @@ Name | Type | Description | Notes + diff --git a/samples/client/petstore/android/httpclient/docs/UserApi.md b/samples/client/petstore/android/httpclient/docs/UserApi.md index e5a16428112..4c54ee4c77c 100644 --- a/samples/client/petstore/android/httpclient/docs/UserApi.md +++ b/samples/client/petstore/android/httpclient/docs/UserApi.md @@ -14,23 +14,25 @@ Method | HTTP request | Description [**updateUser**](UserApi.md#updateUser) | **PUT** /user/{username} | Updated user - -# **createUser** -> createUser(user) + +## createUser + +> createUser(body) Create user This can only be done by the logged in user. ### Example + ```java // Import classes: //import org.openapitools.client.api.UserApi; UserApi apiInstance = new UserApi(); -User user = new User(); // User | Created user object +User body = new User(); // User | Created user object try { - apiInstance.createUser(user); + apiInstance.createUser(body); } catch (ApiException e) { System.err.println("Exception when calling UserApi#createUser"); e.printStackTrace(); @@ -39,9 +41,10 @@ try { ### Parameters + Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **user** | [**User**](User.md)| Created user object | + **body** | [**User**](User.md)| Created user object | ### Return type @@ -53,24 +56,26 @@ No authorization required ### HTTP request headers - - **Content-Type**: Not defined - - **Accept**: Not defined +- **Content-Type**: Not defined +- **Accept**: Not defined - -# **createUsersWithArrayInput** -> createUsersWithArrayInput(user) + +## createUsersWithArrayInput + +> createUsersWithArrayInput(body) Creates list of users with given input array ### Example + ```java // Import classes: //import org.openapitools.client.api.UserApi; UserApi apiInstance = new UserApi(); -List user = Arrays.asList(new List()); // List | List of user object +List body = Arrays.asList(new User()); // List | List of user object try { - apiInstance.createUsersWithArrayInput(user); + apiInstance.createUsersWithArrayInput(body); } catch (ApiException e) { System.err.println("Exception when calling UserApi#createUsersWithArrayInput"); e.printStackTrace(); @@ -79,9 +84,10 @@ try { ### Parameters + Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **user** | [**List<User>**](List.md)| List of user object | + **body** | [**List<User>**](User.md)| List of user object | ### Return type @@ -93,24 +99,26 @@ No authorization required ### HTTP request headers - - **Content-Type**: Not defined - - **Accept**: Not defined +- **Content-Type**: Not defined +- **Accept**: Not defined - -# **createUsersWithListInput** -> createUsersWithListInput(user) + +## createUsersWithListInput + +> createUsersWithListInput(body) Creates list of users with given input array ### Example + ```java // Import classes: //import org.openapitools.client.api.UserApi; UserApi apiInstance = new UserApi(); -List user = Arrays.asList(new List()); // List | List of user object +List body = Arrays.asList(new User()); // List | List of user object try { - apiInstance.createUsersWithListInput(user); + apiInstance.createUsersWithListInput(body); } catch (ApiException e) { System.err.println("Exception when calling UserApi#createUsersWithListInput"); e.printStackTrace(); @@ -119,9 +127,10 @@ try { ### Parameters + Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **user** | [**List<User>**](List.md)| List of user object | + **body** | [**List<User>**](User.md)| List of user object | ### Return type @@ -133,11 +142,12 @@ No authorization required ### HTTP request headers - - **Content-Type**: Not defined - - **Accept**: Not defined +- **Content-Type**: Not defined +- **Accept**: Not defined + + +## deleteUser - -# **deleteUser** > deleteUser(username) Delete user @@ -145,6 +155,7 @@ Delete user This can only be done by the logged in user. ### Example + ```java // Import classes: //import org.openapitools.client.api.UserApi; @@ -161,6 +172,7 @@ try { ### Parameters + Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **username** | **String**| The name that needs to be deleted | [default to null] @@ -175,16 +187,18 @@ No authorization required ### HTTP request headers - - **Content-Type**: Not defined - - **Accept**: Not defined +- **Content-Type**: Not defined +- **Accept**: Not defined + + +## getUserByName - -# **getUserByName** > User getUserByName(username) Get user by user name ### Example + ```java // Import classes: //import org.openapitools.client.api.UserApi; @@ -202,6 +216,7 @@ try { ### Parameters + Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **username** | **String**| The name that needs to be fetched. Use user1 for testing. | [default to null] @@ -216,16 +231,18 @@ No authorization required ### HTTP request headers - - **Content-Type**: Not defined - - **Accept**: application/xml, application/json +- **Content-Type**: Not defined +- **Accept**: application/xml, application/json + + +## loginUser - -# **loginUser** > String loginUser(username, password) Logs user into the system ### Example + ```java // Import classes: //import org.openapitools.client.api.UserApi; @@ -244,6 +261,7 @@ try { ### Parameters + Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **username** | **String**| The user name for login | [default to null] @@ -259,16 +277,18 @@ No authorization required ### HTTP request headers - - **Content-Type**: Not defined - - **Accept**: application/xml, application/json +- **Content-Type**: Not defined +- **Accept**: application/xml, application/json + + +## logoutUser - -# **logoutUser** > logoutUser() Logs out current logged in user session ### Example + ```java // Import classes: //import org.openapitools.client.api.UserApi; @@ -283,6 +303,7 @@ try { ``` ### Parameters + This endpoint does not need any parameter. ### Return type @@ -295,27 +316,29 @@ No authorization required ### HTTP request headers - - **Content-Type**: Not defined - - **Accept**: Not defined +- **Content-Type**: Not defined +- **Accept**: Not defined - -# **updateUser** -> updateUser(username, user) + +## updateUser + +> updateUser(username, body) Updated user This can only be done by the logged in user. ### Example + ```java // Import classes: //import org.openapitools.client.api.UserApi; UserApi apiInstance = new UserApi(); String username = null; // String | name that need to be deleted -User user = new User(); // User | Updated user object +User body = new User(); // User | Updated user object try { - apiInstance.updateUser(username, user); + apiInstance.updateUser(username, body); } catch (ApiException e) { System.err.println("Exception when calling UserApi#updateUser"); e.printStackTrace(); @@ -324,10 +347,11 @@ try { ### Parameters + Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **username** | **String**| name that need to be deleted | [default to null] - **user** | [**User**](User.md)| Updated user object | + **body** | [**User**](User.md)| Updated user object | ### Return type @@ -339,6 +363,6 @@ No authorization required ### HTTP request headers - - **Content-Type**: Not defined - - **Accept**: Not defined +- **Content-Type**: Not defined +- **Accept**: Not defined diff --git a/samples/client/petstore/android/httpclient/git_push.sh b/samples/client/petstore/android/httpclient/git_push.sh index 20057f67ade..ced3be2b0c7 100644 --- a/samples/client/petstore/android/httpclient/git_push.sh +++ b/samples/client/petstore/android/httpclient/git_push.sh @@ -1,11 +1,17 @@ #!/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-pestore-perl "minor update" +# Usage example: /bin/sh ./git_push.sh wing328 openapi-pestore-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" @@ -37,9 +43,9 @@ 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://github.com/${git_user_id}/${git_repo_id}.git + 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}@github.com/${git_user_id}/${git_repo_id}.git + git remote add origin https://${git_user_id}:${GIT_TOKEN}@${git_host}/${git_user_id}/${git_repo_id}.git fi fi @@ -47,6 +53,6 @@ fi git pull origin master # Pushes (Forces) the changes in the local repository up to the remote repository -echo "Git pushing to https://github.com/${git_user_id}/${git_repo_id}.git" +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/android/httpclient/gradle/wrapper/gradle-wrapper.jar b/samples/client/petstore/android/httpclient/gradle/wrapper/gradle-wrapper.jar index 87b738cbd05..e708b1c023e 100644 Binary files a/samples/client/petstore/android/httpclient/gradle/wrapper/gradle-wrapper.jar and b/samples/client/petstore/android/httpclient/gradle/wrapper/gradle-wrapper.jar differ diff --git a/samples/client/petstore/android/httpclient/gradle/wrapper/gradle-wrapper.properties b/samples/client/petstore/android/httpclient/gradle/wrapper/gradle-wrapper.properties index e496c054f69..4d9ca164914 100644 --- a/samples/client/petstore/android/httpclient/gradle/wrapper/gradle-wrapper.properties +++ b/samples/client/petstore/android/httpclient/gradle/wrapper/gradle-wrapper.properties @@ -1,5 +1,5 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-2.14.1-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-6.7.1-bin.zip zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists diff --git a/samples/client/petstore/android/httpclient/gradlew b/samples/client/petstore/android/httpclient/gradlew index af6708ff229..4f906e0c811 100755 --- a/samples/client/petstore/android/httpclient/gradlew +++ b/samples/client/petstore/android/httpclient/gradlew @@ -1,5 +1,21 @@ #!/usr/bin/env sh +# +# Copyright 2015 the original author or 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 UN*X @@ -28,7 +44,7 @@ APP_NAME="Gradle" APP_BASE_NAME=`basename "$0"` # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -DEFAULT_JVM_OPTS='"-Xmx64m"' +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' # Use the maximum available, or set MAX_FD != -1 to use that value. MAX_FD="maximum" @@ -66,6 +82,7 @@ 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 @@ -109,10 +126,11 @@ if $darwin; then GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" fi -# For Cygwin, switch paths to Windows format before running java -if $cygwin ; then +# 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 @@ -138,19 +156,19 @@ if $cygwin ; then else eval `echo args$i`="\"$arg\"" fi - i=$((i+1)) + i=`expr $i + 1` done case $i in - (0) set -- ;; - (1) set -- "$args0" ;; - (2) set -- "$args0" "$args1" ;; - (3) set -- "$args0" "$args1" "$args2" ;; - (4) set -- "$args0" "$args1" "$args2" "$args3" ;; - (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; - (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; - (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; - (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; - (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + 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 @@ -159,14 +177,9 @@ save () { for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done echo " " } -APP_ARGS=$(save "$@") +APP_ARGS=`save "$@"` # 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" -# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong -if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then - cd "$(dirname "$0")" -fi - exec "$JAVACMD" "$@" diff --git a/samples/client/petstore/android/httpclient/gradlew.bat b/samples/client/petstore/android/httpclient/gradlew.bat index f9553162f12..107acd32c4e 100644 --- a/samples/client/petstore/android/httpclient/gradlew.bat +++ b/samples/client/petstore/android/httpclient/gradlew.bat @@ -1,3 +1,19 @@ +@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 @@ -13,15 +29,18 @@ 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= +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%" == "0" goto init +if "%ERRORLEVEL%" == "0" goto execute echo. echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. @@ -35,7 +54,7 @@ goto fail set JAVA_HOME=%JAVA_HOME:"=% set JAVA_EXE=%JAVA_HOME%/bin/java.exe -if exist "%JAVA_EXE%" goto init +if exist "%JAVA_EXE%" goto execute echo. echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% @@ -45,28 +64,14 @@ echo location of your Java installation. goto fail -:init -@rem Get command-line arguments, handling Windows variants - -if not "%OS%" == "Windows_NT" goto win9xME_args - -:win9xME_args -@rem Slurp the command line arguments. -set CMD_LINE_ARGS= -set _SKIP=2 - -:win9xME_args_slurp -if "x%~1" == "x" goto execute - -set CMD_LINE_ARGS=%* - :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 %CMD_LINE_ARGS% +"%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 diff --git a/samples/client/petstore/android/httpclient/pom.xml b/samples/client/petstore/android/httpclient/pom.xml index 455f6be5ff8..9335f3e0504 100644 --- a/samples/client/petstore/android/httpclient/pom.xml +++ b/samples/client/petstore/android/httpclient/pom.xml @@ -173,9 +173,9 @@ UTF-8 1.5.18 2.3.1 - 4.8.1 + 4.13.1 1.0.0 4.8.1 - 4.3.6 + 4.5.13 diff --git a/samples/client/petstore/android/httpclient/src/main/java/org/openapitools/client/ApiException.java b/samples/client/petstore/android/httpclient/src/main/java/org/openapitools/client/ApiException.java index 7e9a6ef4d56..2e0db8b1bf7 100644 --- a/samples/client/petstore/android/httpclient/src/main/java/org/openapitools/client/ApiException.java +++ b/samples/client/petstore/android/httpclient/src/main/java/org/openapitools/client/ApiException.java @@ -2,7 +2,7 @@ * 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. * - * OpenAPI spec version: 1.0.0 + * The version of the OpenAPI document: 1.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/samples/client/petstore/android/httpclient/src/main/java/org/openapitools/client/ApiInvoker.java b/samples/client/petstore/android/httpclient/src/main/java/org/openapitools/client/ApiInvoker.java index 18403b1972c..fd1eba49be8 100644 --- a/samples/client/petstore/android/httpclient/src/main/java/org/openapitools/client/ApiInvoker.java +++ b/samples/client/petstore/android/httpclient/src/main/java/org/openapitools/client/ApiInvoker.java @@ -2,7 +2,7 @@ * 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. * - * OpenAPI spec version: 1.0.0 + * The version of the OpenAPI document: 1.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/samples/client/petstore/android/httpclient/src/main/java/org/openapitools/client/HttpPatch.java b/samples/client/petstore/android/httpclient/src/main/java/org/openapitools/client/HttpPatch.java index 33fd7b63bd2..5f6c62e79d8 100644 --- a/samples/client/petstore/android/httpclient/src/main/java/org/openapitools/client/HttpPatch.java +++ b/samples/client/petstore/android/httpclient/src/main/java/org/openapitools/client/HttpPatch.java @@ -2,7 +2,7 @@ * 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. * - * OpenAPI spec version: 1.0.0 + * The version of the OpenAPI document: 1.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/samples/client/petstore/android/httpclient/src/main/java/org/openapitools/client/JsonUtil.java b/samples/client/petstore/android/httpclient/src/main/java/org/openapitools/client/JsonUtil.java index 624c820ebce..b603422c4e3 100644 --- a/samples/client/petstore/android/httpclient/src/main/java/org/openapitools/client/JsonUtil.java +++ b/samples/client/petstore/android/httpclient/src/main/java/org/openapitools/client/JsonUtil.java @@ -5,6 +5,7 @@ import com.google.gson.GsonBuilder; import com.google.gson.reflect.TypeToken; import java.lang.reflect.Type; import java.util.List; +import org.openapitools.client.model.*; public class JsonUtil { public static GsonBuilder gsonBuilder; diff --git a/samples/client/petstore/android/httpclient/src/main/java/org/openapitools/client/Pair.java b/samples/client/petstore/android/httpclient/src/main/java/org/openapitools/client/Pair.java index 21a436455a1..06288352310 100644 --- a/samples/client/petstore/android/httpclient/src/main/java/org/openapitools/client/Pair.java +++ b/samples/client/petstore/android/httpclient/src/main/java/org/openapitools/client/Pair.java @@ -2,7 +2,7 @@ * 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. * - * OpenAPI spec version: 1.0.0 + * The version of the OpenAPI document: 1.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/samples/client/petstore/android/httpclient/src/main/java/org/openapitools/client/api/PetApi.java b/samples/client/petstore/android/httpclient/src/main/java/org/openapitools/client/api/PetApi.java index 10e4466ae0b..361994a058f 100644 --- a/samples/client/petstore/android/httpclient/src/main/java/org/openapitools/client/api/PetApi.java +++ b/samples/client/petstore/android/httpclient/src/main/java/org/openapitools/client/api/PetApi.java @@ -2,7 +2,7 @@ * 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. * - * OpenAPI spec version: 1.0.0 + * The version of the OpenAPI document: 1.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). @@ -53,14 +53,14 @@ public class PetApi { /** * Add a new pet to the store * - * @param pet Pet object that needs to be added to the store + * @param body Pet object that needs to be added to the store * @return void */ - public void addPet (Pet pet) throws ApiException { - Object localVarPostBody = pet; - // verify the required parameter 'pet' is set - if (pet == null) { - throw new ApiException(400, "Missing the required parameter 'pet' when calling addPet"); + public void addPet (Pet body) throws ApiException { + Object localVarPostBody = body; + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException(400, "Missing the required parameter 'body' when calling addPet"); } // create path and map variables @@ -317,14 +317,14 @@ public class PetApi { /** * Update an existing pet * - * @param pet Pet object that needs to be added to the store + * @param body Pet object that needs to be added to the store * @return void */ - public void updatePet (Pet pet) throws ApiException { - Object localVarPostBody = pet; - // verify the required parameter 'pet' is set - if (pet == null) { - throw new ApiException(400, "Missing the required parameter 'pet' when calling updatePet"); + public void updatePet (Pet body) throws ApiException { + Object localVarPostBody = body; + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException(400, "Missing the required parameter 'body' when calling updatePet"); } // create path and map variables diff --git a/samples/client/petstore/android/httpclient/src/main/java/org/openapitools/client/api/StoreApi.java b/samples/client/petstore/android/httpclient/src/main/java/org/openapitools/client/api/StoreApi.java index 91dadd5646d..17ad5b2c084 100644 --- a/samples/client/petstore/android/httpclient/src/main/java/org/openapitools/client/api/StoreApi.java +++ b/samples/client/petstore/android/httpclient/src/main/java/org/openapitools/client/api/StoreApi.java @@ -2,7 +2,7 @@ * 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. * - * OpenAPI spec version: 1.0.0 + * The version of the OpenAPI document: 1.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). @@ -203,14 +203,14 @@ public class StoreApi { /** * Place an order for a pet * - * @param order order placed for purchasing the pet + * @param body order placed for purchasing the pet * @return Order */ - public Order placeOrder (Order order) throws ApiException { - Object localVarPostBody = order; - // verify the required parameter 'order' is set - if (order == null) { - throw new ApiException(400, "Missing the required parameter 'order' when calling placeOrder"); + public Order placeOrder (Order body) throws ApiException { + Object localVarPostBody = body; + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException(400, "Missing the required parameter 'body' when calling placeOrder"); } // create path and map variables diff --git a/samples/client/petstore/android/httpclient/src/main/java/org/openapitools/client/api/UserApi.java b/samples/client/petstore/android/httpclient/src/main/java/org/openapitools/client/api/UserApi.java index 6189aff41a3..c6a854dec57 100644 --- a/samples/client/petstore/android/httpclient/src/main/java/org/openapitools/client/api/UserApi.java +++ b/samples/client/petstore/android/httpclient/src/main/java/org/openapitools/client/api/UserApi.java @@ -2,7 +2,7 @@ * 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. * - * OpenAPI spec version: 1.0.0 + * The version of the OpenAPI document: 1.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). @@ -52,14 +52,14 @@ public class UserApi { /** * Create user * This can only be done by the logged in user. - * @param user Created user object + * @param body Created user object * @return void */ - public void createUser (User user) throws ApiException { - Object localVarPostBody = user; - // verify the required parameter 'user' is set - if (user == null) { - throw new ApiException(400, "Missing the required parameter 'user' when calling createUser"); + public void createUser (User body) throws ApiException { + Object localVarPostBody = body; + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException(400, "Missing the required parameter 'body' when calling createUser"); } // create path and map variables @@ -104,14 +104,14 @@ public class UserApi { /** * Creates list of users with given input array * - * @param user List of user object + * @param body List of user object * @return void */ - public void createUsersWithArrayInput (List user) throws ApiException { - Object localVarPostBody = user; - // verify the required parameter 'user' is set - if (user == null) { - throw new ApiException(400, "Missing the required parameter 'user' when calling createUsersWithArrayInput"); + public void createUsersWithArrayInput (List body) throws ApiException { + Object localVarPostBody = body; + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException(400, "Missing the required parameter 'body' when calling createUsersWithArrayInput"); } // create path and map variables @@ -156,14 +156,14 @@ public class UserApi { /** * Creates list of users with given input array * - * @param user List of user object + * @param body List of user object * @return void */ - public void createUsersWithListInput (List user) throws ApiException { - Object localVarPostBody = user; - // verify the required parameter 'user' is set - if (user == null) { - throw new ApiException(400, "Missing the required parameter 'user' when calling createUsersWithListInput"); + public void createUsersWithListInput (List body) throws ApiException { + Object localVarPostBody = body; + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException(400, "Missing the required parameter 'body' when calling createUsersWithListInput"); } // create path and map variables @@ -419,18 +419,18 @@ public class UserApi { * Updated user * This can only be done by the logged in user. * @param username name that need to be deleted - * @param user Updated user object + * @param body Updated user object * @return void */ - public void updateUser (String username, User user) throws ApiException { - Object localVarPostBody = user; + public void updateUser (String username, User body) throws ApiException { + Object localVarPostBody = body; // verify the required parameter 'username' is set if (username == null) { throw new ApiException(400, "Missing the required parameter 'username' when calling updateUser"); } - // verify the required parameter 'user' is set - if (user == null) { - throw new ApiException(400, "Missing the required parameter 'user' when calling updateUser"); + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException(400, "Missing the required parameter 'body' when calling updateUser"); } // create path and map variables diff --git a/samples/client/petstore/android/volley/.openapi-generator/VERSION b/samples/client/petstore/android/volley/.openapi-generator/VERSION index c30f0ec2be7..6555596f931 100644 --- a/samples/client/petstore/android/volley/.openapi-generator/VERSION +++ b/samples/client/petstore/android/volley/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.0-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/apex/.openapi-generator/VERSION b/samples/client/petstore/apex/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/client/petstore/apex/.openapi-generator/VERSION +++ b/samples/client/petstore/apex/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/client/petstore/bash/.openapi-generator/VERSION b/samples/client/petstore/bash/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/client/petstore/bash/.openapi-generator/VERSION +++ b/samples/client/petstore/bash/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/client/petstore/c/.openapi-generator/VERSION b/samples/client/petstore/c/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/client/petstore/c/.openapi-generator/VERSION +++ b/samples/client/petstore/c/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/client/petstore/cpp-qt5/.clang-format b/samples/client/petstore/cpp-qt/.clang-format similarity index 100% rename from samples/client/petstore/cpp-qt5/.clang-format rename to samples/client/petstore/cpp-qt/.clang-format diff --git a/samples/client/petstore/cpp-qt5/.gitignore b/samples/client/petstore/cpp-qt/.gitignore similarity index 100% rename from samples/client/petstore/cpp-qt5/.gitignore rename to samples/client/petstore/cpp-qt/.gitignore diff --git a/samples/client/petstore/cpp-qt5/.openapi-generator-ignore b/samples/client/petstore/cpp-qt/.openapi-generator-ignore similarity index 100% rename from samples/client/petstore/cpp-qt5/.openapi-generator-ignore rename to samples/client/petstore/cpp-qt/.openapi-generator-ignore diff --git a/samples/client/petstore/cpp-qt5/.openapi-generator/FILES b/samples/client/petstore/cpp-qt/.openapi-generator/FILES similarity index 100% rename from samples/client/petstore/cpp-qt5/.openapi-generator/FILES rename to samples/client/petstore/cpp-qt/.openapi-generator/FILES diff --git a/samples/client/petstore/cpp-qt/.openapi-generator/VERSION b/samples/client/petstore/cpp-qt/.openapi-generator/VERSION new file mode 100644 index 00000000000..4b448de535c --- /dev/null +++ b/samples/client/petstore/cpp-qt/.openapi-generator/VERSION @@ -0,0 +1 @@ +5.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/cpp-qt5/CMakeLists.txt b/samples/client/petstore/cpp-qt/CMakeLists.txt similarity index 100% rename from samples/client/petstore/cpp-qt5/CMakeLists.txt rename to samples/client/petstore/cpp-qt/CMakeLists.txt diff --git a/samples/client/petstore/cpp-qt5/PetStore/PetApiTests.cpp b/samples/client/petstore/cpp-qt/PetStore/PetApiTests.cpp similarity index 100% rename from samples/client/petstore/cpp-qt5/PetStore/PetApiTests.cpp rename to samples/client/petstore/cpp-qt/PetStore/PetApiTests.cpp diff --git a/samples/client/petstore/cpp-qt5/PetStore/PetApiTests.h b/samples/client/petstore/cpp-qt/PetStore/PetApiTests.h similarity index 100% rename from samples/client/petstore/cpp-qt5/PetStore/PetApiTests.h rename to samples/client/petstore/cpp-qt/PetStore/PetApiTests.h diff --git a/samples/client/petstore/cpp-qt5/PetStore/PetStore.pro b/samples/client/petstore/cpp-qt/PetStore/PetStore.pro similarity index 100% rename from samples/client/petstore/cpp-qt5/PetStore/PetStore.pro rename to samples/client/petstore/cpp-qt/PetStore/PetStore.pro diff --git a/samples/client/petstore/cpp-qt5/PetStore/StoreApiTests.cpp b/samples/client/petstore/cpp-qt/PetStore/StoreApiTests.cpp similarity index 100% rename from samples/client/petstore/cpp-qt5/PetStore/StoreApiTests.cpp rename to samples/client/petstore/cpp-qt/PetStore/StoreApiTests.cpp diff --git a/samples/client/petstore/cpp-qt5/PetStore/StoreApiTests.h b/samples/client/petstore/cpp-qt/PetStore/StoreApiTests.h similarity index 100% rename from samples/client/petstore/cpp-qt5/PetStore/StoreApiTests.h rename to samples/client/petstore/cpp-qt/PetStore/StoreApiTests.h diff --git a/samples/client/petstore/cpp-qt5/PetStore/UserApiTests.cpp b/samples/client/petstore/cpp-qt/PetStore/UserApiTests.cpp similarity index 100% rename from samples/client/petstore/cpp-qt5/PetStore/UserApiTests.cpp rename to samples/client/petstore/cpp-qt/PetStore/UserApiTests.cpp diff --git a/samples/client/petstore/cpp-qt5/PetStore/UserApiTests.h b/samples/client/petstore/cpp-qt/PetStore/UserApiTests.h similarity index 100% rename from samples/client/petstore/cpp-qt5/PetStore/UserApiTests.h rename to samples/client/petstore/cpp-qt/PetStore/UserApiTests.h diff --git a/samples/client/petstore/cpp-qt5/PetStore/main.cpp b/samples/client/petstore/cpp-qt/PetStore/main.cpp similarity index 100% rename from samples/client/petstore/cpp-qt5/PetStore/main.cpp rename to samples/client/petstore/cpp-qt/PetStore/main.cpp diff --git a/samples/client/petstore/cpp-qt5/README.md b/samples/client/petstore/cpp-qt/README.md similarity index 98% rename from samples/client/petstore/cpp-qt5/README.md rename to samples/client/petstore/cpp-qt/README.md index f72d21e557d..156bb656f1d 100644 --- a/samples/client/petstore/cpp-qt5/README.md +++ b/samples/client/petstore/cpp-qt/README.md @@ -46,10 +46,10 @@ At first generate the JAR by executing: mvn clean package ``` -Use the Jar file to generate the Qt5 Client: +Use the Jar file to generate the Qt Client: ```shell -java -jar target/openapi-generator-cli.jar generate -i -g cpp-qt5-client -o +java -jar target/openapi-generator-cli.jar generate -i -g cpp-qt-client -o ``` ## Getting Started diff --git a/samples/client/petstore/cpp-qt5/build-and-test.bash b/samples/client/petstore/cpp-qt/build-and-test.bash similarity index 100% rename from samples/client/petstore/cpp-qt5/build-and-test.bash rename to samples/client/petstore/cpp-qt/build-and-test.bash diff --git a/samples/client/petstore/cpp-qt5/client/CMakeLists.txt b/samples/client/petstore/cpp-qt/client/CMakeLists.txt similarity index 100% rename from samples/client/petstore/cpp-qt5/client/CMakeLists.txt rename to samples/client/petstore/cpp-qt/client/CMakeLists.txt diff --git a/samples/client/petstore/cpp-qt5/client/PFXApiResponse.cpp b/samples/client/petstore/cpp-qt/client/PFXApiResponse.cpp similarity index 100% rename from samples/client/petstore/cpp-qt5/client/PFXApiResponse.cpp rename to samples/client/petstore/cpp-qt/client/PFXApiResponse.cpp diff --git a/samples/client/petstore/cpp-qt5/client/PFXApiResponse.h b/samples/client/petstore/cpp-qt/client/PFXApiResponse.h similarity index 100% rename from samples/client/petstore/cpp-qt5/client/PFXApiResponse.h rename to samples/client/petstore/cpp-qt/client/PFXApiResponse.h diff --git a/samples/client/petstore/cpp-qt5/client/PFXCategory.cpp b/samples/client/petstore/cpp-qt/client/PFXCategory.cpp similarity index 100% rename from samples/client/petstore/cpp-qt5/client/PFXCategory.cpp rename to samples/client/petstore/cpp-qt/client/PFXCategory.cpp diff --git a/samples/client/petstore/cpp-qt5/client/PFXCategory.h b/samples/client/petstore/cpp-qt/client/PFXCategory.h similarity index 100% rename from samples/client/petstore/cpp-qt5/client/PFXCategory.h rename to samples/client/petstore/cpp-qt/client/PFXCategory.h diff --git a/samples/client/petstore/cpp-qt5/client/PFXEnum.h b/samples/client/petstore/cpp-qt/client/PFXEnum.h similarity index 100% rename from samples/client/petstore/cpp-qt5/client/PFXEnum.h rename to samples/client/petstore/cpp-qt/client/PFXEnum.h diff --git a/samples/client/petstore/cpp-qt5/client/PFXHelpers.cpp b/samples/client/petstore/cpp-qt/client/PFXHelpers.cpp similarity index 100% rename from samples/client/petstore/cpp-qt5/client/PFXHelpers.cpp rename to samples/client/petstore/cpp-qt/client/PFXHelpers.cpp diff --git a/samples/client/petstore/cpp-qt5/client/PFXHelpers.h b/samples/client/petstore/cpp-qt/client/PFXHelpers.h similarity index 100% rename from samples/client/petstore/cpp-qt5/client/PFXHelpers.h rename to samples/client/petstore/cpp-qt/client/PFXHelpers.h diff --git a/samples/client/petstore/cpp-qt5/client/PFXHttpFileElement.cpp b/samples/client/petstore/cpp-qt/client/PFXHttpFileElement.cpp similarity index 100% rename from samples/client/petstore/cpp-qt5/client/PFXHttpFileElement.cpp rename to samples/client/petstore/cpp-qt/client/PFXHttpFileElement.cpp diff --git a/samples/client/petstore/cpp-qt5/client/PFXHttpFileElement.h b/samples/client/petstore/cpp-qt/client/PFXHttpFileElement.h similarity index 100% rename from samples/client/petstore/cpp-qt5/client/PFXHttpFileElement.h rename to samples/client/petstore/cpp-qt/client/PFXHttpFileElement.h diff --git a/samples/client/petstore/cpp-qt5/client/PFXHttpRequest.cpp b/samples/client/petstore/cpp-qt/client/PFXHttpRequest.cpp similarity index 99% rename from samples/client/petstore/cpp-qt5/client/PFXHttpRequest.cpp rename to samples/client/petstore/cpp-qt/client/PFXHttpRequest.cpp index ec16ac8e916..b05c2c19219 100644 --- a/samples/client/petstore/cpp-qt5/client/PFXHttpRequest.cpp +++ b/samples/client/petstore/cpp-qt/client/PFXHttpRequest.cpp @@ -335,7 +335,7 @@ void PFXHttpRequestWorker::execute(PFXHttpRequestInput *input) { if (PFXHttpRequestWorker::sslDefaultConfiguration != nullptr) { request.setSslConfiguration(*PFXHttpRequestWorker::sslDefaultConfiguration); } - request.setRawHeader("User-Agent", "OpenAPI-Generator/1.0.0/cpp-qt5"); + request.setRawHeader("User-Agent", "OpenAPI-Generator/1.0.0/cpp-qt"); foreach (QString key, input->headers.keys()) { request.setRawHeader(key.toStdString().c_str(), input->headers.value(key).toStdString().c_str()); } if (request_content.size() > 0 && !isFormData && (input->var_layout != MULTIPART)) { diff --git a/samples/client/petstore/cpp-qt5/client/PFXHttpRequest.h b/samples/client/petstore/cpp-qt/client/PFXHttpRequest.h similarity index 100% rename from samples/client/petstore/cpp-qt5/client/PFXHttpRequest.h rename to samples/client/petstore/cpp-qt/client/PFXHttpRequest.h diff --git a/samples/client/petstore/cpp-qt5/client/PFXObject.h b/samples/client/petstore/cpp-qt/client/PFXObject.h similarity index 100% rename from samples/client/petstore/cpp-qt5/client/PFXObject.h rename to samples/client/petstore/cpp-qt/client/PFXObject.h diff --git a/samples/client/petstore/cpp-qt5/client/PFXOrder.cpp b/samples/client/petstore/cpp-qt/client/PFXOrder.cpp similarity index 100% rename from samples/client/petstore/cpp-qt5/client/PFXOrder.cpp rename to samples/client/petstore/cpp-qt/client/PFXOrder.cpp diff --git a/samples/client/petstore/cpp-qt5/client/PFXOrder.h b/samples/client/petstore/cpp-qt/client/PFXOrder.h similarity index 100% rename from samples/client/petstore/cpp-qt5/client/PFXOrder.h rename to samples/client/petstore/cpp-qt/client/PFXOrder.h diff --git a/samples/client/petstore/cpp-qt5/client/PFXPet.cpp b/samples/client/petstore/cpp-qt/client/PFXPet.cpp similarity index 100% rename from samples/client/petstore/cpp-qt5/client/PFXPet.cpp rename to samples/client/petstore/cpp-qt/client/PFXPet.cpp diff --git a/samples/client/petstore/cpp-qt5/client/PFXPet.h b/samples/client/petstore/cpp-qt/client/PFXPet.h similarity index 100% rename from samples/client/petstore/cpp-qt5/client/PFXPet.h rename to samples/client/petstore/cpp-qt/client/PFXPet.h diff --git a/samples/client/petstore/cpp-qt5/client/PFXPetApi.cpp b/samples/client/petstore/cpp-qt/client/PFXPetApi.cpp similarity index 100% rename from samples/client/petstore/cpp-qt5/client/PFXPetApi.cpp rename to samples/client/petstore/cpp-qt/client/PFXPetApi.cpp diff --git a/samples/client/petstore/cpp-qt5/client/PFXPetApi.h b/samples/client/petstore/cpp-qt/client/PFXPetApi.h similarity index 100% rename from samples/client/petstore/cpp-qt5/client/PFXPetApi.h rename to samples/client/petstore/cpp-qt/client/PFXPetApi.h diff --git a/samples/client/petstore/cpp-qt5/client/PFXServerConfiguration.h b/samples/client/petstore/cpp-qt/client/PFXServerConfiguration.h similarity index 100% rename from samples/client/petstore/cpp-qt5/client/PFXServerConfiguration.h rename to samples/client/petstore/cpp-qt/client/PFXServerConfiguration.h diff --git a/samples/client/petstore/cpp-qt5/client/PFXServerVariable.h b/samples/client/petstore/cpp-qt/client/PFXServerVariable.h similarity index 100% rename from samples/client/petstore/cpp-qt5/client/PFXServerVariable.h rename to samples/client/petstore/cpp-qt/client/PFXServerVariable.h diff --git a/samples/client/petstore/cpp-qt5/client/PFXStoreApi.cpp b/samples/client/petstore/cpp-qt/client/PFXStoreApi.cpp similarity index 100% rename from samples/client/petstore/cpp-qt5/client/PFXStoreApi.cpp rename to samples/client/petstore/cpp-qt/client/PFXStoreApi.cpp diff --git a/samples/client/petstore/cpp-qt5/client/PFXStoreApi.h b/samples/client/petstore/cpp-qt/client/PFXStoreApi.h similarity index 100% rename from samples/client/petstore/cpp-qt5/client/PFXStoreApi.h rename to samples/client/petstore/cpp-qt/client/PFXStoreApi.h diff --git a/samples/client/petstore/cpp-qt5/client/PFXTag.cpp b/samples/client/petstore/cpp-qt/client/PFXTag.cpp similarity index 100% rename from samples/client/petstore/cpp-qt5/client/PFXTag.cpp rename to samples/client/petstore/cpp-qt/client/PFXTag.cpp diff --git a/samples/client/petstore/cpp-qt5/client/PFXTag.h b/samples/client/petstore/cpp-qt/client/PFXTag.h similarity index 100% rename from samples/client/petstore/cpp-qt5/client/PFXTag.h rename to samples/client/petstore/cpp-qt/client/PFXTag.h diff --git a/samples/client/petstore/cpp-qt5/client/PFXUser.cpp b/samples/client/petstore/cpp-qt/client/PFXUser.cpp similarity index 100% rename from samples/client/petstore/cpp-qt5/client/PFXUser.cpp rename to samples/client/petstore/cpp-qt/client/PFXUser.cpp diff --git a/samples/client/petstore/cpp-qt5/client/PFXUser.h b/samples/client/petstore/cpp-qt/client/PFXUser.h similarity index 100% rename from samples/client/petstore/cpp-qt5/client/PFXUser.h rename to samples/client/petstore/cpp-qt/client/PFXUser.h diff --git a/samples/client/petstore/cpp-qt5/client/PFXUserApi.cpp b/samples/client/petstore/cpp-qt/client/PFXUserApi.cpp similarity index 100% rename from samples/client/petstore/cpp-qt5/client/PFXUserApi.cpp rename to samples/client/petstore/cpp-qt/client/PFXUserApi.cpp diff --git a/samples/client/petstore/cpp-qt5/client/PFXUserApi.h b/samples/client/petstore/cpp-qt/client/PFXUserApi.h similarity index 100% rename from samples/client/petstore/cpp-qt5/client/PFXUserApi.h rename to samples/client/petstore/cpp-qt/client/PFXUserApi.h diff --git a/samples/client/petstore/cpp-qt5/client/PFXclient.pri b/samples/client/petstore/cpp-qt/client/PFXclient.pri similarity index 100% rename from samples/client/petstore/cpp-qt5/client/PFXclient.pri rename to samples/client/petstore/cpp-qt/client/PFXclient.pri diff --git a/samples/client/petstore/cpp-qt5/pom.xml b/samples/client/petstore/cpp-qt/pom.xml similarity index 100% rename from samples/client/petstore/cpp-qt5/pom.xml rename to samples/client/petstore/cpp-qt/pom.xml diff --git a/samples/client/petstore/cpp-restsdk/client/.openapi-generator/VERSION b/samples/client/petstore/cpp-restsdk/client/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/client/petstore/cpp-restsdk/client/.openapi-generator/VERSION +++ b/samples/client/petstore/cpp-restsdk/client/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/client/petstore/cpp-restsdk/client/ApiClient.cpp b/samples/client/petstore/cpp-restsdk/client/ApiClient.cpp index 9ec1a3c1291..b4b88d752fe 100644 --- a/samples/client/petstore/cpp-restsdk/client/ApiClient.cpp +++ b/samples/client/petstore/cpp-restsdk/client/ApiClient.cpp @@ -4,7 +4,11 @@ * * The version of the OpenAPI document: 1.0.0 * +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI-Generator 6.0.0-SNAPSHOT. +======= + * NOTE: This class is auto generated by OpenAPI-Generator 5.3.0-SNAPSHOT. +>>>>>>> origin/5.3.x * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/cpp-restsdk/client/ApiClient.h b/samples/client/petstore/cpp-restsdk/client/ApiClient.h index a6f0ad08b3a..35591953b2a 100644 --- a/samples/client/petstore/cpp-restsdk/client/ApiClient.h +++ b/samples/client/petstore/cpp-restsdk/client/ApiClient.h @@ -4,7 +4,11 @@ * * The version of the OpenAPI document: 1.0.0 * +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI-Generator 6.0.0-SNAPSHOT. +======= + * NOTE: This class is auto generated by OpenAPI-Generator 5.3.0-SNAPSHOT. +>>>>>>> origin/5.3.x * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/cpp-restsdk/client/ApiConfiguration.cpp b/samples/client/petstore/cpp-restsdk/client/ApiConfiguration.cpp index 2be29a96b9a..520c42757ab 100644 --- a/samples/client/petstore/cpp-restsdk/client/ApiConfiguration.cpp +++ b/samples/client/petstore/cpp-restsdk/client/ApiConfiguration.cpp @@ -4,7 +4,11 @@ * * The version of the OpenAPI document: 1.0.0 * +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI-Generator 6.0.0-SNAPSHOT. +======= + * NOTE: This class is auto generated by OpenAPI-Generator 5.3.0-SNAPSHOT. +>>>>>>> origin/5.3.x * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/cpp-restsdk/client/ApiConfiguration.h b/samples/client/petstore/cpp-restsdk/client/ApiConfiguration.h index 791d5fbc12e..acaa0d25ab5 100644 --- a/samples/client/petstore/cpp-restsdk/client/ApiConfiguration.h +++ b/samples/client/petstore/cpp-restsdk/client/ApiConfiguration.h @@ -4,7 +4,11 @@ * * The version of the OpenAPI document: 1.0.0 * +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI-Generator 6.0.0-SNAPSHOT. +======= + * NOTE: This class is auto generated by OpenAPI-Generator 5.3.0-SNAPSHOT. +>>>>>>> origin/5.3.x * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/cpp-restsdk/client/ApiException.cpp b/samples/client/petstore/cpp-restsdk/client/ApiException.cpp index 9df267c0181..876f0759172 100644 --- a/samples/client/petstore/cpp-restsdk/client/ApiException.cpp +++ b/samples/client/petstore/cpp-restsdk/client/ApiException.cpp @@ -4,7 +4,11 @@ * * The version of the OpenAPI document: 1.0.0 * +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI-Generator 6.0.0-SNAPSHOT. +======= + * NOTE: This class is auto generated by OpenAPI-Generator 5.3.0-SNAPSHOT. +>>>>>>> origin/5.3.x * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/cpp-restsdk/client/ApiException.h b/samples/client/petstore/cpp-restsdk/client/ApiException.h index 665ee4f62a9..7972c97aa1e 100644 --- a/samples/client/petstore/cpp-restsdk/client/ApiException.h +++ b/samples/client/petstore/cpp-restsdk/client/ApiException.h @@ -4,7 +4,11 @@ * * The version of the OpenAPI document: 1.0.0 * +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI-Generator 6.0.0-SNAPSHOT. +======= + * NOTE: This class is auto generated by OpenAPI-Generator 5.3.0-SNAPSHOT. +>>>>>>> origin/5.3.x * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/cpp-restsdk/client/HttpContent.cpp b/samples/client/petstore/cpp-restsdk/client/HttpContent.cpp index e21d136df25..c5be624f16e 100644 --- a/samples/client/petstore/cpp-restsdk/client/HttpContent.cpp +++ b/samples/client/petstore/cpp-restsdk/client/HttpContent.cpp @@ -4,7 +4,11 @@ * * The version of the OpenAPI document: 1.0.0 * +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI-Generator 6.0.0-SNAPSHOT. +======= + * NOTE: This class is auto generated by OpenAPI-Generator 5.3.0-SNAPSHOT. +>>>>>>> origin/5.3.x * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/cpp-restsdk/client/HttpContent.h b/samples/client/petstore/cpp-restsdk/client/HttpContent.h index 28cb37a8fe5..1e5ed53d2cb 100644 --- a/samples/client/petstore/cpp-restsdk/client/HttpContent.h +++ b/samples/client/petstore/cpp-restsdk/client/HttpContent.h @@ -4,7 +4,11 @@ * * The version of the OpenAPI document: 1.0.0 * +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI-Generator 6.0.0-SNAPSHOT. +======= + * NOTE: This class is auto generated by OpenAPI-Generator 5.3.0-SNAPSHOT. +>>>>>>> origin/5.3.x * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/cpp-restsdk/client/IHttpBody.h b/samples/client/petstore/cpp-restsdk/client/IHttpBody.h index 7ce2577f5be..7fe675d8ff2 100644 --- a/samples/client/petstore/cpp-restsdk/client/IHttpBody.h +++ b/samples/client/petstore/cpp-restsdk/client/IHttpBody.h @@ -4,7 +4,11 @@ * * The version of the OpenAPI document: 1.0.0 * +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI-Generator 6.0.0-SNAPSHOT. +======= + * NOTE: This class is auto generated by OpenAPI-Generator 5.3.0-SNAPSHOT. +>>>>>>> origin/5.3.x * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/cpp-restsdk/client/JsonBody.cpp b/samples/client/petstore/cpp-restsdk/client/JsonBody.cpp index 5d03753cfff..ee3bf94e2e2 100644 --- a/samples/client/petstore/cpp-restsdk/client/JsonBody.cpp +++ b/samples/client/petstore/cpp-restsdk/client/JsonBody.cpp @@ -4,7 +4,11 @@ * * The version of the OpenAPI document: 1.0.0 * +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI-Generator 6.0.0-SNAPSHOT. +======= + * NOTE: This class is auto generated by OpenAPI-Generator 5.3.0-SNAPSHOT. +>>>>>>> origin/5.3.x * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/cpp-restsdk/client/JsonBody.h b/samples/client/petstore/cpp-restsdk/client/JsonBody.h index 7700434e8c3..5384d885c99 100644 --- a/samples/client/petstore/cpp-restsdk/client/JsonBody.h +++ b/samples/client/petstore/cpp-restsdk/client/JsonBody.h @@ -4,7 +4,11 @@ * * The version of the OpenAPI document: 1.0.0 * +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI-Generator 6.0.0-SNAPSHOT. +======= + * NOTE: This class is auto generated by OpenAPI-Generator 5.3.0-SNAPSHOT. +>>>>>>> origin/5.3.x * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/cpp-restsdk/client/ModelBase.cpp b/samples/client/petstore/cpp-restsdk/client/ModelBase.cpp index 2e542efd6a7..ec8be5072af 100644 --- a/samples/client/petstore/cpp-restsdk/client/ModelBase.cpp +++ b/samples/client/petstore/cpp-restsdk/client/ModelBase.cpp @@ -4,7 +4,11 @@ * * The version of the OpenAPI document: 1.0.0 * +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI-Generator 6.0.0-SNAPSHOT. +======= + * NOTE: This class is auto generated by OpenAPI-Generator 5.3.0-SNAPSHOT. +>>>>>>> origin/5.3.x * https://openapi-generator.tech * Do not edit the class manually. */ @@ -260,13 +264,13 @@ bool ModelBase::fromJson( const web::json::value& val, bool & outVal ) } bool ModelBase::fromJson( const web::json::value& val, float & outVal ) { - outVal = !val.is_double() ? std::numeric_limits::quiet_NaN(): static_cast(val.as_double()); - return val.is_double(); + outVal = (!val.is_double() && !val.is_integer()) ? std::numeric_limits::quiet_NaN(): static_cast(val.as_double()); + return val.is_double() || val.is_integer(); } bool ModelBase::fromJson( const web::json::value& val, double & outVal ) { - outVal = !val.is_double() ? std::numeric_limits::quiet_NaN(): val.as_double(); - return val.is_double() ; + outVal = (!val.is_double() && !val.is_integer()) ? std::numeric_limits::quiet_NaN(): val.as_double(); + return val.is_double() || val.is_integer(); } bool ModelBase::fromJson( const web::json::value& val, int32_t & outVal ) { diff --git a/samples/client/petstore/cpp-restsdk/client/ModelBase.h b/samples/client/petstore/cpp-restsdk/client/ModelBase.h index 33f1f0977ac..bec272866c9 100644 --- a/samples/client/petstore/cpp-restsdk/client/ModelBase.h +++ b/samples/client/petstore/cpp-restsdk/client/ModelBase.h @@ -4,7 +4,11 @@ * * The version of the OpenAPI document: 1.0.0 * +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI-Generator 6.0.0-SNAPSHOT. +======= + * NOTE: This class is auto generated by OpenAPI-Generator 5.3.0-SNAPSHOT. +>>>>>>> origin/5.3.x * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/cpp-restsdk/client/MultipartFormData.cpp b/samples/client/petstore/cpp-restsdk/client/MultipartFormData.cpp index 7af87c42e37..5d6d39ffa9a 100644 --- a/samples/client/petstore/cpp-restsdk/client/MultipartFormData.cpp +++ b/samples/client/petstore/cpp-restsdk/client/MultipartFormData.cpp @@ -4,7 +4,11 @@ * * The version of the OpenAPI document: 1.0.0 * +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI-Generator 6.0.0-SNAPSHOT. +======= + * NOTE: This class is auto generated by OpenAPI-Generator 5.3.0-SNAPSHOT. +>>>>>>> origin/5.3.x * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/cpp-restsdk/client/MultipartFormData.h b/samples/client/petstore/cpp-restsdk/client/MultipartFormData.h index 0e25caef84b..0b2773b91d8 100644 --- a/samples/client/petstore/cpp-restsdk/client/MultipartFormData.h +++ b/samples/client/petstore/cpp-restsdk/client/MultipartFormData.h @@ -4,7 +4,11 @@ * * The version of the OpenAPI document: 1.0.0 * +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI-Generator 6.0.0-SNAPSHOT. +======= + * NOTE: This class is auto generated by OpenAPI-Generator 5.3.0-SNAPSHOT. +>>>>>>> origin/5.3.x * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/cpp-restsdk/client/Object.cpp b/samples/client/petstore/cpp-restsdk/client/Object.cpp index 620e9e30e80..649af998f24 100644 --- a/samples/client/petstore/cpp-restsdk/client/Object.cpp +++ b/samples/client/petstore/cpp-restsdk/client/Object.cpp @@ -4,7 +4,11 @@ * * The version of the OpenAPI document: 1.0.0 * +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI-Generator 6.0.0-SNAPSHOT. +======= + * NOTE: This class is auto generated by OpenAPI-Generator 5.3.0-SNAPSHOT. +>>>>>>> origin/5.3.x * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/cpp-restsdk/client/Object.h b/samples/client/petstore/cpp-restsdk/client/Object.h index 8dc027cb4df..3b318b8b69b 100644 --- a/samples/client/petstore/cpp-restsdk/client/Object.h +++ b/samples/client/petstore/cpp-restsdk/client/Object.h @@ -4,7 +4,11 @@ * * The version of the OpenAPI document: 1.0.0 * +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI-Generator 6.0.0-SNAPSHOT. +======= + * NOTE: This class is auto generated by OpenAPI-Generator 5.3.0-SNAPSHOT. +>>>>>>> origin/5.3.x * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/cpp-restsdk/client/api/PetApi.cpp b/samples/client/petstore/cpp-restsdk/client/api/PetApi.cpp index 7c7b63f1804..ce2ea7e7629 100644 --- a/samples/client/petstore/cpp-restsdk/client/api/PetApi.cpp +++ b/samples/client/petstore/cpp-restsdk/client/api/PetApi.cpp @@ -4,7 +4,11 @@ * * The version of the OpenAPI document: 1.0.0 * +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI-Generator 6.0.0-SNAPSHOT. +======= + * NOTE: This class is auto generated by OpenAPI-Generator 5.3.0-SNAPSHOT. +>>>>>>> origin/5.3.x * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/cpp-restsdk/client/api/PetApi.h b/samples/client/petstore/cpp-restsdk/client/api/PetApi.h index 52d61688482..a6b5d6cbe2f 100644 --- a/samples/client/petstore/cpp-restsdk/client/api/PetApi.h +++ b/samples/client/petstore/cpp-restsdk/client/api/PetApi.h @@ -4,7 +4,11 @@ * * The version of the OpenAPI document: 1.0.0 * +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI-Generator 6.0.0-SNAPSHOT. +======= + * NOTE: This class is auto generated by OpenAPI-Generator 5.3.0-SNAPSHOT. +>>>>>>> origin/5.3.x * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/cpp-restsdk/client/api/StoreApi.cpp b/samples/client/petstore/cpp-restsdk/client/api/StoreApi.cpp index 7d347ca96d9..9a83aaca40d 100644 --- a/samples/client/petstore/cpp-restsdk/client/api/StoreApi.cpp +++ b/samples/client/petstore/cpp-restsdk/client/api/StoreApi.cpp @@ -4,7 +4,11 @@ * * The version of the OpenAPI document: 1.0.0 * +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI-Generator 6.0.0-SNAPSHOT. +======= + * NOTE: This class is auto generated by OpenAPI-Generator 5.3.0-SNAPSHOT. +>>>>>>> origin/5.3.x * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/cpp-restsdk/client/api/StoreApi.h b/samples/client/petstore/cpp-restsdk/client/api/StoreApi.h index 89ccea78d06..e11d78a4967 100644 --- a/samples/client/petstore/cpp-restsdk/client/api/StoreApi.h +++ b/samples/client/petstore/cpp-restsdk/client/api/StoreApi.h @@ -4,7 +4,11 @@ * * The version of the OpenAPI document: 1.0.0 * +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI-Generator 6.0.0-SNAPSHOT. +======= + * NOTE: This class is auto generated by OpenAPI-Generator 5.3.0-SNAPSHOT. +>>>>>>> origin/5.3.x * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/cpp-restsdk/client/api/UserApi.cpp b/samples/client/petstore/cpp-restsdk/client/api/UserApi.cpp index 1ad3d50f0d5..a82924ffef0 100644 --- a/samples/client/petstore/cpp-restsdk/client/api/UserApi.cpp +++ b/samples/client/petstore/cpp-restsdk/client/api/UserApi.cpp @@ -4,7 +4,11 @@ * * The version of the OpenAPI document: 1.0.0 * +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI-Generator 6.0.0-SNAPSHOT. +======= + * NOTE: This class is auto generated by OpenAPI-Generator 5.3.0-SNAPSHOT. +>>>>>>> origin/5.3.x * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/cpp-restsdk/client/api/UserApi.h b/samples/client/petstore/cpp-restsdk/client/api/UserApi.h index 943d13757ea..40e4cd6deba 100644 --- a/samples/client/petstore/cpp-restsdk/client/api/UserApi.h +++ b/samples/client/petstore/cpp-restsdk/client/api/UserApi.h @@ -4,7 +4,11 @@ * * The version of the OpenAPI document: 1.0.0 * +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI-Generator 6.0.0-SNAPSHOT. +======= + * NOTE: This class is auto generated by OpenAPI-Generator 5.3.0-SNAPSHOT. +>>>>>>> origin/5.3.x * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/cpp-restsdk/client/model/ApiResponse.cpp b/samples/client/petstore/cpp-restsdk/client/model/ApiResponse.cpp index 240b8ca1682..4538885e5e2 100644 --- a/samples/client/petstore/cpp-restsdk/client/model/ApiResponse.cpp +++ b/samples/client/petstore/cpp-restsdk/client/model/ApiResponse.cpp @@ -4,7 +4,11 @@ * * The version of the OpenAPI document: 1.0.0 * +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI-Generator 6.0.0-SNAPSHOT. +======= + * NOTE: This class is auto generated by OpenAPI-Generator 5.3.0-SNAPSHOT. +>>>>>>> origin/5.3.x * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/cpp-restsdk/client/model/ApiResponse.h b/samples/client/petstore/cpp-restsdk/client/model/ApiResponse.h index aa992da1771..9073577a144 100644 --- a/samples/client/petstore/cpp-restsdk/client/model/ApiResponse.h +++ b/samples/client/petstore/cpp-restsdk/client/model/ApiResponse.h @@ -4,7 +4,11 @@ * * The version of the OpenAPI document: 1.0.0 * +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI-Generator 6.0.0-SNAPSHOT. +======= + * NOTE: This class is auto generated by OpenAPI-Generator 5.3.0-SNAPSHOT. +>>>>>>> origin/5.3.x * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/cpp-restsdk/client/model/Category.cpp b/samples/client/petstore/cpp-restsdk/client/model/Category.cpp index 2cbfe4ed64d..1fadd278e6e 100644 --- a/samples/client/petstore/cpp-restsdk/client/model/Category.cpp +++ b/samples/client/petstore/cpp-restsdk/client/model/Category.cpp @@ -4,7 +4,11 @@ * * The version of the OpenAPI document: 1.0.0 * +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI-Generator 6.0.0-SNAPSHOT. +======= + * NOTE: This class is auto generated by OpenAPI-Generator 5.3.0-SNAPSHOT. +>>>>>>> origin/5.3.x * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/cpp-restsdk/client/model/Category.h b/samples/client/petstore/cpp-restsdk/client/model/Category.h index 7a0e66e8538..e5640bd4664 100644 --- a/samples/client/petstore/cpp-restsdk/client/model/Category.h +++ b/samples/client/petstore/cpp-restsdk/client/model/Category.h @@ -4,7 +4,11 @@ * * The version of the OpenAPI document: 1.0.0 * +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI-Generator 6.0.0-SNAPSHOT. +======= + * NOTE: This class is auto generated by OpenAPI-Generator 5.3.0-SNAPSHOT. +>>>>>>> origin/5.3.x * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/cpp-restsdk/client/model/Order.cpp b/samples/client/petstore/cpp-restsdk/client/model/Order.cpp index 0533c250bd7..5312c11f010 100644 --- a/samples/client/petstore/cpp-restsdk/client/model/Order.cpp +++ b/samples/client/petstore/cpp-restsdk/client/model/Order.cpp @@ -4,7 +4,11 @@ * * The version of the OpenAPI document: 1.0.0 * +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI-Generator 6.0.0-SNAPSHOT. +======= + * NOTE: This class is auto generated by OpenAPI-Generator 5.3.0-SNAPSHOT. +>>>>>>> origin/5.3.x * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/cpp-restsdk/client/model/Order.h b/samples/client/petstore/cpp-restsdk/client/model/Order.h index f6fa17a75d5..f14b2bbf49f 100644 --- a/samples/client/petstore/cpp-restsdk/client/model/Order.h +++ b/samples/client/petstore/cpp-restsdk/client/model/Order.h @@ -4,7 +4,11 @@ * * The version of the OpenAPI document: 1.0.0 * +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI-Generator 6.0.0-SNAPSHOT. +======= + * NOTE: This class is auto generated by OpenAPI-Generator 5.3.0-SNAPSHOT. +>>>>>>> origin/5.3.x * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/cpp-restsdk/client/model/Pet.cpp b/samples/client/petstore/cpp-restsdk/client/model/Pet.cpp index 8a52519bd6a..57af78e51cd 100644 --- a/samples/client/petstore/cpp-restsdk/client/model/Pet.cpp +++ b/samples/client/petstore/cpp-restsdk/client/model/Pet.cpp @@ -4,7 +4,11 @@ * * The version of the OpenAPI document: 1.0.0 * +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI-Generator 6.0.0-SNAPSHOT. +======= + * NOTE: This class is auto generated by OpenAPI-Generator 5.3.0-SNAPSHOT. +>>>>>>> origin/5.3.x * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/cpp-restsdk/client/model/Pet.h b/samples/client/petstore/cpp-restsdk/client/model/Pet.h index 581042fa91d..4ce48bb628a 100644 --- a/samples/client/petstore/cpp-restsdk/client/model/Pet.h +++ b/samples/client/petstore/cpp-restsdk/client/model/Pet.h @@ -4,7 +4,11 @@ * * The version of the OpenAPI document: 1.0.0 * +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI-Generator 6.0.0-SNAPSHOT. +======= + * NOTE: This class is auto generated by OpenAPI-Generator 5.3.0-SNAPSHOT. +>>>>>>> origin/5.3.x * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/cpp-restsdk/client/model/Tag.cpp b/samples/client/petstore/cpp-restsdk/client/model/Tag.cpp index f7cec46aa43..6ea4ce4f37a 100644 --- a/samples/client/petstore/cpp-restsdk/client/model/Tag.cpp +++ b/samples/client/petstore/cpp-restsdk/client/model/Tag.cpp @@ -4,7 +4,11 @@ * * The version of the OpenAPI document: 1.0.0 * +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI-Generator 6.0.0-SNAPSHOT. +======= + * NOTE: This class is auto generated by OpenAPI-Generator 5.3.0-SNAPSHOT. +>>>>>>> origin/5.3.x * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/cpp-restsdk/client/model/Tag.h b/samples/client/petstore/cpp-restsdk/client/model/Tag.h index 3dac8f1f790..0cd036a86f3 100644 --- a/samples/client/petstore/cpp-restsdk/client/model/Tag.h +++ b/samples/client/petstore/cpp-restsdk/client/model/Tag.h @@ -4,7 +4,11 @@ * * The version of the OpenAPI document: 1.0.0 * +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI-Generator 6.0.0-SNAPSHOT. +======= + * NOTE: This class is auto generated by OpenAPI-Generator 5.3.0-SNAPSHOT. +>>>>>>> origin/5.3.x * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/cpp-restsdk/client/model/User.cpp b/samples/client/petstore/cpp-restsdk/client/model/User.cpp index d0981f41ccd..e686817a29f 100644 --- a/samples/client/petstore/cpp-restsdk/client/model/User.cpp +++ b/samples/client/petstore/cpp-restsdk/client/model/User.cpp @@ -4,7 +4,11 @@ * * The version of the OpenAPI document: 1.0.0 * +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI-Generator 6.0.0-SNAPSHOT. +======= + * NOTE: This class is auto generated by OpenAPI-Generator 5.3.0-SNAPSHOT. +>>>>>>> origin/5.3.x * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/cpp-restsdk/client/model/User.h b/samples/client/petstore/cpp-restsdk/client/model/User.h index 757a48ae8a7..b2e8acb922d 100644 --- a/samples/client/petstore/cpp-restsdk/client/model/User.h +++ b/samples/client/petstore/cpp-restsdk/client/model/User.h @@ -4,7 +4,11 @@ * * The version of the OpenAPI document: 1.0.0 * +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI-Generator 6.0.0-SNAPSHOT. +======= + * NOTE: This class is auto generated by OpenAPI-Generator 5.3.0-SNAPSHOT. +>>>>>>> origin/5.3.x * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/openapi3/server/petstore/php-mezzio-ph/.openapi-generator-ignore b/samples/client/petstore/cpp-tiny/.openapi-generator-ignore similarity index 100% rename from samples/openapi3/server/petstore/php-mezzio-ph/.openapi-generator-ignore rename to samples/client/petstore/cpp-tiny/.openapi-generator-ignore diff --git a/samples/client/petstore/cpp-tiny/.openapi-generator/FILES b/samples/client/petstore/cpp-tiny/.openapi-generator/FILES new file mode 100644 index 00000000000..1024d945064 --- /dev/null +++ b/samples/client/petstore/cpp-tiny/.openapi-generator/FILES @@ -0,0 +1,30 @@ +README.md +README.md +lib/Models/ApiResponse.cpp +lib/Models/ApiResponse.h +lib/Models/Category.cpp +lib/Models/Category.h +lib/Models/Helpers.cpp +lib/Models/Helpers.h +lib/Models/Order.cpp +lib/Models/Order.h +lib/Models/Pet.cpp +lib/Models/Pet.h +lib/Models/Tag.cpp +lib/Models/Tag.h +lib/Models/User.cpp +lib/Models/User.h +lib/service/AbstractService.cpp +lib/service/AbstractService.h +lib/service/PetApi.cpp +lib/service/PetApi.h +lib/service/Response.h +lib/service/StoreApi.cpp +lib/service/StoreApi.h +lib/service/UserApi.cpp +lib/service/UserApi.h +platformio.ini +pre_compiling_bourne.py +root.cert +src/main.cpp +test/RunTests.cpp diff --git a/samples/client/petstore/cpp-tiny/.openapi-generator/VERSION b/samples/client/petstore/cpp-tiny/.openapi-generator/VERSION new file mode 100644 index 00000000000..4b448de535c --- /dev/null +++ b/samples/client/petstore/cpp-tiny/.openapi-generator/VERSION @@ -0,0 +1 @@ +5.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/cpp-tiny/README.md b/samples/client/petstore/cpp-tiny/README.md new file mode 100644 index 00000000000..e8bf721275b --- /dev/null +++ b/samples/client/petstore/cpp-tiny/README.md @@ -0,0 +1,73 @@ +# Documentation for OpenAPI Petstore +This is a client generator for microcontrollers on the Espressif32 platform and the Arduino framework +After the client have been generated, you have to change these following variablies: +- root.cert | Provide your service root certificate. +- src/main.cpp | Change wifi name +- src/main.cpp | Change wifi password +- lib/service/AbstractService.h | Change to your url + +# Documentation for OpenAPI Petstore 1.0.0 Tiny client cpp (Arduino) + +The project is structured like this: +``` +samples/client/petstore/tiny/cpp/ +├── lib +│ ├── Models +│ ├── service +│ └── TestFiles +├── platformio.ini +├── pre_compiling_bourne.py +├── README.md +├── root.cert +├── src +│ └── main.cpp +└── test + └── RunTests.cpp +``` + +All URIs are relative to http://petstore.swagger.iohttp://petstore.swagger.io/v2 + +### PetApi +|Method | HTTP request | Description| +|------------- | ------------- | -------------| +|*addPet* | *POST* /pet | Add a new pet to the store.| +|*deletePet* | *DELETE* /pet/{petId} | Deletes a pet.| +|*findPetsByStatus* | *GET* /pet/findByStatus | Finds Pets by status.| +|*findPetsByTags* | *GET* /pet/findByTags | Finds Pets by tags.| +|*getPetById* | *GET* /pet/{petId} | Find pet by ID.| +|*updatePet* | *PUT* /pet | Update an existing pet.| +|*updatePetWithForm* | *POST* /pet/{petId} | Updates a pet in the store with form data.| +|*uploadFile* | *POST* /pet/{petId}/uploadImage | uploads an image.| + +### StoreApi +|Method | HTTP request | Description| +|------------- | ------------- | -------------| +|*deleteOrder* | *DELETE* /store/order/{orderId} | Delete purchase order by ID.| +|*getInventory* | *GET* /store/inventory | Returns pet inventories by status.| +|*getOrderById* | *GET* /store/order/{orderId} | Find purchase order by ID.| +|*placeOrder* | *POST* /store/order | Place an order for a pet.| + +### UserApi +|Method | HTTP request | Description| +|------------- | ------------- | -------------| +|*createUser* | *POST* /user | Create user.| +|*createUsersWithArrayInput* | *POST* /user/createWithArray | Creates list of users with given input array.| +|*createUsersWithListInput* | *POST* /user/createWithList | Creates list of users with given input array.| +|*deleteUser* | *DELETE* /user/{username} | Delete user.| +|*getUserByName* | *GET* /user/{username} | Get user by user name.| +|*loginUser* | *GET* /user/login | Logs user into the system.| +|*logoutUser* | *GET* /user/logout | Logs out current logged in user session.| +|*updateUser* | *PUT* /user/{username} | Updated user.| + + +## What are the Model files for the data structures/objects? +|Class | Description| +|------------- | -------------| +|*ApiResponse* | Describes the result of uploading an image resource| +|*Category* | A category for a pet| +|*Order* | An order for a pets from the pet store| +|*Pet* | A pet for sale in the pet store| +|*Tag* | A tag for a pet| +|*User* | A User who is purchasing from the pet store| + + diff --git a/samples/client/petstore/cpp-tiny/lib/Models/ApiResponse.cpp b/samples/client/petstore/cpp-tiny/lib/Models/ApiResponse.cpp new file mode 100644 index 00000000000..e9be9e2b618 --- /dev/null +++ b/samples/client/petstore/cpp-tiny/lib/Models/ApiResponse.cpp @@ -0,0 +1,139 @@ + + +#include "ApiResponse.h" + +using namespace Tiny; + +ApiResponse::ApiResponse() +{ + code = int(0); + type = std::string(); + message = std::string(); +} + +ApiResponse::ApiResponse(std::string jsonString) +{ + this->fromJson(jsonString); +} + +ApiResponse::~ApiResponse() +{ + +} + +void +ApiResponse::fromJson(std::string jsonObj) +{ + bourne::json object = bourne::json::parse(jsonObj); + + const char *codeKey = "code"; + + if(object.has_key(codeKey)) + { + bourne::json value = object[codeKey]; + + + + jsonToValue(&code, value, "int"); + + + } + + const char *typeKey = "type"; + + if(object.has_key(typeKey)) + { + bourne::json value = object[typeKey]; + + + + jsonToValue(&type, value, "std::string"); + + + } + + const char *messageKey = "message"; + + if(object.has_key(messageKey)) + { + bourne::json value = object[messageKey]; + + + + jsonToValue(&message, value, "std::string"); + + + } + + +} + +bourne::json +ApiResponse::toJson() +{ + bourne::json object = bourne::json::object(); + + + + + + object["code"] = getCode(); + + + + + + + object["type"] = getType(); + + + + + + + object["message"] = getMessage(); + + + + return object; + +} + +int +ApiResponse::getCode() +{ + return code; +} + +void +ApiResponse::setCode(int code) +{ + this->code = code; +} + +std::string +ApiResponse::getType() +{ + return type; +} + +void +ApiResponse::setType(std::string type) +{ + this->type = type; +} + +std::string +ApiResponse::getMessage() +{ + return message; +} + +void +ApiResponse::setMessage(std::string message) +{ + this->message = message; +} + + + diff --git a/samples/client/petstore/cpp-tiny/lib/Models/ApiResponse.h b/samples/client/petstore/cpp-tiny/lib/Models/ApiResponse.h new file mode 100644 index 00000000000..dbaf8abcaf3 --- /dev/null +++ b/samples/client/petstore/cpp-tiny/lib/Models/ApiResponse.h @@ -0,0 +1,78 @@ + +/* + * ApiResponse.h + * + * Describes the result of uploading an image resource + */ + +#ifndef TINY_CPP_CLIENT_ApiResponse_H_ +#define TINY_CPP_CLIENT_ApiResponse_H_ + + +#include +#include "bourne/json.hpp" +#include "Helpers.h" + +namespace Tiny { + + +/*! \brief Describes the result of uploading an image resource + * + * \ingroup Models + * + */ + +class ApiResponse{ +public: + + /*! \brief Constructor. + */ + ApiResponse(); + ApiResponse(std::string jsonString); + + + /*! \brief Destructor. + */ + virtual ~ApiResponse(); + + + /*! \brief Retrieve a bourne JSON representation of this class. + */ + bourne::json toJson(); + + + /*! \brief Fills in members of this class from bourne JSON object representing it. + */ + void fromJson(std::string jsonObj); + + /*! \brief Get + */ + int getCode(); + + /*! \brief Set + */ + void setCode(int code); + /*! \brief Get + */ + std::string getType(); + + /*! \brief Set + */ + void setType(std::string type); + /*! \brief Get + */ + std::string getMessage(); + + /*! \brief Set + */ + void setMessage(std::string message); + + + private: + int code{}; + std::string type{}; + std::string message{}; +}; +} + +#endif /* TINY_CPP_CLIENT_ApiResponse_H_ */ diff --git a/samples/client/petstore/cpp-tiny/lib/Models/Category.cpp b/samples/client/petstore/cpp-tiny/lib/Models/Category.cpp new file mode 100644 index 00000000000..950b06ffd44 --- /dev/null +++ b/samples/client/petstore/cpp-tiny/lib/Models/Category.cpp @@ -0,0 +1,106 @@ + + +#include "Category.h" + +using namespace Tiny; + +Category::Category() +{ + id = long(0); + name = std::string(); +} + +Category::Category(std::string jsonString) +{ + this->fromJson(jsonString); +} + +Category::~Category() +{ + +} + +void +Category::fromJson(std::string jsonObj) +{ + bourne::json object = bourne::json::parse(jsonObj); + + const char *idKey = "id"; + + if(object.has_key(idKey)) + { + bourne::json value = object[idKey]; + + + + jsonToValue(&id, value, "long"); + + + } + + const char *nameKey = "name"; + + if(object.has_key(nameKey)) + { + bourne::json value = object[nameKey]; + + + + jsonToValue(&name, value, "std::string"); + + + } + + +} + +bourne::json +Category::toJson() +{ + bourne::json object = bourne::json::object(); + + + + + + object["id"] = getId(); + + + + + + + object["name"] = getName(); + + + + return object; + +} + +long +Category::getId() +{ + return id; +} + +void +Category::setId(long id) +{ + this->id = id; +} + +std::string +Category::getName() +{ + return name; +} + +void +Category::setName(std::string name) +{ + this->name = name; +} + + + diff --git a/samples/client/petstore/cpp-tiny/lib/Models/Category.h b/samples/client/petstore/cpp-tiny/lib/Models/Category.h new file mode 100644 index 00000000000..9c90e3dd416 --- /dev/null +++ b/samples/client/petstore/cpp-tiny/lib/Models/Category.h @@ -0,0 +1,70 @@ + +/* + * Category.h + * + * A category for a pet + */ + +#ifndef TINY_CPP_CLIENT_Category_H_ +#define TINY_CPP_CLIENT_Category_H_ + + +#include +#include "bourne/json.hpp" +#include "Helpers.h" + +namespace Tiny { + + +/*! \brief A category for a pet + * + * \ingroup Models + * + */ + +class Category{ +public: + + /*! \brief Constructor. + */ + Category(); + Category(std::string jsonString); + + + /*! \brief Destructor. + */ + virtual ~Category(); + + + /*! \brief Retrieve a bourne JSON representation of this class. + */ + bourne::json toJson(); + + + /*! \brief Fills in members of this class from bourne JSON object representing it. + */ + void fromJson(std::string jsonObj); + + /*! \brief Get + */ + long getId(); + + /*! \brief Set + */ + void setId(long id); + /*! \brief Get + */ + std::string getName(); + + /*! \brief Set + */ + void setName(std::string name); + + + private: + long id{}; + std::string name{}; +}; +} + +#endif /* TINY_CPP_CLIENT_Category_H_ */ diff --git a/samples/client/petstore/cpp-tiny/lib/Models/Helpers.cpp b/samples/client/petstore/cpp-tiny/lib/Models/Helpers.cpp new file mode 100644 index 00000000000..c3935b37cde --- /dev/null +++ b/samples/client/petstore/cpp-tiny/lib/Models/Helpers.cpp @@ -0,0 +1,102 @@ +#include "Helpers.h" +#include +#include + +bool isprimitive(std::string type){ + if(type == "std::string" || + type == "int" || + type == "float" || + type == "long" || + type == "double" || + type == "bool" || + type == "std::map" || + type == "std::list") + { + return true; + } + return false; +} + + +void +jsonToValue(void* target, bourne::json value, std::string type) +{ + if (target == NULL || value.is_null()) { + return; + } + + else if (type.compare("bool") == 0) + { + bool* val = static_cast (target); + *val = value.to_bool(); + } + + else if (type.compare("int") == 0) + { + int* val = static_cast (target); + *val = value.to_int(); + } + + else if (type.compare("float") == 0) + { + float* val = static_cast (target); + *val = (float)(value.to_float()); + } + + else if (type.compare("long") == 0) + { + long* val = static_cast (target); + *val = (long)(value.to_int()); + } + + else if (type.compare("double") == 0) + { + double* val = static_cast (target); + *val = value.to_float(); + } + + else if (type.compare("std::string") == 0) + { + std::string* val = static_cast (target); + *val = value.to_string(); + } + else { + return; + } +} + +std::string +stringify(long input){ + std::stringstream stream; + stream << input; + return stream.str(); + +}; + +std::string +stringify(int input){ + std::stringstream stream; + stream << input; + return stream.str(); +}; + +std::string +stringify(double input){ + std::stringstream stream; + stream << input; + return stream.str(); +}; + +std::string +stringify(float input){ + std::stringstream stream; + stream << input; + return stream.str(); +}; + +std::string +stringify(std::string input){ + std::stringstream stream; + stream << input; + return stream.str(); +}; diff --git a/samples/client/petstore/cpp-tiny/lib/Models/Helpers.h b/samples/client/petstore/cpp-tiny/lib/Models/Helpers.h new file mode 100644 index 00000000000..5ef7d9afdf7 --- /dev/null +++ b/samples/client/petstore/cpp-tiny/lib/Models/Helpers.h @@ -0,0 +1,22 @@ +#ifndef TINY_CPP_CLIENT_HELPERS_H_ +#define TINY_CPP_CLIENT_HELPERS_H_ + +#include +#include "bourne/json.hpp" + +bool isprimitive(std::string type); + +void jsonToValue(void* target, bourne::json value, std::string type); + +std::string stringify(long input); + +std::string stringify(int input); + +std::string stringify(double input); + +std::string stringify(float input); + +std::string stringify(std::string input); + +#endif /* TINY_CPP_CLIENT_HELPERS_H_ */ + diff --git a/samples/client/petstore/cpp-tiny/lib/Models/Order.cpp b/samples/client/petstore/cpp-tiny/lib/Models/Order.cpp new file mode 100644 index 00000000000..b8b7e00d3fc --- /dev/null +++ b/samples/client/petstore/cpp-tiny/lib/Models/Order.cpp @@ -0,0 +1,238 @@ + + +#include "Order.h" + +using namespace Tiny; + +Order::Order() +{ + id = long(0); + petId = long(0); + quantity = int(0); + shipDate = std::string(); + status = std::string(); + complete = bool(false); +} + +Order::Order(std::string jsonString) +{ + this->fromJson(jsonString); +} + +Order::~Order() +{ + +} + +void +Order::fromJson(std::string jsonObj) +{ + bourne::json object = bourne::json::parse(jsonObj); + + const char *idKey = "id"; + + if(object.has_key(idKey)) + { + bourne::json value = object[idKey]; + + + + jsonToValue(&id, value, "long"); + + + } + + const char *petIdKey = "petId"; + + if(object.has_key(petIdKey)) + { + bourne::json value = object[petIdKey]; + + + + jsonToValue(&petId, value, "long"); + + + } + + const char *quantityKey = "quantity"; + + if(object.has_key(quantityKey)) + { + bourne::json value = object[quantityKey]; + + + + jsonToValue(&quantity, value, "int"); + + + } + + const char *shipDateKey = "shipDate"; + + if(object.has_key(shipDateKey)) + { + bourne::json value = object[shipDateKey]; + + + + jsonToValue(&shipDate, value, "std::string"); + + + } + + const char *statusKey = "status"; + + if(object.has_key(statusKey)) + { + bourne::json value = object[statusKey]; + + + + jsonToValue(&status, value, "std::string"); + + + } + + const char *completeKey = "complete"; + + if(object.has_key(completeKey)) + { + bourne::json value = object[completeKey]; + + + + jsonToValue(&complete, value, "bool"); + + + } + + +} + +bourne::json +Order::toJson() +{ + bourne::json object = bourne::json::object(); + + + + + + object["id"] = getId(); + + + + + + + object["petId"] = getPetId(); + + + + + + + object["quantity"] = getQuantity(); + + + + + + + object["shipDate"] = getShipDate(); + + + + + + + object["status"] = getStatus(); + + + + + + + object["complete"] = isComplete(); + + + + return object; + +} + +long +Order::getId() +{ + return id; +} + +void +Order::setId(long id) +{ + this->id = id; +} + +long +Order::getPetId() +{ + return petId; +} + +void +Order::setPetId(long petId) +{ + this->petId = petId; +} + +int +Order::getQuantity() +{ + return quantity; +} + +void +Order::setQuantity(int quantity) +{ + this->quantity = quantity; +} + +std::string +Order::getShipDate() +{ + return shipDate; +} + +void +Order::setShipDate(std::string shipDate) +{ + this->shipDate = shipDate; +} + +std::string +Order::getStatus() +{ + return status; +} + +void +Order::setStatus(std::string status) +{ + this->status = status; +} + +bool +Order::isComplete() +{ + return complete; +} + +void +Order::setComplete(bool complete) +{ + this->complete = complete; +} + + + diff --git a/samples/client/petstore/cpp-tiny/lib/Models/Order.h b/samples/client/petstore/cpp-tiny/lib/Models/Order.h new file mode 100644 index 00000000000..6f36404f959 --- /dev/null +++ b/samples/client/petstore/cpp-tiny/lib/Models/Order.h @@ -0,0 +1,102 @@ + +/* + * Order.h + * + * An order for a pets from the pet store + */ + +#ifndef TINY_CPP_CLIENT_Order_H_ +#define TINY_CPP_CLIENT_Order_H_ + + +#include +#include "bourne/json.hpp" +#include "Helpers.h" + +namespace Tiny { + + +/*! \brief An order for a pets from the pet store + * + * \ingroup Models + * + */ + +class Order{ +public: + + /*! \brief Constructor. + */ + Order(); + Order(std::string jsonString); + + + /*! \brief Destructor. + */ + virtual ~Order(); + + + /*! \brief Retrieve a bourne JSON representation of this class. + */ + bourne::json toJson(); + + + /*! \brief Fills in members of this class from bourne JSON object representing it. + */ + void fromJson(std::string jsonObj); + + /*! \brief Get + */ + long getId(); + + /*! \brief Set + */ + void setId(long id); + /*! \brief Get + */ + long getPetId(); + + /*! \brief Set + */ + void setPetId(long petId); + /*! \brief Get + */ + int getQuantity(); + + /*! \brief Set + */ + void setQuantity(int quantity); + /*! \brief Get + */ + std::string getShipDate(); + + /*! \brief Set + */ + void setShipDate(std::string shipDate); + /*! \brief Get Order Status + */ + std::string getStatus(); + + /*! \brief Set Order Status + */ + void setStatus(std::string status); + /*! \brief Get + */ + bool isComplete(); + + /*! \brief Set + */ + void setComplete(bool complete); + + + private: + long id{}; + long petId{}; + int quantity{}; + std::string shipDate{}; + std::string status{}; + bool complete{}; +}; +} + +#endif /* TINY_CPP_CLIENT_Order_H_ */ diff --git a/samples/client/petstore/cpp-tiny/lib/Models/Pet.cpp b/samples/client/petstore/cpp-tiny/lib/Models/Pet.cpp new file mode 100644 index 00000000000..57f7781aef2 --- /dev/null +++ b/samples/client/petstore/cpp-tiny/lib/Models/Pet.cpp @@ -0,0 +1,274 @@ + + +#include "Pet.h" + +using namespace Tiny; + +Pet::Pet() +{ + id = long(0); + category = Category(); + name = std::string(); + photoUrls = std::list(); + tags = std::list(); + status = std::string(); +} + +Pet::Pet(std::string jsonString) +{ + this->fromJson(jsonString); +} + +Pet::~Pet() +{ + +} + +void +Pet::fromJson(std::string jsonObj) +{ + bourne::json object = bourne::json::parse(jsonObj); + + const char *idKey = "id"; + + if(object.has_key(idKey)) + { + bourne::json value = object[idKey]; + + + + jsonToValue(&id, value, "long"); + + + } + + const char *categoryKey = "category"; + + if(object.has_key(categoryKey)) + { + bourne::json value = object[categoryKey]; + + + + + Category* obj = &category; + obj->fromJson(value.dump()); + + } + + const char *nameKey = "name"; + + if(object.has_key(nameKey)) + { + bourne::json value = object[nameKey]; + + + + jsonToValue(&name, value, "std::string"); + + + } + + const char *photoUrlsKey = "photoUrls"; + + if(object.has_key(photoUrlsKey)) + { + bourne::json value = object[photoUrlsKey]; + + + std::list photoUrls_list; + std::string element; + for(auto& var : value.array_range()) + { + + jsonToValue(&element, var, "std::string"); + + + photoUrls_list.push_back(element); + } + photoUrls = photoUrls_list; + + + } + + const char *tagsKey = "tags"; + + if(object.has_key(tagsKey)) + { + bourne::json value = object[tagsKey]; + + + std::list tags_list; + Tag element; + for(auto& var : value.array_range()) + { + + + element.fromJson(var.dump()); + + tags_list.push_back(element); + } + tags = tags_list; + + + } + + const char *statusKey = "status"; + + if(object.has_key(statusKey)) + { + bourne::json value = object[statusKey]; + + + + jsonToValue(&status, value, "std::string"); + + + } + + +} + +bourne::json +Pet::toJson() +{ + bourne::json object = bourne::json::object(); + + + + + + object["id"] = getId(); + + + + + + + + object["category"] = getCategory().toJson(); + + + + + + object["name"] = getName(); + + + + + + std::list photoUrls_list = getPhotoUrls(); + bourne::json photoUrls_arr = bourne::json::array(); + + for(auto& var : photoUrls_list) + { + photoUrls_arr.append(var); + } + object["photoUrls"] = photoUrls_arr; + + + + + + + + + std::list tags_list = getTags(); + bourne::json tags_arr = bourne::json::array(); + + for(auto& var : tags_list) + { + Tag obj = var; + tags_arr.append(obj.toJson()); + } + object["tags"] = tags_arr; + + + + + + + + object["status"] = getStatus(); + + + + return object; + +} + +long +Pet::getId() +{ + return id; +} + +void +Pet::setId(long id) +{ + this->id = id; +} + +Category +Pet::getCategory() +{ + return category; +} + +void +Pet::setCategory(Category category) +{ + this->category = category; +} + +std::string +Pet::getName() +{ + return name; +} + +void +Pet::setName(std::string name) +{ + this->name = name; +} + +std::list +Pet::getPhotoUrls() +{ + return photoUrls; +} + +void +Pet::setPhotoUrls(std::list photoUrls) +{ + this->photoUrls = photoUrls; +} + +std::list +Pet::getTags() +{ + return tags; +} + +void +Pet::setTags(std::list tags) +{ + this->tags = tags; +} + +std::string +Pet::getStatus() +{ + return status; +} + +void +Pet::setStatus(std::string status) +{ + this->status = status; +} + + + diff --git a/samples/client/petstore/cpp-tiny/lib/Models/Pet.h b/samples/client/petstore/cpp-tiny/lib/Models/Pet.h new file mode 100644 index 00000000000..3329735f8a1 --- /dev/null +++ b/samples/client/petstore/cpp-tiny/lib/Models/Pet.h @@ -0,0 +1,105 @@ + +/* + * Pet.h + * + * A pet for sale in the pet store + */ + +#ifndef TINY_CPP_CLIENT_Pet_H_ +#define TINY_CPP_CLIENT_Pet_H_ + + +#include +#include "bourne/json.hpp" +#include "Helpers.h" +#include "Category.h" +#include "Tag.h" +#include + +namespace Tiny { + + +/*! \brief A pet for sale in the pet store + * + * \ingroup Models + * + */ + +class Pet{ +public: + + /*! \brief Constructor. + */ + Pet(); + Pet(std::string jsonString); + + + /*! \brief Destructor. + */ + virtual ~Pet(); + + + /*! \brief Retrieve a bourne JSON representation of this class. + */ + bourne::json toJson(); + + + /*! \brief Fills in members of this class from bourne JSON object representing it. + */ + void fromJson(std::string jsonObj); + + /*! \brief Get + */ + long getId(); + + /*! \brief Set + */ + void setId(long id); + /*! \brief Get + */ + Category getCategory(); + + /*! \brief Set + */ + void setCategory(Category category); + /*! \brief Get + */ + std::string getName(); + + /*! \brief Set + */ + void setName(std::string name); + /*! \brief Get + */ + std::list getPhotoUrls(); + + /*! \brief Set + */ + void setPhotoUrls(std::list photoUrls); + /*! \brief Get + */ + std::list getTags(); + + /*! \brief Set + */ + void setTags(std::list tags); + /*! \brief Get pet status in the store + */ + std::string getStatus(); + + /*! \brief Set pet status in the store + */ + void setStatus(std::string status); + + + private: + long id{}; + Category category; + std::string name{}; + std::list photoUrls; + std::list tags; + std::string status{}; +}; +} + +#endif /* TINY_CPP_CLIENT_Pet_H_ */ diff --git a/samples/client/petstore/cpp-tiny/lib/Models/Tag.cpp b/samples/client/petstore/cpp-tiny/lib/Models/Tag.cpp new file mode 100644 index 00000000000..e46d94258a1 --- /dev/null +++ b/samples/client/petstore/cpp-tiny/lib/Models/Tag.cpp @@ -0,0 +1,106 @@ + + +#include "Tag.h" + +using namespace Tiny; + +Tag::Tag() +{ + id = long(0); + name = std::string(); +} + +Tag::Tag(std::string jsonString) +{ + this->fromJson(jsonString); +} + +Tag::~Tag() +{ + +} + +void +Tag::fromJson(std::string jsonObj) +{ + bourne::json object = bourne::json::parse(jsonObj); + + const char *idKey = "id"; + + if(object.has_key(idKey)) + { + bourne::json value = object[idKey]; + + + + jsonToValue(&id, value, "long"); + + + } + + const char *nameKey = "name"; + + if(object.has_key(nameKey)) + { + bourne::json value = object[nameKey]; + + + + jsonToValue(&name, value, "std::string"); + + + } + + +} + +bourne::json +Tag::toJson() +{ + bourne::json object = bourne::json::object(); + + + + + + object["id"] = getId(); + + + + + + + object["name"] = getName(); + + + + return object; + +} + +long +Tag::getId() +{ + return id; +} + +void +Tag::setId(long id) +{ + this->id = id; +} + +std::string +Tag::getName() +{ + return name; +} + +void +Tag::setName(std::string name) +{ + this->name = name; +} + + + diff --git a/samples/client/petstore/cpp-tiny/lib/Models/Tag.h b/samples/client/petstore/cpp-tiny/lib/Models/Tag.h new file mode 100644 index 00000000000..e05bcdc9290 --- /dev/null +++ b/samples/client/petstore/cpp-tiny/lib/Models/Tag.h @@ -0,0 +1,70 @@ + +/* + * Tag.h + * + * A tag for a pet + */ + +#ifndef TINY_CPP_CLIENT_Tag_H_ +#define TINY_CPP_CLIENT_Tag_H_ + + +#include +#include "bourne/json.hpp" +#include "Helpers.h" + +namespace Tiny { + + +/*! \brief A tag for a pet + * + * \ingroup Models + * + */ + +class Tag{ +public: + + /*! \brief Constructor. + */ + Tag(); + Tag(std::string jsonString); + + + /*! \brief Destructor. + */ + virtual ~Tag(); + + + /*! \brief Retrieve a bourne JSON representation of this class. + */ + bourne::json toJson(); + + + /*! \brief Fills in members of this class from bourne JSON object representing it. + */ + void fromJson(std::string jsonObj); + + /*! \brief Get + */ + long getId(); + + /*! \brief Set + */ + void setId(long id); + /*! \brief Get + */ + std::string getName(); + + /*! \brief Set + */ + void setName(std::string name); + + + private: + long id{}; + std::string name{}; +}; +} + +#endif /* TINY_CPP_CLIENT_Tag_H_ */ diff --git a/samples/client/petstore/cpp-tiny/lib/Models/User.cpp b/samples/client/petstore/cpp-tiny/lib/Models/User.cpp new file mode 100644 index 00000000000..ac84c40205a --- /dev/null +++ b/samples/client/petstore/cpp-tiny/lib/Models/User.cpp @@ -0,0 +1,304 @@ + + +#include "User.h" + +using namespace Tiny; + +User::User() +{ + id = long(0); + username = std::string(); + firstName = std::string(); + lastName = std::string(); + email = std::string(); + password = std::string(); + phone = std::string(); + userStatus = int(0); +} + +User::User(std::string jsonString) +{ + this->fromJson(jsonString); +} + +User::~User() +{ + +} + +void +User::fromJson(std::string jsonObj) +{ + bourne::json object = bourne::json::parse(jsonObj); + + const char *idKey = "id"; + + if(object.has_key(idKey)) + { + bourne::json value = object[idKey]; + + + + jsonToValue(&id, value, "long"); + + + } + + const char *usernameKey = "username"; + + if(object.has_key(usernameKey)) + { + bourne::json value = object[usernameKey]; + + + + jsonToValue(&username, value, "std::string"); + + + } + + const char *firstNameKey = "firstName"; + + if(object.has_key(firstNameKey)) + { + bourne::json value = object[firstNameKey]; + + + + jsonToValue(&firstName, value, "std::string"); + + + } + + const char *lastNameKey = "lastName"; + + if(object.has_key(lastNameKey)) + { + bourne::json value = object[lastNameKey]; + + + + jsonToValue(&lastName, value, "std::string"); + + + } + + const char *emailKey = "email"; + + if(object.has_key(emailKey)) + { + bourne::json value = object[emailKey]; + + + + jsonToValue(&email, value, "std::string"); + + + } + + const char *passwordKey = "password"; + + if(object.has_key(passwordKey)) + { + bourne::json value = object[passwordKey]; + + + + jsonToValue(&password, value, "std::string"); + + + } + + const char *phoneKey = "phone"; + + if(object.has_key(phoneKey)) + { + bourne::json value = object[phoneKey]; + + + + jsonToValue(&phone, value, "std::string"); + + + } + + const char *userStatusKey = "userStatus"; + + if(object.has_key(userStatusKey)) + { + bourne::json value = object[userStatusKey]; + + + + jsonToValue(&userStatus, value, "int"); + + + } + + +} + +bourne::json +User::toJson() +{ + bourne::json object = bourne::json::object(); + + + + + + object["id"] = getId(); + + + + + + + object["username"] = getUsername(); + + + + + + + object["firstName"] = getFirstName(); + + + + + + + object["lastName"] = getLastName(); + + + + + + + object["email"] = getEmail(); + + + + + + + object["password"] = getPassword(); + + + + + + + object["phone"] = getPhone(); + + + + + + + object["userStatus"] = getUserStatus(); + + + + return object; + +} + +long +User::getId() +{ + return id; +} + +void +User::setId(long id) +{ + this->id = id; +} + +std::string +User::getUsername() +{ + return username; +} + +void +User::setUsername(std::string username) +{ + this->username = username; +} + +std::string +User::getFirstName() +{ + return firstName; +} + +void +User::setFirstName(std::string firstName) +{ + this->firstName = firstName; +} + +std::string +User::getLastName() +{ + return lastName; +} + +void +User::setLastName(std::string lastName) +{ + this->lastName = lastName; +} + +std::string +User::getEmail() +{ + return email; +} + +void +User::setEmail(std::string email) +{ + this->email = email; +} + +std::string +User::getPassword() +{ + return password; +} + +void +User::setPassword(std::string password) +{ + this->password = password; +} + +std::string +User::getPhone() +{ + return phone; +} + +void +User::setPhone(std::string phone) +{ + this->phone = phone; +} + +int +User::getUserStatus() +{ + return userStatus; +} + +void +User::setUserStatus(int userStatus) +{ + this->userStatus = userStatus; +} + + + diff --git a/samples/client/petstore/cpp-tiny/lib/Models/User.h b/samples/client/petstore/cpp-tiny/lib/Models/User.h new file mode 100644 index 00000000000..84de5204ced --- /dev/null +++ b/samples/client/petstore/cpp-tiny/lib/Models/User.h @@ -0,0 +1,118 @@ + +/* + * User.h + * + * A User who is purchasing from the pet store + */ + +#ifndef TINY_CPP_CLIENT_User_H_ +#define TINY_CPP_CLIENT_User_H_ + + +#include +#include "bourne/json.hpp" +#include "Helpers.h" + +namespace Tiny { + + +/*! \brief A User who is purchasing from the pet store + * + * \ingroup Models + * + */ + +class User{ +public: + + /*! \brief Constructor. + */ + User(); + User(std::string jsonString); + + + /*! \brief Destructor. + */ + virtual ~User(); + + + /*! \brief Retrieve a bourne JSON representation of this class. + */ + bourne::json toJson(); + + + /*! \brief Fills in members of this class from bourne JSON object representing it. + */ + void fromJson(std::string jsonObj); + + /*! \brief Get + */ + long getId(); + + /*! \brief Set + */ + void setId(long id); + /*! \brief Get + */ + std::string getUsername(); + + /*! \brief Set + */ + void setUsername(std::string username); + /*! \brief Get + */ + std::string getFirstName(); + + /*! \brief Set + */ + void setFirstName(std::string firstName); + /*! \brief Get + */ + std::string getLastName(); + + /*! \brief Set + */ + void setLastName(std::string lastName); + /*! \brief Get + */ + std::string getEmail(); + + /*! \brief Set + */ + void setEmail(std::string email); + /*! \brief Get + */ + std::string getPassword(); + + /*! \brief Set + */ + void setPassword(std::string password); + /*! \brief Get + */ + std::string getPhone(); + + /*! \brief Set + */ + void setPhone(std::string phone); + /*! \brief Get User Status + */ + int getUserStatus(); + + /*! \brief Set User Status + */ + void setUserStatus(int userStatus); + + + private: + long id{}; + std::string username{}; + std::string firstName{}; + std::string lastName{}; + std::string email{}; + std::string password{}; + std::string phone{}; + int userStatus{}; +}; +} + +#endif /* TINY_CPP_CLIENT_User_H_ */ diff --git a/samples/client/petstore/cpp-tiny/lib/TestFiles/ApiResponseTest.cpp b/samples/client/petstore/cpp-tiny/lib/TestFiles/ApiResponseTest.cpp new file mode 100644 index 00000000000..160f4217f5d --- /dev/null +++ b/samples/client/petstore/cpp-tiny/lib/TestFiles/ApiResponseTest.cpp @@ -0,0 +1,139 @@ + +#include "ApiResponse.h" + +using namespace Tiny; + +#include +#include +#include +#include "bourne/json.hpp" + + + +void test_ApiResponse_code_is_assigned_from_json() +{ + bourne::json input = + { + "code", 1 + }; + + ApiResponse obj(input.dump()); + + TEST_ASSERT_EQUAL_INT(1, obj.getCode()); + + + + + + + + +} + + +void test_ApiResponse_type_is_assigned_from_json() +{ + + + bourne::json input = + { + "type", "hello" + }; + + ApiResponse obj(input.dump()); + + TEST_ASSERT_EQUAL_STRING("hello", obj.getType().c_str()); + + + + + + +} + + +void test_ApiResponse_message_is_assigned_from_json() +{ + + + bourne::json input = + { + "message", "hello" + }; + + ApiResponse obj(input.dump()); + + TEST_ASSERT_EQUAL_STRING("hello", obj.getMessage().c_str()); + + + + + + +} + + + +void test_ApiResponse_code_is_converted_to_json() +{ + bourne::json input = + { + "code", 1 + }; + + ApiResponse obj(input.dump()); + + bourne::json output = bourne::json::object(); + + output = obj.toJson(); + + TEST_ASSERT(input["code"] == output["code"]); + + + + +} + + +void test_ApiResponse_type_is_converted_to_json() +{ + + bourne::json input = + { + "type", "hello" + }; + + ApiResponse obj(input.dump()); + + bourne::json output = bourne::json::object(); + + output = obj.toJson(); + + TEST_ASSERT(input["type"] == output["type"]); + + + +} + + +void test_ApiResponse_message_is_converted_to_json() +{ + + bourne::json input = + { + "message", "hello" + }; + + ApiResponse obj(input.dump()); + + bourne::json output = bourne::json::object(); + + output = obj.toJson(); + + TEST_ASSERT(input["message"] == output["message"]); + + + +} + + diff --git a/samples/client/petstore/cpp-tiny/lib/TestFiles/CategoryTest.cpp b/samples/client/petstore/cpp-tiny/lib/TestFiles/CategoryTest.cpp new file mode 100644 index 00000000000..2951856e6a5 --- /dev/null +++ b/samples/client/petstore/cpp-tiny/lib/TestFiles/CategoryTest.cpp @@ -0,0 +1,97 @@ + +#include "Category.h" + +using namespace Tiny; + +#include +#include +#include +#include "bourne/json.hpp" + + + +void test_Category_id_is_assigned_from_json() +{ + + + + + + + bourne::json input = + { + "id", 1 + }; + + Category obj(input.dump()); + + TEST_ASSERT_EQUAL_INT(1, obj.getId()); + + +} + + +void test_Category_name_is_assigned_from_json() +{ + + + bourne::json input = + { + "name", "hello" + }; + + Category obj(input.dump()); + + TEST_ASSERT_EQUAL_STRING("hello", obj.getName().c_str()); + + + + + + +} + + + +void test_Category_id_is_converted_to_json() +{ + + + + bourne::json input = + { + "id", 1 + }; + + Category obj(input.dump()); + + bourne::json output = bourne::json::object(); + + output = obj.toJson(); + + TEST_ASSERT(input["id"] == output["id"]); + +} + + +void test_Category_name_is_converted_to_json() +{ + + bourne::json input = + { + "name", "hello" + }; + + Category obj(input.dump()); + + bourne::json output = bourne::json::object(); + + output = obj.toJson(); + + TEST_ASSERT(input["name"] == output["name"]); + + + +} + + diff --git a/samples/client/petstore/cpp-tiny/lib/TestFiles/OrderTest.cpp b/samples/client/petstore/cpp-tiny/lib/TestFiles/OrderTest.cpp new file mode 100644 index 00000000000..13125fc8fc5 --- /dev/null +++ b/samples/client/petstore/cpp-tiny/lib/TestFiles/OrderTest.cpp @@ -0,0 +1,245 @@ + +#include "Order.h" + +using namespace Tiny; + +#include +#include +#include +#include "bourne/json.hpp" + + + +void test_Order_id_is_assigned_from_json() +{ + + + + + + + bourne::json input = + { + "id", 1 + }; + + Order obj(input.dump()); + + TEST_ASSERT_EQUAL_INT(1, obj.getId()); + + +} + + +void test_Order_petId_is_assigned_from_json() +{ + + + + + + + bourne::json input = + { + "petId", 1 + }; + + Order obj(input.dump()); + + TEST_ASSERT_EQUAL_INT(1, obj.getPetId()); + + +} + + +void test_Order_quantity_is_assigned_from_json() +{ + bourne::json input = + { + "quantity", 1 + }; + + Order obj(input.dump()); + + TEST_ASSERT_EQUAL_INT(1, obj.getQuantity()); + + + + + + + + +} + + +void test_Order_shipDate_is_assigned_from_json() +{ + + + + + + + + +} + + +void test_Order_status_is_assigned_from_json() +{ + + + bourne::json input = + { + "status", "hello" + }; + + Order obj(input.dump()); + + TEST_ASSERT_EQUAL_STRING("hello", obj.getStatus().c_str()); + + + + + + +} + + +void test_Order_complete_is_assigned_from_json() +{ + + + + + bourne::json input = + { + "complete", true + }; + + Order obj(input.dump()); + + TEST_ASSERT(true == obj.isComplete()); + + + + +} + + + +void test_Order_id_is_converted_to_json() +{ + + + + bourne::json input = + { + "id", 1 + }; + + Order obj(input.dump()); + + bourne::json output = bourne::json::object(); + + output = obj.toJson(); + + TEST_ASSERT(input["id"] == output["id"]); + +} + + +void test_Order_petId_is_converted_to_json() +{ + + + + bourne::json input = + { + "petId", 1 + }; + + Order obj(input.dump()); + + bourne::json output = bourne::json::object(); + + output = obj.toJson(); + + TEST_ASSERT(input["petId"] == output["petId"]); + +} + + +void test_Order_quantity_is_converted_to_json() +{ + bourne::json input = + { + "quantity", 1 + }; + + Order obj(input.dump()); + + bourne::json output = bourne::json::object(); + + output = obj.toJson(); + + TEST_ASSERT(input["quantity"] == output["quantity"]); + + + + +} + + +void test_Order_shipDate_is_converted_to_json() +{ + + + + +} + + +void test_Order_status_is_converted_to_json() +{ + + bourne::json input = + { + "status", "hello" + }; + + Order obj(input.dump()); + + bourne::json output = bourne::json::object(); + + output = obj.toJson(); + + TEST_ASSERT(input["status"] == output["status"]); + + + +} + + +void test_Order_complete_is_converted_to_json() +{ + + + bourne::json input = + { + "complete", true + }; + + Order obj(input.dump()); + + bourne::json output = bourne::json::object(); + + output = obj.toJson(); + + TEST_ASSERT(input["complete"] == output["complete"]); + + +} + + diff --git a/samples/client/petstore/cpp-tiny/lib/TestFiles/PetTest.cpp b/samples/client/petstore/cpp-tiny/lib/TestFiles/PetTest.cpp new file mode 100644 index 00000000000..04dad464093 --- /dev/null +++ b/samples/client/petstore/cpp-tiny/lib/TestFiles/PetTest.cpp @@ -0,0 +1,145 @@ + +#include "Pet.h" + +using namespace Tiny; + +#include +#include +#include +#include "bourne/json.hpp" + + + +void test_Pet_id_is_assigned_from_json() +{ + + + + + + + bourne::json input = + { + "id", 1 + }; + + Pet obj(input.dump()); + + TEST_ASSERT_EQUAL_INT(1, obj.getId()); + + +} + + + +void test_Pet_name_is_assigned_from_json() +{ + + + bourne::json input = + { + "name", "hello" + }; + + Pet obj(input.dump()); + + TEST_ASSERT_EQUAL_STRING("hello", obj.getName().c_str()); + + + + + + +} + + + + +void test_Pet_status_is_assigned_from_json() +{ + + + bourne::json input = + { + "status", "hello" + }; + + Pet obj(input.dump()); + + TEST_ASSERT_EQUAL_STRING("hello", obj.getStatus().c_str()); + + + + + + +} + + + +void test_Pet_id_is_converted_to_json() +{ + + + + bourne::json input = + { + "id", 1 + }; + + Pet obj(input.dump()); + + bourne::json output = bourne::json::object(); + + output = obj.toJson(); + + TEST_ASSERT(input["id"] == output["id"]); + +} + + + +void test_Pet_name_is_converted_to_json() +{ + + bourne::json input = + { + "name", "hello" + }; + + Pet obj(input.dump()); + + bourne::json output = bourne::json::object(); + + output = obj.toJson(); + + TEST_ASSERT(input["name"] == output["name"]); + + + +} + + + + +void test_Pet_status_is_converted_to_json() +{ + + bourne::json input = + { + "status", "hello" + }; + + Pet obj(input.dump()); + + bourne::json output = bourne::json::object(); + + output = obj.toJson(); + + TEST_ASSERT(input["status"] == output["status"]); + + + +} + + diff --git a/samples/client/petstore/cpp-tiny/lib/TestFiles/TagTest.cpp b/samples/client/petstore/cpp-tiny/lib/TestFiles/TagTest.cpp new file mode 100644 index 00000000000..41ea1d0095d --- /dev/null +++ b/samples/client/petstore/cpp-tiny/lib/TestFiles/TagTest.cpp @@ -0,0 +1,97 @@ + +#include "Tag.h" + +using namespace Tiny; + +#include +#include +#include +#include "bourne/json.hpp" + + + +void test_Tag_id_is_assigned_from_json() +{ + + + + + + + bourne::json input = + { + "id", 1 + }; + + Tag obj(input.dump()); + + TEST_ASSERT_EQUAL_INT(1, obj.getId()); + + +} + + +void test_Tag_name_is_assigned_from_json() +{ + + + bourne::json input = + { + "name", "hello" + }; + + Tag obj(input.dump()); + + TEST_ASSERT_EQUAL_STRING("hello", obj.getName().c_str()); + + + + + + +} + + + +void test_Tag_id_is_converted_to_json() +{ + + + + bourne::json input = + { + "id", 1 + }; + + Tag obj(input.dump()); + + bourne::json output = bourne::json::object(); + + output = obj.toJson(); + + TEST_ASSERT(input["id"] == output["id"]); + +} + + +void test_Tag_name_is_converted_to_json() +{ + + bourne::json input = + { + "name", "hello" + }; + + Tag obj(input.dump()); + + bourne::json output = bourne::json::object(); + + output = obj.toJson(); + + TEST_ASSERT(input["name"] == output["name"]); + + + +} + + diff --git a/samples/client/petstore/cpp-tiny/lib/TestFiles/UserTest.cpp b/samples/client/petstore/cpp-tiny/lib/TestFiles/UserTest.cpp new file mode 100644 index 00000000000..689ee582bee --- /dev/null +++ b/samples/client/petstore/cpp-tiny/lib/TestFiles/UserTest.cpp @@ -0,0 +1,349 @@ + +#include "User.h" + +using namespace Tiny; + +#include +#include +#include +#include "bourne/json.hpp" + + + +void test_User_id_is_assigned_from_json() +{ + + + + + + + bourne::json input = + { + "id", 1 + }; + + User obj(input.dump()); + + TEST_ASSERT_EQUAL_INT(1, obj.getId()); + + +} + + +void test_User_username_is_assigned_from_json() +{ + + + bourne::json input = + { + "username", "hello" + }; + + User obj(input.dump()); + + TEST_ASSERT_EQUAL_STRING("hello", obj.getUsername().c_str()); + + + + + + +} + + +void test_User_firstName_is_assigned_from_json() +{ + + + bourne::json input = + { + "firstName", "hello" + }; + + User obj(input.dump()); + + TEST_ASSERT_EQUAL_STRING("hello", obj.getFirstName().c_str()); + + + + + + +} + + +void test_User_lastName_is_assigned_from_json() +{ + + + bourne::json input = + { + "lastName", "hello" + }; + + User obj(input.dump()); + + TEST_ASSERT_EQUAL_STRING("hello", obj.getLastName().c_str()); + + + + + + +} + + +void test_User_email_is_assigned_from_json() +{ + + + bourne::json input = + { + "email", "hello" + }; + + User obj(input.dump()); + + TEST_ASSERT_EQUAL_STRING("hello", obj.getEmail().c_str()); + + + + + + +} + + +void test_User_password_is_assigned_from_json() +{ + + + bourne::json input = + { + "password", "hello" + }; + + User obj(input.dump()); + + TEST_ASSERT_EQUAL_STRING("hello", obj.getPassword().c_str()); + + + + + + +} + + +void test_User_phone_is_assigned_from_json() +{ + + + bourne::json input = + { + "phone", "hello" + }; + + User obj(input.dump()); + + TEST_ASSERT_EQUAL_STRING("hello", obj.getPhone().c_str()); + + + + + + +} + + +void test_User_userStatus_is_assigned_from_json() +{ + bourne::json input = + { + "userStatus", 1 + }; + + User obj(input.dump()); + + TEST_ASSERT_EQUAL_INT(1, obj.getUserStatus()); + + + + + + + + +} + + + +void test_User_id_is_converted_to_json() +{ + + + + bourne::json input = + { + "id", 1 + }; + + User obj(input.dump()); + + bourne::json output = bourne::json::object(); + + output = obj.toJson(); + + TEST_ASSERT(input["id"] == output["id"]); + +} + + +void test_User_username_is_converted_to_json() +{ + + bourne::json input = + { + "username", "hello" + }; + + User obj(input.dump()); + + bourne::json output = bourne::json::object(); + + output = obj.toJson(); + + TEST_ASSERT(input["username"] == output["username"]); + + + +} + + +void test_User_firstName_is_converted_to_json() +{ + + bourne::json input = + { + "firstName", "hello" + }; + + User obj(input.dump()); + + bourne::json output = bourne::json::object(); + + output = obj.toJson(); + + TEST_ASSERT(input["firstName"] == output["firstName"]); + + + +} + + +void test_User_lastName_is_converted_to_json() +{ + + bourne::json input = + { + "lastName", "hello" + }; + + User obj(input.dump()); + + bourne::json output = bourne::json::object(); + + output = obj.toJson(); + + TEST_ASSERT(input["lastName"] == output["lastName"]); + + + +} + + +void test_User_email_is_converted_to_json() +{ + + bourne::json input = + { + "email", "hello" + }; + + User obj(input.dump()); + + bourne::json output = bourne::json::object(); + + output = obj.toJson(); + + TEST_ASSERT(input["email"] == output["email"]); + + + +} + + +void test_User_password_is_converted_to_json() +{ + + bourne::json input = + { + "password", "hello" + }; + + User obj(input.dump()); + + bourne::json output = bourne::json::object(); + + output = obj.toJson(); + + TEST_ASSERT(input["password"] == output["password"]); + + + +} + + +void test_User_phone_is_converted_to_json() +{ + + bourne::json input = + { + "phone", "hello" + }; + + User obj(input.dump()); + + bourne::json output = bourne::json::object(); + + output = obj.toJson(); + + TEST_ASSERT(input["phone"] == output["phone"]); + + + +} + + +void test_User_userStatus_is_converted_to_json() +{ + bourne::json input = + { + "userStatus", 1 + }; + + User obj(input.dump()); + + bourne::json output = bourne::json::object(); + + output = obj.toJson(); + + TEST_ASSERT(input["userStatus"] == output["userStatus"]); + + + + +} + + diff --git a/samples/client/petstore/cpp-tiny/lib/service/AbstractService.cpp b/samples/client/petstore/cpp-tiny/lib/service/AbstractService.cpp new file mode 100644 index 00000000000..ac7e992cecc --- /dev/null +++ b/samples/client/petstore/cpp-tiny/lib/service/AbstractService.cpp @@ -0,0 +1,8 @@ +#include "AbstractService.h" +#include "Arduino.h" + + + +void Tiny::AbstractService::begin(std::string url){ + http.begin(String(url.c_str()), test_root_ca); //HTTPS connection +} diff --git a/samples/client/petstore/cpp-tiny/lib/service/AbstractService.h b/samples/client/petstore/cpp-tiny/lib/service/AbstractService.h new file mode 100644 index 00000000000..07214896d7f --- /dev/null +++ b/samples/client/petstore/cpp-tiny/lib/service/AbstractService.h @@ -0,0 +1,28 @@ +#ifndef TINY_CPP_CLIENT_ABSTRACTSERVICE_H_ +#define TINY_CPP_CLIENT_ABSTRACTSERVICE_H_ + +#include "HTTPClient.h" +#include "Response.h" +namespace Tiny { + +/** +* Class +* Generated with openapi::tiny-cpp-client +*/ +class AbstractService { +public: +HTTPClient http; +std::string basepath = "https://petstore3.swagger.io/api/v3"; // TODO: change to your url + +void begin(std::string url); + +// Go and comment out a certificate in root.cert, if you get an error here +// Certificate from file +const char* test_root_ca = +#include "../../root.cert" +; + +}; // end class +}// namespace Tinyclient + +#endif /* TINY_CPP_CLIENT_ABSTRACTSERVICE_H_ */ diff --git a/samples/client/petstore/cpp-tiny/lib/service/PetApi.cpp b/samples/client/petstore/cpp-tiny/lib/service/PetApi.cpp new file mode 100644 index 00000000000..1fa081a04b4 --- /dev/null +++ b/samples/client/petstore/cpp-tiny/lib/service/PetApi.cpp @@ -0,0 +1,418 @@ +#include "PetApi.h" + +using namespace Tiny; + + + + Response< + Pet + > + PetApi:: + addPet( + + Pet pet + + ) + { + std::string url = basepath + "/pet"; // + // Query | + // Headers | + // Form | + // Body | pet + + + begin(url); + + std::string payload = ""; + // Send Request + // METHOD | POST + http.addHeader("Content-Type", "application/json"); + + + + payload = pet.toJson().dump(); + + int httpCode = http.sendRequest("POST", reinterpret_cast(&payload[0]), payload.length()); + + // Handle Request + String output = http.getString(); + std::string output_string = output.c_str(); + + http.end(); + + + + + Pet obj(output_string); + + + Response response(obj, httpCode); + return response; + } + + Response< + String + > + PetApi:: + deletePet( + + long petId + , + + std::string apiKey + + ) + { + std::string url = basepath + "/pet/{petId}"; //petId + // Query | + // Headers | apiKey + // Form | + // Body | + + std::string s_petId("{"); + s_petId.append("petId"); + s_petId.append("}"); + + int pos = url.find(s_petId); + + url.erase(pos, s_petId.length()); + url.insert(pos, stringify(petId)); + + begin(url); + + std::string payload = ""; + // Send Request + // METHOD | DELETE + int httpCode = http.sendRequest("DELETE", reinterpret_cast(&payload[0]), payload.length()); + + // Handle Request + String output = http.getString(); + std::string output_string = output.c_str(); + + http.end(); + + + Response response(output, httpCode); + return response; + } + + Response< + std::list + > + PetApi:: + findPetsByStatus( + std::list status + + + ) + { + std::string url = basepath + "/pet/findByStatus"; // + // Query | status + // Headers | + // Form | + // Body | + + + begin(url); + + std::string payload = ""; + // Send Request + // METHOD | GET + int httpCode = http.sendRequest("GET", reinterpret_cast(&payload[0]), payload.length()); + + // Handle Request + String output = http.getString(); + std::string output_string = output.c_str(); + + http.end(); + + + + std::list obj = std::list(); + bourne::json jsonPayload(output_string); + + + + + + + + + + for(auto& var : jsonPayload.array_range()) + { + Pet tmp(var.dump()); + obj.push_back(tmp); + } + + + + + + + + + Response> response(obj, httpCode); + return response; + } + + Response< + std::list + > + PetApi:: + findPetsByTags( + std::list tags + + + ) + { + std::string url = basepath + "/pet/findByTags"; // + // Query | tags + // Headers | + // Form | + // Body | + + + begin(url); + + std::string payload = ""; + // Send Request + // METHOD | GET + int httpCode = http.sendRequest("GET", reinterpret_cast(&payload[0]), payload.length()); + + // Handle Request + String output = http.getString(); + std::string output_string = output.c_str(); + + http.end(); + + + + std::list obj = std::list(); + bourne::json jsonPayload(output_string); + + + + + + + + + + for(auto& var : jsonPayload.array_range()) + { + Pet tmp(var.dump()); + obj.push_back(tmp); + } + + + + + + + + + Response> response(obj, httpCode); + return response; + } + + Response< + Pet + > + PetApi:: + getPetById( + + long petId + + ) + { + std::string url = basepath + "/pet/{petId}"; //petId + // Query | + // Headers | + // Form | + // Body | + + std::string s_petId("{"); + s_petId.append("petId"); + s_petId.append("}"); + + int pos = url.find(s_petId); + + url.erase(pos, s_petId.length()); + url.insert(pos, stringify(petId)); + + begin(url); + + std::string payload = ""; + // Send Request + // METHOD | GET + int httpCode = http.sendRequest("GET", reinterpret_cast(&payload[0]), payload.length()); + + // Handle Request + String output = http.getString(); + std::string output_string = output.c_str(); + + http.end(); + + + + + Pet obj(output_string); + + + Response response(obj, httpCode); + return response; + } + + Response< + Pet + > + PetApi:: + updatePet( + + Pet pet + + ) + { + std::string url = basepath + "/pet"; // + // Query | + // Headers | + // Form | + // Body | pet + + + begin(url); + + std::string payload = ""; + // Send Request + // METHOD | PUT + http.addHeader("Content-Type", "application/json"); + + + + payload = pet.toJson().dump(); + + int httpCode = http.sendRequest("PUT", reinterpret_cast(&payload[0]), payload.length()); + + // Handle Request + String output = http.getString(); + std::string output_string = output.c_str(); + + http.end(); + + + + + Pet obj(output_string); + + + Response response(obj, httpCode); + return response; + } + + Response< + String + > + PetApi:: + updatePetWithForm( + + long petId + , + + std::string name + , + + std::string status + + ) + { + std::string url = basepath + "/pet/{petId}"; //petId + // Query | + // Headers | + // Form | name status + // Body | + + std::string s_petId("{"); + s_petId.append("petId"); + s_petId.append("}"); + + int pos = url.find(s_petId); + + url.erase(pos, s_petId.length()); + url.insert(pos, stringify(petId)); + + begin(url); + + std::string payload = ""; + // Send Request + // METHOD | POST + int httpCode = http.sendRequest("POST", reinterpret_cast(&payload[0]), payload.length()); + + // Handle Request + String output = http.getString(); + std::string output_string = output.c_str(); + + http.end(); + + + Response response(output, httpCode); + return response; + } + + Response< + ApiResponse + > + PetApi:: + uploadFile( + + long petId + , + + std::string additionalMetadata + , + + std::string file + + ) + { + std::string url = basepath + "/pet/{petId}/uploadImage"; //petId + // Query | + // Headers | + // Form | additionalMetadata file + // Body | + + std::string s_petId("{"); + s_petId.append("petId"); + s_petId.append("}"); + + int pos = url.find(s_petId); + + url.erase(pos, s_petId.length()); + url.insert(pos, stringify(petId)); + + begin(url); + + std::string payload = ""; + // Send Request + // METHOD | POST + int httpCode = http.sendRequest("POST", reinterpret_cast(&payload[0]), payload.length()); + + // Handle Request + String output = http.getString(); + std::string output_string = output.c_str(); + + http.end(); + + + + + ApiResponse obj(output_string); + + + Response response(obj, httpCode); + return response; + } + + + + diff --git a/samples/client/petstore/cpp-tiny/lib/service/PetApi.h b/samples/client/petstore/cpp-tiny/lib/service/PetApi.h new file mode 100644 index 00000000000..abcb0af0de9 --- /dev/null +++ b/samples/client/petstore/cpp-tiny/lib/service/PetApi.h @@ -0,0 +1,163 @@ +#ifndef TINY_CPP_CLIENT_PetApi_H_ +#define TINY_CPP_CLIENT_PetApi_H_ + + +#include "Response.h" +#include "Arduino.h" +#include "AbstractService.h" +#include "Helpers.h" +#include + +#include "ApiResponse.h" +#include "Pet.h" + +namespace Tiny { + +/** + * Class + * Generated with openapi::tiny-cpp-client + */ + +class PetApi : public AbstractService { +public: + PetApi() = default; + + virtual ~PetApi() = default; + + /** + * Add a new pet to the store. + * + * + * \param pet Pet object that needs to be added to the store *Required* + */ + Response< + Pet + > + addPet( + + Pet pet + + ); + /** + * Deletes a pet. + * + * + * \param petId Pet id to delete *Required* + * \param apiKey + */ + Response< + String + > + deletePet( + + long petId + , + + std::string apiKey + + ); + /** + * 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* + */ + Response< + std::list + > + findPetsByStatus( + std::list status + + + ); + /** + * 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* + */ + Response< + std::list + > + findPetsByTags( + std::list tags + + + ); + /** + * Find pet by ID. + * + * Returns a single pet + * \param petId ID of pet to return *Required* + */ + Response< + Pet + > + getPetById( + + long petId + + ); + /** + * Update an existing pet. + * + * + * \param pet Pet object that needs to be added to the store *Required* + */ + Response< + Pet + > + updatePet( + + Pet pet + + ); + /** + * Updates a pet in the store with form data. + * + * + * \param petId ID of pet that needs to be updated *Required* + * \param name Updated name of the pet + * \param status Updated status of the pet + */ + Response< + String + > + updatePetWithForm( + + long petId + , + + std::string name + , + + std::string status + + ); + /** + * uploads an image. + * + * + * \param petId ID of pet to update *Required* + * \param additionalMetadata Additional data to pass to server + * \param file file to upload + */ + Response< + ApiResponse + > + uploadFile( + + long petId + , + + std::string additionalMetadata + , + + std::string file + + ); +}; + +} + +#endif /* TINY_CPP_CLIENT_PetApi_H_ */ \ No newline at end of file diff --git a/samples/client/petstore/cpp-tiny/lib/service/Response.h b/samples/client/petstore/cpp-tiny/lib/service/Response.h new file mode 100644 index 00000000000..9b7b616b8f1 --- /dev/null +++ b/samples/client/petstore/cpp-tiny/lib/service/Response.h @@ -0,0 +1,25 @@ +#ifndef TINY_CPP_CLIENT_RESPONSE_H_ +#define TINY_CPP_CLIENT_RESPONSE_H_ +#include + +namespace Tiny { + +/** +* Class +* Generated with openapi::tiny-cpp-client +*/ +template + class Response { + public: + + Response(T _obj, int _code){ + obj = _obj; + code = _code; + } + + int code; + T obj; + }; + } // namespace Tinyclient + +#endif /* TINY_CPP_CLIENT_RESPONSE_H_ */ diff --git a/samples/client/petstore/cpp-tiny/lib/service/StoreApi.cpp b/samples/client/petstore/cpp-tiny/lib/service/StoreApi.cpp new file mode 100644 index 00000000000..210eb8277ac --- /dev/null +++ b/samples/client/petstore/cpp-tiny/lib/service/StoreApi.cpp @@ -0,0 +1,185 @@ +#include "StoreApi.h" + +using namespace Tiny; + + + + Response< + String + > + StoreApi:: + deleteOrder( + + std::string orderId + + ) + { + std::string url = basepath + "/store/order/{orderId}"; //orderId + // Query | + // Headers | + // Form | + // Body | + + std::string s_orderId("{"); + s_orderId.append("orderId"); + s_orderId.append("}"); + + int pos = url.find(s_orderId); + + url.erase(pos, s_orderId.length()); + url.insert(pos, stringify(orderId)); + + begin(url); + + std::string payload = ""; + // Send Request + // METHOD | DELETE + int httpCode = http.sendRequest("DELETE", reinterpret_cast(&payload[0]), payload.length()); + + // Handle Request + String output = http.getString(); + std::string output_string = output.c_str(); + + http.end(); + + + Response response(output, httpCode); + return response; + } + + Response< + String + > + StoreApi:: + getInventory( + ) + { + std::string url = basepath + "/store/inventory"; // + // Query | + // Headers | + // Form | + // Body | + + + begin(url); + + std::string payload = ""; + // Send Request + // METHOD | GET + int httpCode = http.sendRequest("GET", reinterpret_cast(&payload[0]), payload.length()); + + // Handle Request + String output = http.getString(); + std::string output_string = output.c_str(); + + http.end(); + + + + //TODO: Implement map logic here + + + + + //TODO: No support for maps. + Response response(output, httpCode); + return response; + } + + Response< + Order + > + StoreApi:: + getOrderById( + + long orderId + + ) + { + std::string url = basepath + "/store/order/{orderId}"; //orderId + // Query | + // Headers | + // Form | + // Body | + + std::string s_orderId("{"); + s_orderId.append("orderId"); + s_orderId.append("}"); + + int pos = url.find(s_orderId); + + url.erase(pos, s_orderId.length()); + url.insert(pos, stringify(orderId)); + + begin(url); + + std::string payload = ""; + // Send Request + // METHOD | GET + int httpCode = http.sendRequest("GET", reinterpret_cast(&payload[0]), payload.length()); + + // Handle Request + String output = http.getString(); + std::string output_string = output.c_str(); + + http.end(); + + + + + Order obj(output_string); + + + Response response(obj, httpCode); + return response; + } + + Response< + Order + > + StoreApi:: + placeOrder( + + Order order + + ) + { + std::string url = basepath + "/store/order"; // + // Query | + // Headers | + // Form | + // Body | order + + + begin(url); + + std::string payload = ""; + // Send Request + // METHOD | POST + http.addHeader("Content-Type", "application/json"); + + + + payload = order.toJson().dump(); + + int httpCode = http.sendRequest("POST", reinterpret_cast(&payload[0]), payload.length()); + + // Handle Request + String output = http.getString(); + std::string output_string = output.c_str(); + + http.end(); + + + + + Order obj(output_string); + + + Response response(obj, httpCode); + return response; + } + + + + diff --git a/samples/client/petstore/cpp-tiny/lib/service/StoreApi.h b/samples/client/petstore/cpp-tiny/lib/service/StoreApi.h new file mode 100644 index 00000000000..1bf0db02373 --- /dev/null +++ b/samples/client/petstore/cpp-tiny/lib/service/StoreApi.h @@ -0,0 +1,83 @@ +#ifndef TINY_CPP_CLIENT_StoreApi_H_ +#define TINY_CPP_CLIENT_StoreApi_H_ + + +#include "Response.h" +#include "Arduino.h" +#include "AbstractService.h" +#include "Helpers.h" +#include + +#include +#include "Order.h" + +namespace Tiny { + +/** + * Class + * Generated with openapi::tiny-cpp-client + */ + +class StoreApi : public AbstractService { +public: + StoreApi() = default; + + virtual ~StoreApi() = default; + + /** + * 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 *Required* + */ + Response< + String + > + deleteOrder( + + std::string orderId + + ); + /** + * Returns pet inventories by status. + * + * Returns a map of status codes to quantities + */ + Response< + String + > + getInventory( + ); + /** + * Find purchase order by ID. + * + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + * \param orderId ID of pet that needs to be fetched *Required* + */ + Response< + Order + > + getOrderById( + + long orderId + + ); + /** + * Place an order for a pet. + * + * + * \param order order placed for purchasing the pet *Required* + */ + Response< + Order + > + placeOrder( + + Order order + + ); +}; + +} + +#endif /* TINY_CPP_CLIENT_StoreApi_H_ */ \ No newline at end of file diff --git a/samples/client/petstore/cpp-tiny/lib/service/UserApi.cpp b/samples/client/petstore/cpp-tiny/lib/service/UserApi.cpp new file mode 100644 index 00000000000..d1cf12b80a9 --- /dev/null +++ b/samples/client/petstore/cpp-tiny/lib/service/UserApi.cpp @@ -0,0 +1,366 @@ +#include "UserApi.h" + +using namespace Tiny; + + + + Response< + String + > + UserApi:: + createUser( + + User user + + ) + { + std::string url = basepath + "/user"; // + // Query | + // Headers | + // Form | + // Body | user + + + begin(url); + + std::string payload = ""; + // Send Request + // METHOD | POST + http.addHeader("Content-Type", "application/json"); + + + + payload = user.toJson().dump(); + + int httpCode = http.sendRequest("POST", reinterpret_cast(&payload[0]), payload.length()); + + // Handle Request + String output = http.getString(); + std::string output_string = output.c_str(); + + http.end(); + + + Response response(output, httpCode); + return response; + } + + Response< + String + > + UserApi:: + createUsersWithArrayInput( + std::list user + + + ) + { + std::string url = basepath + "/user/createWithArray"; // + // Query | + // Headers | + // Form | + // Body | user + + + begin(url); + + std::string payload = ""; + // Send Request + // METHOD | POST + http.addHeader("Content-Type", "application/json"); + + + bourne::json tmp_arr = bourne::json::array(); + for(auto& var : user) + { + auto tmp = var.toJson(); + tmp_arr.append(tmp); + + } + payload = tmp_arr.dump(); + + + int httpCode = http.sendRequest("POST", reinterpret_cast(&payload[0]), payload.length()); + + // Handle Request + String output = http.getString(); + std::string output_string = output.c_str(); + + http.end(); + + + Response response(output, httpCode); + return response; + } + + Response< + String + > + UserApi:: + createUsersWithListInput( + std::list user + + + ) + { + std::string url = basepath + "/user/createWithList"; // + // Query | + // Headers | + // Form | + // Body | user + + + begin(url); + + std::string payload = ""; + // Send Request + // METHOD | POST + http.addHeader("Content-Type", "application/json"); + + + bourne::json tmp_arr = bourne::json::array(); + for(auto& var : user) + { + auto tmp = var.toJson(); + tmp_arr.append(tmp); + + } + payload = tmp_arr.dump(); + + + int httpCode = http.sendRequest("POST", reinterpret_cast(&payload[0]), payload.length()); + + // Handle Request + String output = http.getString(); + std::string output_string = output.c_str(); + + http.end(); + + + Response response(output, httpCode); + return response; + } + + Response< + String + > + UserApi:: + deleteUser( + + std::string username + + ) + { + std::string url = basepath + "/user/{username}"; //username + // Query | + // Headers | + // Form | + // Body | + + std::string s_username("{"); + s_username.append("username"); + s_username.append("}"); + + int pos = url.find(s_username); + + url.erase(pos, s_username.length()); + url.insert(pos, stringify(username)); + + begin(url); + + std::string payload = ""; + // Send Request + // METHOD | DELETE + int httpCode = http.sendRequest("DELETE", reinterpret_cast(&payload[0]), payload.length()); + + // Handle Request + String output = http.getString(); + std::string output_string = output.c_str(); + + http.end(); + + + Response response(output, httpCode); + return response; + } + + Response< + User + > + UserApi:: + getUserByName( + + std::string username + + ) + { + std::string url = basepath + "/user/{username}"; //username + // Query | + // Headers | + // Form | + // Body | + + std::string s_username("{"); + s_username.append("username"); + s_username.append("}"); + + int pos = url.find(s_username); + + url.erase(pos, s_username.length()); + url.insert(pos, stringify(username)); + + begin(url); + + std::string payload = ""; + // Send Request + // METHOD | GET + int httpCode = http.sendRequest("GET", reinterpret_cast(&payload[0]), payload.length()); + + // Handle Request + String output = http.getString(); + std::string output_string = output.c_str(); + + http.end(); + + + + + User obj(output_string); + + + Response response(obj, httpCode); + return response; + } + + Response< + std::string + > + UserApi:: + loginUser( + + std::string username + , + + std::string password + + ) + { + std::string url = basepath + "/user/login"; // + // Query | username password + // Headers | + // Form | + // Body | + + + begin(url); + + std::string payload = ""; + // Send Request + // METHOD | GET + int httpCode = http.sendRequest("GET", reinterpret_cast(&payload[0]), payload.length()); + + // Handle Request + String output = http.getString(); + std::string output_string = output.c_str(); + + http.end(); + + + + bourne::json jsonPayload(output_string); + std::string obj; + jsonToValue(&obj, jsonPayload, "std::string"); + + + + Response response(obj, httpCode); + return response; + } + + Response< + String + > + UserApi:: + logoutUser( + ) + { + std::string url = basepath + "/user/logout"; // + // Query | + // Headers | + // Form | + // Body | + + + begin(url); + + std::string payload = ""; + // Send Request + // METHOD | GET + int httpCode = http.sendRequest("GET", reinterpret_cast(&payload[0]), payload.length()); + + // Handle Request + String output = http.getString(); + std::string output_string = output.c_str(); + + http.end(); + + + Response response(output, httpCode); + return response; + } + + Response< + String + > + UserApi:: + updateUser( + + std::string username + , + + User user + + ) + { + std::string url = basepath + "/user/{username}"; //username + // Query | + // Headers | + // Form | + // Body | user + + std::string s_username("{"); + s_username.append("username"); + s_username.append("}"); + + int pos = url.find(s_username); + + url.erase(pos, s_username.length()); + url.insert(pos, stringify(username)); + + begin(url); + + std::string payload = ""; + // Send Request + // METHOD | PUT + http.addHeader("Content-Type", "application/json"); + + + + payload = user.toJson().dump(); + + int httpCode = http.sendRequest("PUT", reinterpret_cast(&payload[0]), payload.length()); + + // Handle Request + String output = http.getString(); + std::string output_string = output.c_str(); + + http.end(); + + + Response response(output, httpCode); + return response; + } + + + + diff --git a/samples/client/petstore/cpp-tiny/lib/service/UserApi.h b/samples/client/petstore/cpp-tiny/lib/service/UserApi.h new file mode 100644 index 00000000000..afdaefa0f8c --- /dev/null +++ b/samples/client/petstore/cpp-tiny/lib/service/UserApi.h @@ -0,0 +1,147 @@ +#ifndef TINY_CPP_CLIENT_UserApi_H_ +#define TINY_CPP_CLIENT_UserApi_H_ + + +#include "Response.h" +#include "Arduino.h" +#include "AbstractService.h" +#include "Helpers.h" +#include + +#include "User.h" +#include + +namespace Tiny { + +/** + * Class + * Generated with openapi::tiny-cpp-client + */ + +class UserApi : public AbstractService { +public: + UserApi() = default; + + virtual ~UserApi() = default; + + /** + * Create user. + * + * This can only be done by the logged in user. + * \param user Created user object *Required* + */ + Response< + String + > + createUser( + + User user + + ); + /** + * Creates list of users with given input array. + * + * + * \param user List of user object *Required* + */ + Response< + String + > + createUsersWithArrayInput( + std::list user + + + ); + /** + * Creates list of users with given input array. + * + * + * \param user List of user object *Required* + */ + Response< + String + > + createUsersWithListInput( + std::list user + + + ); + /** + * Delete user. + * + * This can only be done by the logged in user. + * \param username The name that needs to be deleted *Required* + */ + Response< + String + > + deleteUser( + + std::string username + + ); + /** + * Get user by user name. + * + * + * \param username The name that needs to be fetched. Use user1 for testing. *Required* + */ + Response< + User + > + getUserByName( + + std::string username + + ); + /** + * Logs user into the system. + * + * + * \param username The user name for login *Required* + * \param password The password for login in clear text *Required* + */ + Response< + std::string + > + loginUser( + + std::string username + , + + std::string password + + ); + /** + * Logs out current logged in user session. + * + * + */ + Response< + String + > + logoutUser( + ); + /** + * Updated user. + * + * This can only be done by the logged in user. + * \param username name that need to be deleted *Required* + * \param user Updated user object *Required* + */ + Response< + String + > + updateUser( + + std::string username + , + + User user + + ); +}; + +} + +#endif /* TINY_CPP_CLIENT_UserApi_H_ */ \ No newline at end of file diff --git a/samples/client/petstore/cpp-tiny/platformio.ini b/samples/client/petstore/cpp-tiny/platformio.ini new file mode 100644 index 00000000000..00781178d10 --- /dev/null +++ b/samples/client/petstore/cpp-tiny/platformio.ini @@ -0,0 +1,7 @@ +[env:esp32] +platform = espressif32 +board = nodemcu-32s +framework = arduino +lib_deps = https://github.com/steinwurf/bourne.git +extra_scripts = pre_compiling_bourne.py + diff --git a/samples/client/petstore/cpp-tiny/pre_compiling_bourne.py b/samples/client/petstore/cpp-tiny/pre_compiling_bourne.py new file mode 100644 index 00000000000..96356dcdf15 --- /dev/null +++ b/samples/client/petstore/cpp-tiny/pre_compiling_bourne.py @@ -0,0 +1,25 @@ +Import("env") + +## Compatibility for bourne to work on microcontrollers +# We insert '#define _GLIBCXX_USE_C99' in files that use std::stoll or std::to_string +def insert_c99_into(file): + import fileinput + + path = env['PROJECT_LIBDEPS_DIR'] + "/" + env['PIOENV'] + "/bourne/src/bourne/" + file + value = '#define _GLIBCXX_USE_C99 1\n' + + for line in fileinput.FileInput(path,inplace=1): + if line.startswith('#define _GLIBCXX_USE_C99'): + continue + elif line.startswith('// D'): + line=line.replace(line,line+value) + print(line, end='') + +def fix_parser(): + insert_c99_into('detail/parser.cpp') + +def fix_json(): + insert_c99_into('json.cpp') + +fix_parser() +fix_json() \ No newline at end of file diff --git a/samples/client/petstore/cpp-tiny/root.cert b/samples/client/petstore/cpp-tiny/root.cert new file mode 100644 index 00000000000..bad9c08efad --- /dev/null +++ b/samples/client/petstore/cpp-tiny/root.cert @@ -0,0 +1,53 @@ +// TODO: Provide your service root certificate. +// Below is two examples of root certificates. + +// Let's encrypt root certificate +/** +"-----BEGIN CERTIFICATE-----\n" \ +"MIIDrzCCApegAwIBAgIQCDvgVpBCRrGhdWrJWZHHSjANBgkqhkiG9w0BAQUFADBh\n" \ +"MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3\n" \ +"d3cuZGlnaWNlcnQuY29tMSAwHgYDVQQDExdEaWdpQ2VydCBHbG9iYWwgUm9vdCBD\n" \ +"QTAeFw0wNjExMTAwMDAwMDBaFw0zMTExMTAwMDAwMDBaMGExCzAJBgNVBAYTAlVT\n" \ +"MRUwEwYDVQQKEwxEaWdpQ2VydCBJbmMxGTAXBgNVBAsTEHd3dy5kaWdpY2VydC5j\n" \ +"b20xIDAeBgNVBAMTF0RpZ2lDZXJ0IEdsb2JhbCBSb290IENBMIIBIjANBgkqhkiG\n" \ +"9w0BAQEFAAOCAQ8AMIIBCgKCAQEA4jvhEXLeqKTTo1eqUKKPC3eQyaKl7hLOllsB\n" \ +"CSDMAZOnTjC3U/dDxGkAV53ijSLdhwZAAIEJzs4bg7/fzTtxRuLWZscFs3YnFo97\n" \ +"nh6Vfe63SKMI2tavegw5BmV/Sl0fvBf4q77uKNd0f3p4mVmFaG5cIzJLv07A6Fpt\n" \ +"43C/dxC//AH2hdmoRBBYMql1GNXRor5H4idq9Joz+EkIYIvUX7Q6hL+hqkpMfT7P\n" \ +"T19sdl6gSzeRntwi5m3OFBqOasv+zbMUZBfHWymeMr/y7vrTC0LUq7dBMtoM1O/4\n" \ +"gdW7jVg/tRvoSSiicNoxBN33shbyTApOB6jtSj1etX+jkMOvJwIDAQABo2MwYTAO\n" \ +"BgNVHQ8BAf8EBAMCAYYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUA95QNVbR\n" \ +"TLtm8KPiGxvDl7I90VUwHwYDVR0jBBgwFoAUA95QNVbRTLtm8KPiGxvDl7I90VUw\n" \ +"DQYJKoZIhvcNAQEFBQADggEBAMucN6pIExIK+t1EnE9SsPTfrgT1eXkIoyQY/Esr\n" \ +"hMAtudXH/vTBH1jLuG2cenTnmCmrEbXjcKChzUyImZOMkXDiqw8cvpOp/2PV5Adg\n" \ +"06O/nVsJ8dWO41P0jmP6P6fbtGbfYmbW0W5BjfIttep3Sp+dWOIrWcBAI+0tKIJF\n" \ +"PnlUkiaY4IBIqDfv8NZ5YBberOgOzW6sRBc4L0na4UU+Krk2U886UAb3LujEV0ls\n" \ +"YSEY1QSteDwsOoBrp+uvFRTp2InBuThs4pFsiv9kuXclVzDAGySj4dzp30d8tbQk\n" \ +"CAUw7C29C79Fv1C5qfPrmAESrciIxpg0X40KPMbp1ZWVbd4=\n" \ +"-----END CERTIFICATE-----\n" +*/ + +// Amazon_Root_CA_1.pem +/** +"-----BEGIN CERTIFICATE-----\n" \ +"MIIDQTCCAimgAwIBAgITBmyfz5m/jAo54vB4ikPmljZbyjANBgkqhkiG9w0BAQsF\n" \ +"ADA5MQswCQYDVQQGEwJVUzEPMA0GA1UEChMGQW1hem9uMRkwFwYDVQQDExBBbWF6\n" \ +"b24gUm9vdCBDQSAxMB4XDTE1MDUyNjAwMDAwMFoXDTM4MDExNzAwMDAwMFowOTEL\n" \ +"MAkGA1UEBhMCVVMxDzANBgNVBAoTBkFtYXpvbjEZMBcGA1UEAxMQQW1hem9uIFJv\n" \ +"b3QgQ0EgMTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALJ4gHHKeNXj\n" \ +"ca9HgFB0fW7Y14h29Jlo91ghYPl0hAEvrAIthtOgQ3pOsqTQNroBvo3bSMgHFzZM\n" \ +"9O6II8c+6zf1tRn4SWiw3te5djgdYZ6k/oI2peVKVuRF4fn9tBb6dNqcmzU5L/qw\n" \ +"IFAGbHrQgLKm+a/sRxmPUDgH3KKHOVj4utWp+UhnMJbulHheb4mjUcAwhmahRWa6\n" \ +"VOujw5H5SNz/0egwLX0tdHA114gk957EWW67c4cX8jJGKLhD+rcdqsq08p8kDi1L\n" \ +"93FcXmn/6pUCyziKrlA4b9v7LWIbxcceVOF34GfID5yHI9Y/QCB/IIDEgEw+OyQm\n" \ +"jgSubJrIqg0CAwEAAaNCMEAwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMC\n" \ +"AYYwHQYDVR0OBBYEFIQYzIU07LwMlJQuCFmcx7IQTgoIMA0GCSqGSIb3DQEBCwUA\n" \ +"A4IBAQCY8jdaQZChGsV2USggNiMOruYou6r4lK5IpDB/G/wkjUu0yKGX9rbxenDI\n" \ +"U5PMCCjjmCXPI6T53iHTfIUJrU6adTrCC2qJeHZERxhlbI1Bjjt/msv0tadQ1wUs\n" \ +"N+gDS63pYaACbvXy8MWy7Vu33PqUXHeeE6V/Uq2V8viTO96LXFvKWlJbYK8U90vv\n" \ +"o/ufQJVtMVT8QtPHRh8jrdkPSHCa2XV4cdFyQzR1bldZwgJcJmApzyMZFo6IQ6XU\n" \ +"5MsI+yMRQ+hDKXJioaldXgjUkK642M4UwtBV8ob2xJNDd2ZhwLnoQdeXeGADbkpy\n" \ +"rqXRfboQnoZsG4q5WTP468SQvvG5\n" \ +"-----END CERTIFICATE-----\n" \ +*/ + diff --git a/samples/client/petstore/cpp-tiny/src/main.cpp b/samples/client/petstore/cpp-tiny/src/main.cpp new file mode 100644 index 00000000000..34ba455fbdd --- /dev/null +++ b/samples/client/petstore/cpp-tiny/src/main.cpp @@ -0,0 +1,37 @@ +#include "PetApi.h" + +const char* ssid = "your wifi name"; // TODO Change wifi name +const char* password = "Your wifi password"; //TODO Change wifi password + + +void setup(){ + //Initialize serial and wait for port to open: + Serial.begin(9600); + delay(100); + + Serial.print("Attempting to connect to SSID: "); + Serial.println(ssid); + WiFi.begin(ssid, password); + + // attempt to connect to Wifi network: + while (WiFi.status() != WL_CONNECTED) { + Serial.print("."); + // wait 1 second for re-trying + delay(1000); + } + + Serial.print("Connected to "); + Serial.println(ssid); + + //Print LAN IP. + Serial.print("IP address set: "); + Serial.println(WiFi.localIP()); + + Tiny::PetApi petapi; + auto resp = petapi.getPetById(10); + Serial.println(resp.code); + Tiny::Pet pet = resp.obj; + Serial.println(pet.toJson().dump().c_str()); +} + +void loop(){} diff --git a/samples/client/petstore/cpp-tiny/test/RunTests.cpp b/samples/client/petstore/cpp-tiny/test/RunTests.cpp new file mode 100644 index 00000000000..4caafb4ee44 --- /dev/null +++ b/samples/client/petstore/cpp-tiny/test/RunTests.cpp @@ -0,0 +1,204 @@ + +#include "ApiResponseTest.cpp" + +#include "CategoryTest.cpp" + +#include "OrderTest.cpp" + +#include "PetTest.cpp" + +#include "TagTest.cpp" + +#include "UserTest.cpp" + + + +void setUp(){} + +void tearDown(){} + +void runTests(){ + + + RUN_TEST(test_ApiResponse_code_is_assigned_from_json); + + + RUN_TEST(test_ApiResponse_type_is_assigned_from_json); + + + RUN_TEST(test_ApiResponse_message_is_assigned_from_json); + + + + RUN_TEST(test_Category_id_is_assigned_from_json); + + + RUN_TEST(test_Category_name_is_assigned_from_json); + + + + RUN_TEST(test_Order_id_is_assigned_from_json); + + + RUN_TEST(test_Order_petId_is_assigned_from_json); + + + RUN_TEST(test_Order_quantity_is_assigned_from_json); + + + RUN_TEST(test_Order_shipDate_is_assigned_from_json); + + + RUN_TEST(test_Order_status_is_assigned_from_json); + + + RUN_TEST(test_Order_complete_is_assigned_from_json); + + + + RUN_TEST(test_Pet_id_is_assigned_from_json); + + + + RUN_TEST(test_Pet_name_is_assigned_from_json); + + + + + RUN_TEST(test_Pet_status_is_assigned_from_json); + + + + RUN_TEST(test_Tag_id_is_assigned_from_json); + + + RUN_TEST(test_Tag_name_is_assigned_from_json); + + + + RUN_TEST(test_User_id_is_assigned_from_json); + + + RUN_TEST(test_User_username_is_assigned_from_json); + + + RUN_TEST(test_User_firstName_is_assigned_from_json); + + + RUN_TEST(test_User_lastName_is_assigned_from_json); + + + RUN_TEST(test_User_email_is_assigned_from_json); + + + RUN_TEST(test_User_password_is_assigned_from_json); + + + RUN_TEST(test_User_phone_is_assigned_from_json); + + + RUN_TEST(test_User_userStatus_is_assigned_from_json); + + + + + + RUN_TEST(test_ApiResponse_code_is_converted_to_json); + + + RUN_TEST(test_ApiResponse_type_is_converted_to_json); + + + RUN_TEST(test_ApiResponse_message_is_converted_to_json); + + + + RUN_TEST(test_Category_id_is_converted_to_json); + + + RUN_TEST(test_Category_name_is_converted_to_json); + + + + RUN_TEST(test_Order_id_is_converted_to_json); + + + RUN_TEST(test_Order_petId_is_converted_to_json); + + + RUN_TEST(test_Order_quantity_is_converted_to_json); + + + RUN_TEST(test_Order_shipDate_is_converted_to_json); + + + RUN_TEST(test_Order_status_is_converted_to_json); + + + RUN_TEST(test_Order_complete_is_converted_to_json); + + + + RUN_TEST(test_Pet_id_is_converted_to_json); + + + + RUN_TEST(test_Pet_name_is_converted_to_json); + + + + + RUN_TEST(test_Pet_status_is_converted_to_json); + + + + RUN_TEST(test_Tag_id_is_converted_to_json); + + + RUN_TEST(test_Tag_name_is_converted_to_json); + + + + RUN_TEST(test_User_id_is_converted_to_json); + + + RUN_TEST(test_User_username_is_converted_to_json); + + + RUN_TEST(test_User_firstName_is_converted_to_json); + + + RUN_TEST(test_User_lastName_is_converted_to_json); + + + RUN_TEST(test_User_email_is_converted_to_json); + + + RUN_TEST(test_User_password_is_converted_to_json); + + + RUN_TEST(test_User_phone_is_converted_to_json); + + + RUN_TEST(test_User_userStatus_is_converted_to_json); + + + + +} + +int main(void) { + UNITY_BEGIN(); + runTests(); + return UNITY_END(); +} + +void setup() { + UNITY_BEGIN(); + runTests(); + UNITY_END(); +} + +void loop() { + +} diff --git a/samples/client/petstore/crystal/.openapi-generator/VERSION b/samples/client/petstore/crystal/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/client/petstore/crystal/.openapi-generator/VERSION +++ b/samples/client/petstore/crystal/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/client/petstore/crystal/.travis.yml b/samples/client/petstore/crystal/.travis.yml index 572732b4a5b..c94f5891df2 100644 --- a/samples/client/petstore/crystal/.travis.yml +++ b/samples/client/petstore/crystal/.travis.yml @@ -5,7 +5,11 @@ #The version of the OpenAPI document: 1.0.0 # #Generated by: https://openapi-generator.tech +<<<<<<< HEAD #OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +#OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x # language: crystal diff --git a/samples/client/petstore/crystal/bin/ameba b/samples/client/petstore/crystal/bin/ameba index 332b8c750a4..c88ac4a8d02 100755 Binary files a/samples/client/petstore/crystal/bin/ameba and b/samples/client/petstore/crystal/bin/ameba differ diff --git a/samples/client/petstore/crystal/pom.xml b/samples/client/petstore/crystal/pom.xml index f4b890f7d80..29b7e4bc351 100644 --- a/samples/client/petstore/crystal/pom.xml +++ b/samples/client/petstore/crystal/pom.xml @@ -34,6 +34,10 @@ shards + + install + --ignore-crystal-version + diff --git a/samples/client/petstore/crystal/shard.lock b/samples/client/petstore/crystal/shard.lock index 97567adcb9e..6a33ec4f671 100644 --- a/samples/client/petstore/crystal/shard.lock +++ b/samples/client/petstore/crystal/shard.lock @@ -2,23 +2,23 @@ version: 2.0 shards: ameba: git: https://github.com/crystal-ameba/ameba.git - version: 0.13.3 + version: 0.14.3 crest: git: https://github.com/mamantoha/crest.git - version: 0.26.1 + version: 0.26.8 exception_page: git: https://github.com/crystal-loot/exception_page.git - version: 0.1.4 + version: 0.1.5 http-client-digest_auth: git: https://github.com/mamantoha/http-client-digest_auth.git - version: 0.4.0 + version: 0.6.0 http_proxy: git: https://github.com/mamantoha/http_proxy.git - version: 0.7.2 + version: 0.8.0 kemal: git: https://github.com/kemalcr/kemal.git @@ -26,7 +26,7 @@ shards: kilt: git: https://github.com/jeromegn/kilt.git - version: 0.4.0 + version: 0.4.1 radix: git: https://github.com/luislavena/radix.git diff --git a/samples/client/petstore/crystal/spec/api/pet_api_spec.cr b/samples/client/petstore/crystal/spec/api/pet_api_spec.cr index 23bdfa81847..5c5f56295ac 100644 --- a/samples/client/petstore/crystal/spec/api/pet_api_spec.cr +++ b/samples/client/petstore/crystal/spec/api/pet_api_spec.cr @@ -79,7 +79,16 @@ describe "PetApi" do describe "get_pet_by_id test" do it "should work" do # assertion here. ref: https://crystal-lang.org/reference/guides/testing.html - api_instance = Petstore::PetApi.new + + config = Petstore::Configuration.new + config.access_token = "yyy" + config.api_key[:api_key] = "xxx" + config.api_key_prefix[:api_key] = "Token" + + api_client = Petstore::ApiClient.new(config) + + api_instance = Petstore::PetApi.new(api_client) + # create a pet to start with pet_id = Int64.new(91829) pet = Petstore::Pet.new(id: pet_id, category: Petstore::Category.new(id: pet_id + 10, name: "crystal category"), name: "crystal", photo_urls: ["https://crystal-lang.org"], tags: [Petstore::Tag.new(id: pet_id + 100, name: "crystal tag")], status: "available") diff --git a/samples/client/petstore/crystal/spec/api_client_spec.cr b/samples/client/petstore/crystal/spec/api_client_spec.cr new file mode 100644 index 00000000000..18209417eab --- /dev/null +++ b/samples/client/petstore/crystal/spec/api_client_spec.cr @@ -0,0 +1,56 @@ +require "./spec_helper" + +describe Petstore::ApiClient do + describe "#update_params_for_auth!" do + describe "oauth2" do + it "should add 'Authorization' to header" do + config = Petstore::Configuration.new + config.access_token = "xxx" + + header_params = {} of String => String + query_params = {} of String => String + + api_client = Petstore::ApiClient.new(config) + api_client.update_params_for_auth!(header_params, query_params, ["petstore_auth"]) + + header_params["Authorization"].should eq "Bearer xxx" + query_params.size.should eq 0 + end + end + + describe "api_key" do + context "without api_key_prefix" do + it "should add 'api_key' to header" do + config = Petstore::Configuration.new + config.api_key[:api_key] = "xxx" + + header_params = {} of String => String + query_params = {} of String => String + + api_client = Petstore::ApiClient.new(config) + api_client.update_params_for_auth!(header_params, query_params, ["api_key"]) + + header_params["api_key"].should eq "xxx" + query_params.empty?.should be_true + end + end + + context "with api_key_prefix" do + it "should add 'api_key' to header" do + config = Petstore::Configuration.new + config.api_key[:api_key] = "xxx" + config.api_key_prefix[:api_key] = "Token" + + header_params = {} of String => String + query_params = {} of String => String + + api_client = Petstore::ApiClient.new(config) + api_client.update_params_for_auth!(header_params, query_params, ["api_key"]) + + header_params["api_key"].should eq "Token xxx" + query_params.empty?.should be_true + end + end + end + end +end diff --git a/samples/client/petstore/crystal/spec/configuration_spec.cr b/samples/client/petstore/crystal/spec/configuration_spec.cr new file mode 100644 index 00000000000..a99e77166dd --- /dev/null +++ b/samples/client/petstore/crystal/spec/configuration_spec.cr @@ -0,0 +1,26 @@ +require "./spec_helper" + +describe Petstore::Configuration do + describe "#initialize" do + context "with block" do + it "works" do + config = Petstore::Configuration.new do |config| + config.username = "xxx" + end + + config.username.should eq "xxx" + end + end + end + + describe "#configure" do + it "works" do + config = Petstore::Configuration.new + config.configure do |config| + config.username = "xxx" + end + + config.username.should eq "xxx" + end + end +end diff --git a/samples/client/petstore/crystal/spec/petstore_spec.cr b/samples/client/petstore/crystal/spec/petstore_spec.cr new file mode 100644 index 00000000000..cca7698a536 --- /dev/null +++ b/samples/client/petstore/crystal/spec/petstore_spec.cr @@ -0,0 +1,19 @@ +require "./spec_helper" + +describe Petstore do + describe "#configure" do + it "works" do + Petstore.configure do |config| + config.username = "xxx" + end + + config = Petstore.configure + + config.should eq Petstore::Configuration.default + config.username.should eq "xxx" + + # Clean up + Petstore::Configuration.default.username = nil + end + end +end diff --git a/samples/client/petstore/crystal/spec/spec_helper.cr b/samples/client/petstore/crystal/spec/spec_helper.cr index dddb173a221..6728fcac6f2 100644 --- a/samples/client/petstore/crystal/spec/spec_helper.cr +++ b/samples/client/petstore/crystal/spec/spec_helper.cr @@ -5,7 +5,11 @@ #The version of the OpenAPI document: 1.0.0 # #Generated by: https://openapi-generator.tech +<<<<<<< HEAD #OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +#OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x # # load modules diff --git a/samples/client/petstore/crystal/src/petstore.cr b/samples/client/petstore/crystal/src/petstore.cr index 43a3fb124a2..765503bdf7a 100644 --- a/samples/client/petstore/crystal/src/petstore.cr +++ b/samples/client/petstore/crystal/src/petstore.cr @@ -5,7 +5,11 @@ #The version of the OpenAPI document: 1.0.0 # #Generated by: https://openapi-generator.tech +<<<<<<< HEAD #OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +#OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x # # Dependencies @@ -17,18 +21,21 @@ module Petstore VERSION = {{ `shards version #{__DIR__}`.chomp.stringify }} + # Return the default `Configuration` object. + def self.configure + Configuration.default + end + # Customize default settings for the SDK using block. - # Petstore.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 + # + # ``` + # Petstore.configure do |config| + # config.username = "xxx" + # config.password = "xxx" + # end + # ``` + def self.configure + yield Configuration.default end end 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 10b6ac226e1..1c8ad8d1565 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,11 @@ #The version of the OpenAPI document: 1.0.0 # #Generated by: https://openapi-generator.tech +<<<<<<< HEAD #OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +#OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x # require "uri" @@ -40,7 +44,7 @@ module Petstore local_var_path = "/pet" # query parameters - query_params = Hash(Symbol, String).new + query_params = Hash(String, String).new # header parameters header_params = Hash(String, String).new @@ -99,7 +103,7 @@ module Petstore local_var_path = "/pet/{petId}".sub("{" + "petId" + "}", URI.encode(pet_id.to_s).gsub("%2F", "/")) # query parameters - query_params = Hash(Symbol, String).new + query_params = Hash(String, String).new # header parameters header_params = Hash(String, String).new @@ -157,8 +161,8 @@ module Petstore local_var_path = "/pet/findByStatus" # query parameters - query_params = Hash(Symbol, String).new - query_params[:"status"] = @api_client.build_collection_param(status, :csv) + query_params = Hash(String, String).new + query_params["status"] = @api_client.build_collection_param(status, :csv) # header parameters header_params = Hash(String, String).new @@ -217,8 +221,8 @@ module Petstore local_var_path = "/pet/findByTags" # query parameters - query_params = Hash(Symbol, String).new - query_params[:"tags"] = @api_client.build_collection_param(tags, :csv) + query_params = Hash(String, String).new + query_params["tags"] = @api_client.build_collection_param(tags, :csv) # header parameters header_params = Hash(String, String).new @@ -277,7 +281,7 @@ module Petstore local_var_path = "/pet/{petId}".sub("{" + "petId" + "}", URI.encode(pet_id.to_s).gsub("%2F", "/")) # query parameters - query_params = Hash(Symbol, String).new + query_params = Hash(String, String).new # header parameters header_params = Hash(String, String).new @@ -334,7 +338,7 @@ module Petstore local_var_path = "/pet" # query parameters - query_params = Hash(Symbol, String).new + query_params = Hash(String, String).new # header parameters header_params = Hash(String, String).new @@ -393,7 +397,7 @@ module Petstore local_var_path = "/pet/{petId}".sub("{" + "petId" + "}", URI.encode(pet_id.to_s).gsub("%2F", "/")) # query parameters - query_params = Hash(Symbol, String).new + query_params = Hash(String, String).new # header parameters header_params = Hash(String, String).new @@ -452,7 +456,7 @@ module Petstore local_var_path = "/pet/{petId}/uploadImage".sub("{" + "petId" + "}", URI.encode(pet_id.to_s).gsub("%2F", "/")) # query parameters - query_params = Hash(Symbol, String).new + query_params = Hash(String, String).new # header parameters header_params = Hash(String, String).new 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 7cd7e3ee8e5..310b1035d80 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,11 @@ #The version of the OpenAPI document: 1.0.0 # #Generated by: https://openapi-generator.tech +<<<<<<< HEAD #OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +#OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x # require "uri" @@ -42,7 +46,7 @@ module Petstore local_var_path = "/store/order/{orderId}".sub("{" + "orderId" + "}", URI.encode(order_id.to_s).gsub("%2F", "/")) # query parameters - query_params = Hash(Symbol, String).new + query_params = Hash(String, String).new # header parameters header_params = Hash(String, String).new @@ -93,7 +97,7 @@ module Petstore local_var_path = "/store/inventory" # query parameters - query_params = Hash(Symbol, String).new + query_params = Hash(String, String).new # header parameters header_params = Hash(String, String).new @@ -160,7 +164,7 @@ module Petstore local_var_path = "/store/order/{orderId}".sub("{" + "orderId" + "}", URI.encode(order_id.to_s).gsub("%2F", "/")) # query parameters - query_params = Hash(Symbol, String).new + query_params = Hash(String, String).new # header parameters header_params = Hash(String, String).new @@ -217,7 +221,7 @@ module Petstore local_var_path = "/store/order" # query parameters - query_params = Hash(Symbol, String).new + query_params = Hash(String, String).new # header parameters header_params = Hash(String, String).new 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 97894e0d46b..8eb232d68a5 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,11 @@ #The version of the OpenAPI document: 1.0.0 # #Generated by: https://openapi-generator.tech +<<<<<<< HEAD #OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +#OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x # require "uri" @@ -42,7 +46,7 @@ module Petstore local_var_path = "/user" # query parameters - query_params = Hash(Symbol, String).new + query_params = Hash(String, String).new # header parameters header_params = Hash(String, String).new @@ -99,7 +103,7 @@ module Petstore local_var_path = "/user/createWithArray" # query parameters - query_params = Hash(Symbol, String).new + query_params = Hash(String, String).new # header parameters header_params = Hash(String, String).new @@ -156,7 +160,7 @@ module Petstore local_var_path = "/user/createWithList" # query parameters - query_params = Hash(Symbol, String).new + query_params = Hash(String, String).new # header parameters header_params = Hash(String, String).new @@ -215,7 +219,7 @@ module Petstore local_var_path = "/user/{username}".sub("{" + "username" + "}", URI.encode(username.to_s).gsub("%2F", "/")) # query parameters - query_params = Hash(Symbol, String).new + query_params = Hash(String, String).new # header parameters header_params = Hash(String, String).new @@ -270,7 +274,7 @@ module Petstore local_var_path = "/user/{username}".sub("{" + "username" + "}", URI.encode(username.to_s).gsub("%2F", "/")) # query parameters - query_params = Hash(Symbol, String).new + query_params = Hash(String, String).new # header parameters header_params = Hash(String, String).new @@ -338,9 +342,9 @@ module Petstore local_var_path = "/user/login" # query parameters - query_params = Hash(Symbol, String).new - query_params[:"username"] = username - query_params[:"password"] = password + query_params = Hash(String, String).new + query_params["username"] = username + query_params["password"] = password # header parameters header_params = Hash(String, String).new @@ -391,7 +395,7 @@ module Petstore local_var_path = "/user/logout" # query parameters - query_params = Hash(Symbol, String).new + query_params = Hash(String, String).new # header parameters header_params = Hash(String, String).new @@ -454,7 +458,7 @@ module Petstore local_var_path = "/user/{username}".sub("{" + "username" + "}", URI.encode(username.to_s).gsub("%2F", "/")) # query parameters - query_params = Hash(Symbol, String).new + query_params = Hash(String, String).new # header parameters header_params = Hash(String, String).new diff --git a/samples/client/petstore/crystal/src/petstore/api_client.cr b/samples/client/petstore/crystal/src/petstore/api_client.cr index a93932fbe4d..50e5933b80b 100644 --- a/samples/client/petstore/crystal/src/petstore/api_client.cr +++ b/samples/client/petstore/crystal/src/petstore/api_client.cr @@ -5,7 +5,11 @@ #The version of the OpenAPI document: 1.0.0 # #Generated by: https://openapi-generator.tech +<<<<<<< HEAD #OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +#OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x # require "json" @@ -171,7 +175,7 @@ module Petstore # @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_names.each do |auth_name| auth_setting = @config.auth_settings[auth_name] next unless auth_setting case auth_setting[:in] @@ -264,7 +268,7 @@ module Petstore # # @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 : Symbol, path : String, operation : Symbol, return_type : String, post_body : String?, auth_names = [] of String, header_params = {} of String => String, query_params = {} of Symbol => String, form_params = {} of Symbol => String) + def call_api(http_method : Symbol, path : String, operation : Symbol, return_type : String, post_body : String?, auth_names = [] of String, header_params = {} of String => String, query_params = {} of String => String, form_params = {} of Symbol => String) #ssl_options = { # :ca_file => @config.ssl_ca_file, # :verify => @config.ssl_verify, @@ -282,6 +286,8 @@ module Petstore # conn.adapter(Faraday.default_adapter) #end + update_params_for_auth! header_params, query_params, auth_names + if !post_body.nil? && !post_body.empty? # use JSON string in the payload form_or_body = post_body diff --git a/samples/client/petstore/crystal/src/petstore/api_error.cr b/samples/client/petstore/crystal/src/petstore/api_error.cr index 03555af9b6a..f58acc52a2a 100644 --- a/samples/client/petstore/crystal/src/petstore/api_error.cr +++ b/samples/client/petstore/crystal/src/petstore/api_error.cr @@ -5,7 +5,11 @@ #The version of the OpenAPI document: 1.0.0 # #Generated by: https://openapi-generator.tech +<<<<<<< HEAD #OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +#OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x # module Petstore diff --git a/samples/client/petstore/crystal/src/petstore/configuration.cr b/samples/client/petstore/crystal/src/petstore/configuration.cr index 5eab84ae97d..5226ca95cbd 100644 --- a/samples/client/petstore/crystal/src/petstore/configuration.cr +++ b/samples/client/petstore/crystal/src/petstore/configuration.cr @@ -5,7 +5,11 @@ #The version of the OpenAPI document: 1.0.0 # #Generated by: https://openapi-generator.tech +<<<<<<< HEAD #OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +#OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x # require "log" @@ -38,7 +42,7 @@ module Petstore # @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" + # config.api_key[:api_key] = "xxx" property api_key : Hash(Symbol, String) # Defines API key prefixes used with API Key authentications. @@ -46,7 +50,7 @@ module Petstore # @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" + # config.api_key_prefix[:api_key] = "Token" property api_key_prefix : Hash(Symbol, String) # Defines the username used with HTTP basic authentication. @@ -127,6 +131,7 @@ module Petstore # https://github.com/typhoeus/ethon/blob/master/lib/ethon/easy/queryable.rb#L96 #property params_encoding : String? + # Create a new `Configuration`. def initialize @scheme = "http" @host = "petstore.swagger.io" @@ -149,9 +154,19 @@ module Petstore @password = nil @access_token = nil @temp_folder_path = nil + end - # TODO revise below to support block - #yield(self) if block_given? + # Create a new `Configuration` with block. + # + # ``` + # config = Petstore::Configuration.new do |config| + # config.username = "xxx" + # config.password = "xxx" + # end + # ``` + def initialize + initialize + yield self end # The default Configuration object. @@ -159,8 +174,9 @@ module Petstore @@default ||= Configuration.new end + # Configure object with block. def configure - yield(self) if block_given? + yield self end def scheme=(scheme) @@ -191,10 +207,10 @@ module Petstore # 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) - if @api_key_prefix[param_name] - "#{@api_key_prefix[param_name]} #{@api_key[param_name]}" + if prefix = @api_key_prefix[param_name]? + "#{prefix} #{@api_key[param_name]}" else - @api_key[param_name] + @api_key[param_name]? || "" end end @@ -210,7 +226,7 @@ module Petstore type: "api_key", in: "header", key: "api_key", - value: api_key_with_prefix("api_key") + value: api_key_with_prefix(:api_key) }, "petstore_auth" => { type: "oauth2", 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 3359594145f..1bd454ff570 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,11 @@ #The version of the OpenAPI document: 1.0.0 # #Generated by: https://openapi-generator.tech +<<<<<<< HEAD #OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +#OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x # require "json" diff --git a/samples/client/petstore/crystal/src/petstore/models/category.cr b/samples/client/petstore/crystal/src/petstore/models/category.cr index 0fb84faf74b..4a5b2b176ad 100644 --- a/samples/client/petstore/crystal/src/petstore/models/category.cr +++ b/samples/client/petstore/crystal/src/petstore/models/category.cr @@ -5,7 +5,11 @@ #The version of the OpenAPI document: 1.0.0 # #Generated by: https://openapi-generator.tech +<<<<<<< HEAD #OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +#OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x # require "json" diff --git a/samples/client/petstore/crystal/src/petstore/models/order.cr b/samples/client/petstore/crystal/src/petstore/models/order.cr index 656c61b86b7..8e782ea72fd 100644 --- a/samples/client/petstore/crystal/src/petstore/models/order.cr +++ b/samples/client/petstore/crystal/src/petstore/models/order.cr @@ -5,7 +5,11 @@ #The version of the OpenAPI document: 1.0.0 # #Generated by: https://openapi-generator.tech +<<<<<<< HEAD #OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +#OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x # require "json" diff --git a/samples/client/petstore/crystal/src/petstore/models/pet.cr b/samples/client/petstore/crystal/src/petstore/models/pet.cr index c6471d5672a..3e3f8fde44d 100644 --- a/samples/client/petstore/crystal/src/petstore/models/pet.cr +++ b/samples/client/petstore/crystal/src/petstore/models/pet.cr @@ -5,7 +5,11 @@ #The version of the OpenAPI document: 1.0.0 # #Generated by: https://openapi-generator.tech +<<<<<<< HEAD #OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +#OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x # require "json" diff --git a/samples/client/petstore/crystal/src/petstore/models/tag.cr b/samples/client/petstore/crystal/src/petstore/models/tag.cr index ab09edc3291..f2b81f2f6d2 100644 --- a/samples/client/petstore/crystal/src/petstore/models/tag.cr +++ b/samples/client/petstore/crystal/src/petstore/models/tag.cr @@ -5,7 +5,11 @@ #The version of the OpenAPI document: 1.0.0 # #Generated by: https://openapi-generator.tech +<<<<<<< HEAD #OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +#OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x # require "json" diff --git a/samples/client/petstore/crystal/src/petstore/models/user.cr b/samples/client/petstore/crystal/src/petstore/models/user.cr index 8c0fbfde5dc..acfc1431f59 100644 --- a/samples/client/petstore/crystal/src/petstore/models/user.cr +++ b/samples/client/petstore/crystal/src/petstore/models/user.cr @@ -5,7 +5,11 @@ #The version of the OpenAPI document: 1.0.0 # #Generated by: https://openapi-generator.tech +<<<<<<< HEAD #OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +#OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x # require "json" diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/.gitignore b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/.gitignore new file mode 100644 index 00000000000..1ee53850b84 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/.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/server/petstore/cpp-qt5-qhttpengine-server/.openapi-generator-ignore b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/.openapi-generator-ignore similarity index 100% rename from samples/server/petstore/cpp-qt5-qhttpengine-server/.openapi-generator-ignore rename to samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/.openapi-generator-ignore diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/.openapi-generator/FILES b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/.openapi-generator/FILES new file mode 100644 index 00000000000..d258eb64b2f --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/.openapi-generator/FILES @@ -0,0 +1,187 @@ +.gitignore +Org.OpenAPITools.sln +README.md +appveyor.yml +docs/AdditionalPropertiesClass.md +docs/Animal.md +docs/AnotherFakeApi.md +docs/ApiResponse.md +docs/Apple.md +docs/AppleReq.md +docs/ArrayOfArrayOfNumberOnly.md +docs/ArrayOfNumberOnly.md +docs/ArrayTest.md +docs/Banana.md +docs/BananaReq.md +docs/BasquePig.md +docs/Capitalization.md +docs/Cat.md +docs/CatAllOf.md +docs/Category.md +docs/ChildCat.md +docs/ChildCatAllOf.md +docs/ClassModel.md +docs/ComplexQuadrilateral.md +docs/DanishPig.md +docs/DefaultApi.md +docs/Dog.md +docs/DogAllOf.md +docs/Drawing.md +docs/EnumArrays.md +docs/EnumClass.md +docs/EnumTest.md +docs/EquilateralTriangle.md +docs/FakeApi.md +docs/FakeClassnameTags123Api.md +docs/File.md +docs/FileSchemaTestClass.md +docs/Foo.md +docs/FormatTest.md +docs/Fruit.md +docs/FruitReq.md +docs/GmFruit.md +docs/GrandparentAnimal.md +docs/HasOnlyReadOnly.md +docs/HealthCheckResult.md +docs/InlineResponseDefault.md +docs/IsoscelesTriangle.md +docs/List.md +docs/Mammal.md +docs/MapTest.md +docs/MixedPropertiesAndAdditionalPropertiesClass.md +docs/Model200Response.md +docs/ModelClient.md +docs/Name.md +docs/NullableClass.md +docs/NullableShape.md +docs/NumberOnly.md +docs/Order.md +docs/OuterComposite.md +docs/OuterEnum.md +docs/OuterEnumDefaultValue.md +docs/OuterEnumInteger.md +docs/OuterEnumIntegerDefaultValue.md +docs/ParentPet.md +docs/Pet.md +docs/PetApi.md +docs/Pig.md +docs/Quadrilateral.md +docs/QuadrilateralInterface.md +docs/ReadOnlyFirst.md +docs/Return.md +docs/ScaleneTriangle.md +docs/Shape.md +docs/ShapeInterface.md +docs/ShapeOrNull.md +docs/SimpleQuadrilateral.md +docs/SpecialModelName.md +docs/StoreApi.md +docs/Tag.md +docs/Triangle.md +docs/TriangleInterface.md +docs/User.md +docs/UserApi.md +docs/Whale.md +docs/Zebra.md +git_push.sh +src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj +src/Org.OpenAPITools/Api/AnotherFakeApi.cs +src/Org.OpenAPITools/Api/DefaultApi.cs +src/Org.OpenAPITools/Api/FakeApi.cs +src/Org.OpenAPITools/Api/FakeClassnameTags123Api.cs +src/Org.OpenAPITools/Api/PetApi.cs +src/Org.OpenAPITools/Api/StoreApi.cs +src/Org.OpenAPITools/Api/UserApi.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/HttpSigningConfiguration.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/AdditionalPropertiesClass.cs +src/Org.OpenAPITools/Model/Animal.cs +src/Org.OpenAPITools/Model/ApiResponse.cs +src/Org.OpenAPITools/Model/Apple.cs +src/Org.OpenAPITools/Model/AppleReq.cs +src/Org.OpenAPITools/Model/ArrayOfArrayOfNumberOnly.cs +src/Org.OpenAPITools/Model/ArrayOfNumberOnly.cs +src/Org.OpenAPITools/Model/ArrayTest.cs +src/Org.OpenAPITools/Model/Banana.cs +src/Org.OpenAPITools/Model/BananaReq.cs +src/Org.OpenAPITools/Model/BasquePig.cs +src/Org.OpenAPITools/Model/Capitalization.cs +src/Org.OpenAPITools/Model/Cat.cs +src/Org.OpenAPITools/Model/CatAllOf.cs +src/Org.OpenAPITools/Model/Category.cs +src/Org.OpenAPITools/Model/ChildCat.cs +src/Org.OpenAPITools/Model/ChildCatAllOf.cs +src/Org.OpenAPITools/Model/ClassModel.cs +src/Org.OpenAPITools/Model/ComplexQuadrilateral.cs +src/Org.OpenAPITools/Model/DanishPig.cs +src/Org.OpenAPITools/Model/Dog.cs +src/Org.OpenAPITools/Model/DogAllOf.cs +src/Org.OpenAPITools/Model/Drawing.cs +src/Org.OpenAPITools/Model/EnumArrays.cs +src/Org.OpenAPITools/Model/EnumClass.cs +src/Org.OpenAPITools/Model/EnumTest.cs +src/Org.OpenAPITools/Model/EquilateralTriangle.cs +src/Org.OpenAPITools/Model/File.cs +src/Org.OpenAPITools/Model/FileSchemaTestClass.cs +src/Org.OpenAPITools/Model/Foo.cs +src/Org.OpenAPITools/Model/FormatTest.cs +src/Org.OpenAPITools/Model/Fruit.cs +src/Org.OpenAPITools/Model/FruitReq.cs +src/Org.OpenAPITools/Model/GmFruit.cs +src/Org.OpenAPITools/Model/GrandparentAnimal.cs +src/Org.OpenAPITools/Model/HasOnlyReadOnly.cs +src/Org.OpenAPITools/Model/HealthCheckResult.cs +src/Org.OpenAPITools/Model/InlineResponseDefault.cs +src/Org.OpenAPITools/Model/IsoscelesTriangle.cs +src/Org.OpenAPITools/Model/List.cs +src/Org.OpenAPITools/Model/Mammal.cs +src/Org.OpenAPITools/Model/MapTest.cs +src/Org.OpenAPITools/Model/MixedPropertiesAndAdditionalPropertiesClass.cs +src/Org.OpenAPITools/Model/Model200Response.cs +src/Org.OpenAPITools/Model/ModelClient.cs +src/Org.OpenAPITools/Model/Name.cs +src/Org.OpenAPITools/Model/NullableClass.cs +src/Org.OpenAPITools/Model/NullableShape.cs +src/Org.OpenAPITools/Model/NumberOnly.cs +src/Org.OpenAPITools/Model/Order.cs +src/Org.OpenAPITools/Model/OuterComposite.cs +src/Org.OpenAPITools/Model/OuterEnum.cs +src/Org.OpenAPITools/Model/OuterEnumDefaultValue.cs +src/Org.OpenAPITools/Model/OuterEnumInteger.cs +src/Org.OpenAPITools/Model/OuterEnumIntegerDefaultValue.cs +src/Org.OpenAPITools/Model/ParentPet.cs +src/Org.OpenAPITools/Model/Pet.cs +src/Org.OpenAPITools/Model/Pig.cs +src/Org.OpenAPITools/Model/Quadrilateral.cs +src/Org.OpenAPITools/Model/QuadrilateralInterface.cs +src/Org.OpenAPITools/Model/ReadOnlyFirst.cs +src/Org.OpenAPITools/Model/Return.cs +src/Org.OpenAPITools/Model/ScaleneTriangle.cs +src/Org.OpenAPITools/Model/Shape.cs +src/Org.OpenAPITools/Model/ShapeInterface.cs +src/Org.OpenAPITools/Model/ShapeOrNull.cs +src/Org.OpenAPITools/Model/SimpleQuadrilateral.cs +src/Org.OpenAPITools/Model/SpecialModelName.cs +src/Org.OpenAPITools/Model/Tag.cs +src/Org.OpenAPITools/Model/Triangle.cs +src/Org.OpenAPITools/Model/TriangleInterface.cs +src/Org.OpenAPITools/Model/User.cs +src/Org.OpenAPITools/Model/Whale.cs +src/Org.OpenAPITools/Model/Zebra.cs +src/Org.OpenAPITools/Org.OpenAPITools.csproj diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/.openapi-generator/VERSION b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/.openapi-generator/VERSION new file mode 100644 index 00000000000..4b448de535c --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/.openapi-generator/VERSION @@ -0,0 +1 @@ +5.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/Org.OpenAPITools.sln b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/Org.OpenAPITools.sln new file mode 100644 index 00000000000..85fab38c151 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/Org.OpenAPITools.sln @@ -0,0 +1,27 @@ +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 14 +VisualStudioVersion = 14.0.25420.1 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Org.OpenAPITools", "src\Org.OpenAPITools\Org.OpenAPITools.csproj", "{fa96c953-af24-457d-8a01-f2fd2a7547a9}" +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 + {fa96c953-af24-457d-8a01-f2fd2a7547a9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {fa96c953-af24-457d-8a01-f2fd2a7547a9}.Debug|Any CPU.Build.0 = Debug|Any CPU + {fa96c953-af24-457d-8a01-f2fd2a7547a9}.Release|Any CPU.ActiveCfg = Release|Any CPU + {fa96c953-af24-457d-8a01-f2fd2a7547a9}.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-netcore/OpenAPIClient-ConditionalSerialization/README.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/README.md new file mode 100644 index 00000000000..325ba2bd65b --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/README.md @@ -0,0 +1,266 @@ +# Org.OpenAPITools - the C# library for the 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: \" \\ + +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.CSharpNetCoreClientCodegen + + +## Frameworks supported +- .NET Core >=1.0 +- .NET Framework >=4.6 +- Mono/Xamarin >=vNext + + +## Dependencies + +- [RestSharp](https://www.nuget.org/packages/RestSharp) - 106.11.7 or later +- [Json.NET](https://www.nuget.org/packages/Newtonsoft.Json/) - 12.0.3 or later +- [JsonSubTypes](https://www.nuget.org/packages/JsonSubTypes/) - 1.8.0 or later +- [CompareNETObjects](https://www.nuget.org/packages/CompareNETObjects) - 4.61.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 +Install-Package CompareNETObjects +``` + +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 +Generate the DLL using your preferred tool (e.g. `dotnet build`) + +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; +``` + +## 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://petstore.swagger.io:80/v2"; + var apiInstance = new AnotherFakeApi(config); + var modelClient = new ModelClient(); // ModelClient | client model + + try + { + // To test special tags + ModelClient result = apiInstance.Call123TestSpecialTags(modelClient); + Debug.WriteLine(result); + } + catch (ApiException e) + { + Debug.Print("Exception when calling AnotherFakeApi.Call123TestSpecialTags: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); + } + + } + } +} +``` + + +## Documentation for API Endpoints + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +Class | Method | HTTP request | Description +------------ | ------------- | ------------- | ------------- +*AnotherFakeApi* | [**Call123TestSpecialTags**](docs/AnotherFakeApi.md#call123testspecialtags) | **PATCH** /another-fake/dummy | To test special tags +*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 | +*FakeApi* | [**FakeOuterCompositeSerialize**](docs/FakeApi.md#fakeoutercompositeserialize) | **POST** /fake/outer/composite | +*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* | [**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 +*FakeApi* | [**TestEndpointParameters**](docs/FakeApi.md#testendpointparameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 +*FakeApi* | [**TestEnumParameters**](docs/FakeApi.md#testenumparameters) | **GET** /fake | To test enum parameters +*FakeApi* | [**TestGroupParameters**](docs/FakeApi.md#testgroupparameters) | **DELETE** /fake | Fake endpoint to test group parameters (optional) +*FakeApi* | [**TestInlineAdditionalProperties**](docs/FakeApi.md#testinlineadditionalproperties) | **POST** /fake/inline-additionalProperties | test inline additionalProperties +*FakeApi* | [**TestJsonFormData**](docs/FakeApi.md#testjsonformdata) | **GET** /fake/jsonFormData | test json serialization of form data +*FakeApi* | [**TestQueryParameterCollectionFormat**](docs/FakeApi.md#testqueryparametercollectionformat) | **PUT** /fake/test-query-paramters | +*FakeClassnameTags123Api* | [**TestClassname**](docs/FakeClassnameTags123Api.md#testclassname) | **PATCH** /fake_classname_test | To test class name in snake case +*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 +*PetApi* | [**UploadFileWithRequiredFile**](docs/PetApi.md#uploadfilewithrequiredfile) | **POST** /fake/{petId}/uploadImageWithRequiredFile | uploads an image (required) +*StoreApi* | [**DeleteOrder**](docs/StoreApi.md#deleteorder) | **DELETE** /store/order/{order_id} | 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/{order_id} | 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 + + - [Model.AdditionalPropertiesClass](docs/AdditionalPropertiesClass.md) + - [Model.Animal](docs/Animal.md) + - [Model.ApiResponse](docs/ApiResponse.md) + - [Model.Apple](docs/Apple.md) + - [Model.AppleReq](docs/AppleReq.md) + - [Model.ArrayOfArrayOfNumberOnly](docs/ArrayOfArrayOfNumberOnly.md) + - [Model.ArrayOfNumberOnly](docs/ArrayOfNumberOnly.md) + - [Model.ArrayTest](docs/ArrayTest.md) + - [Model.Banana](docs/Banana.md) + - [Model.BananaReq](docs/BananaReq.md) + - [Model.BasquePig](docs/BasquePig.md) + - [Model.Capitalization](docs/Capitalization.md) + - [Model.Cat](docs/Cat.md) + - [Model.CatAllOf](docs/CatAllOf.md) + - [Model.Category](docs/Category.md) + - [Model.ChildCat](docs/ChildCat.md) + - [Model.ChildCatAllOf](docs/ChildCatAllOf.md) + - [Model.ClassModel](docs/ClassModel.md) + - [Model.ComplexQuadrilateral](docs/ComplexQuadrilateral.md) + - [Model.DanishPig](docs/DanishPig.md) + - [Model.Dog](docs/Dog.md) + - [Model.DogAllOf](docs/DogAllOf.md) + - [Model.Drawing](docs/Drawing.md) + - [Model.EnumArrays](docs/EnumArrays.md) + - [Model.EnumClass](docs/EnumClass.md) + - [Model.EnumTest](docs/EnumTest.md) + - [Model.EquilateralTriangle](docs/EquilateralTriangle.md) + - [Model.File](docs/File.md) + - [Model.FileSchemaTestClass](docs/FileSchemaTestClass.md) + - [Model.Foo](docs/Foo.md) + - [Model.FormatTest](docs/FormatTest.md) + - [Model.Fruit](docs/Fruit.md) + - [Model.FruitReq](docs/FruitReq.md) + - [Model.GmFruit](docs/GmFruit.md) + - [Model.GrandparentAnimal](docs/GrandparentAnimal.md) + - [Model.HasOnlyReadOnly](docs/HasOnlyReadOnly.md) + - [Model.HealthCheckResult](docs/HealthCheckResult.md) + - [Model.InlineResponseDefault](docs/InlineResponseDefault.md) + - [Model.IsoscelesTriangle](docs/IsoscelesTriangle.md) + - [Model.List](docs/List.md) + - [Model.Mammal](docs/Mammal.md) + - [Model.MapTest](docs/MapTest.md) + - [Model.MixedPropertiesAndAdditionalPropertiesClass](docs/MixedPropertiesAndAdditionalPropertiesClass.md) + - [Model.Model200Response](docs/Model200Response.md) + - [Model.ModelClient](docs/ModelClient.md) + - [Model.Name](docs/Name.md) + - [Model.NullableClass](docs/NullableClass.md) + - [Model.NullableShape](docs/NullableShape.md) + - [Model.NumberOnly](docs/NumberOnly.md) + - [Model.Order](docs/Order.md) + - [Model.OuterComposite](docs/OuterComposite.md) + - [Model.OuterEnum](docs/OuterEnum.md) + - [Model.OuterEnumDefaultValue](docs/OuterEnumDefaultValue.md) + - [Model.OuterEnumInteger](docs/OuterEnumInteger.md) + - [Model.OuterEnumIntegerDefaultValue](docs/OuterEnumIntegerDefaultValue.md) + - [Model.ParentPet](docs/ParentPet.md) + - [Model.Pet](docs/Pet.md) + - [Model.Pig](docs/Pig.md) + - [Model.Quadrilateral](docs/Quadrilateral.md) + - [Model.QuadrilateralInterface](docs/QuadrilateralInterface.md) + - [Model.ReadOnlyFirst](docs/ReadOnlyFirst.md) + - [Model.Return](docs/Return.md) + - [Model.ScaleneTriangle](docs/ScaleneTriangle.md) + - [Model.Shape](docs/Shape.md) + - [Model.ShapeInterface](docs/ShapeInterface.md) + - [Model.ShapeOrNull](docs/ShapeOrNull.md) + - [Model.SimpleQuadrilateral](docs/SimpleQuadrilateral.md) + - [Model.SpecialModelName](docs/SpecialModelName.md) + - [Model.Tag](docs/Tag.md) + - [Model.Triangle](docs/Triangle.md) + - [Model.TriangleInterface](docs/TriangleInterface.md) + - [Model.User](docs/User.md) + - [Model.Whale](docs/Whale.md) + - [Model.Zebra](docs/Zebra.md) + + + +## Documentation for Authorization + + +### api_key + +- **Type**: API key +- **API key parameter name**: api_key +- **Location**: HTTP header + + +### api_key_query + +- **Type**: API key +- **API key parameter name**: api_key_query +- **Location**: URL query string + + +### bearer_test + +- **Type**: Bearer Authentication + + +### http_basic_test + +- **Type**: HTTP basic authentication + + +### http_signature_test + + + +### 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 + diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/appveyor.yml b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/appveyor.yml new file mode 100644 index 00000000000..f76f63cee50 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/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-netcore/OpenAPIClient-ConditionalSerialization/docs/AdditionalPropertiesClass.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/AdditionalPropertiesClass.md new file mode 100644 index 00000000000..c40cd0f8acc --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/AdditionalPropertiesClass.md @@ -0,0 +1,17 @@ +# Org.OpenAPITools.Model.AdditionalPropertiesClass + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**MapProperty** | **Dictionary<string, string>** | | [optional] +**MapOfMapProperty** | **Dictionary<string, Dictionary<string, string>>** | | [optional] +**Anytype1** | **Object** | | [optional] +**MapWithUndeclaredPropertiesAnytype1** | **Object** | | [optional] +**MapWithUndeclaredPropertiesAnytype2** | **Object** | | [optional] +**MapWithUndeclaredPropertiesAnytype3** | **Dictionary<string, Object>** | | [optional] +**EmptyMap** | **Object** | an object with no declared properties and no undeclared properties, hence it's an empty map. | [optional] +**MapWithUndeclaredPropertiesString** | **Dictionary<string, 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-netcore/OpenAPIClient-ConditionalSerialization/docs/Animal.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/Animal.md new file mode 100644 index 00000000000..f14b7a3ae4e --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/Animal.md @@ -0,0 +1,11 @@ +# Org.OpenAPITools.Model.Animal + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**ClassName** | **string** | | +**Color** | **string** | | [optional] [default to "red"] + +[[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-netcore/OpenAPIClient-ConditionalSerialization/docs/AnotherFakeApi.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/AnotherFakeApi.md new file mode 100644 index 00000000000..93fca7e408a --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/AnotherFakeApi.md @@ -0,0 +1,80 @@ +# Org.OpenAPITools.Api.AnotherFakeApi + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**Call123TestSpecialTags**](AnotherFakeApi.md#call123testspecialtags) | **PATCH** /another-fake/dummy | To test special tags + + + +# **Call123TestSpecialTags** +> ModelClient Call123TestSpecialTags (ModelClient modelClient) + +To test special tags + +To test special tags and operation ID starting with number + +### 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 Call123TestSpecialTagsExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io:80/v2"; + var apiInstance = new AnotherFakeApi(config); + var modelClient = new ModelClient(); // ModelClient | client model + + try + { + // To test special tags + ModelClient result = apiInstance.Call123TestSpecialTags(modelClient); + Debug.WriteLine(result); + } + catch (ApiException e) + { + Debug.Print("Exception when calling AnotherFakeApi.Call123TestSpecialTags: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **modelClient** | [**ModelClient**](ModelClient.md)| client model | + +### Return type + +[**ModelClient**](ModelClient.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) + diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/ApiResponse.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/ApiResponse.md new file mode 100644 index 00000000000..bb723d2baa1 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/ApiResponse.md @@ -0,0 +1,12 @@ +# Org.OpenAPITools.Model.ApiResponse + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Code** | **int** | | [optional] +**Type** | **string** | | [optional] +**Message** | **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-netcore/OpenAPIClient-ConditionalSerialization/docs/Apple.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/Apple.md new file mode 100644 index 00000000000..1f819f8f281 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/Apple.md @@ -0,0 +1,11 @@ +# Org.OpenAPITools.Model.Apple + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Cultivar** | **string** | | [optional] +**Origin** | **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-netcore/OpenAPIClient-ConditionalSerialization/docs/AppleReq.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/AppleReq.md new file mode 100644 index 00000000000..005b8f8058a --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/AppleReq.md @@ -0,0 +1,11 @@ +# Org.OpenAPITools.Model.AppleReq + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Cultivar** | **string** | | +**Mealy** | **bool** | | [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-netcore/OpenAPIClient-ConditionalSerialization/docs/ArrayOfArrayOfNumberOnly.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/ArrayOfArrayOfNumberOnly.md new file mode 100644 index 00000000000..4764c0ff80c --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/ArrayOfArrayOfNumberOnly.md @@ -0,0 +1,10 @@ +# Org.OpenAPITools.Model.ArrayOfArrayOfNumberOnly + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**ArrayArrayNumber** | **List<List<decimal>>** | | [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-netcore/OpenAPIClient-ConditionalSerialization/docs/ArrayOfNumberOnly.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/ArrayOfNumberOnly.md new file mode 100644 index 00000000000..d93717103b8 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/ArrayOfNumberOnly.md @@ -0,0 +1,10 @@ +# Org.OpenAPITools.Model.ArrayOfNumberOnly + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**ArrayNumber** | **List<decimal>** | | [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-netcore/OpenAPIClient-ConditionalSerialization/docs/ArrayTest.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/ArrayTest.md new file mode 100644 index 00000000000..d74d11bae77 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/ArrayTest.md @@ -0,0 +1,12 @@ +# Org.OpenAPITools.Model.ArrayTest + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**ArrayOfString** | **List<string>** | | [optional] +**ArrayArrayOfInteger** | **List<List<long>>** | | [optional] +**ArrayArrayOfModel** | **List<List<ReadOnlyFirst>>** | | [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-netcore/OpenAPIClient-ConditionalSerialization/docs/Banana.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/Banana.md new file mode 100644 index 00000000000..226952d1cec --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/Banana.md @@ -0,0 +1,10 @@ +# Org.OpenAPITools.Model.Banana + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**LengthCm** | **decimal** | | [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-netcore/OpenAPIClient-ConditionalSerialization/docs/BananaReq.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/BananaReq.md new file mode 100644 index 00000000000..f99aab99e38 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/BananaReq.md @@ -0,0 +1,11 @@ +# Org.OpenAPITools.Model.BananaReq + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**LengthCm** | **decimal** | | +**Sweet** | **bool** | | [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-netcore/OpenAPIClient-ConditionalSerialization/docs/BasquePig.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/BasquePig.md new file mode 100644 index 00000000000..681be0bc7e3 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/BasquePig.md @@ -0,0 +1,10 @@ +# Org.OpenAPITools.Model.BasquePig + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**ClassName** | **string** | | + +[[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-netcore/OpenAPIClient-ConditionalSerialization/docs/Capitalization.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/Capitalization.md new file mode 100644 index 00000000000..1b1352d918f --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/Capitalization.md @@ -0,0 +1,15 @@ +# Org.OpenAPITools.Model.Capitalization + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**SmallCamel** | **string** | | [optional] +**CapitalCamel** | **string** | | [optional] +**SmallSnake** | **string** | | [optional] +**CapitalSnake** | **string** | | [optional] +**SCAETHFlowPoints** | **string** | | [optional] +**ATT_NAME** | **string** | Name of the pet | [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-netcore/OpenAPIClient-ConditionalSerialization/docs/Cat.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/Cat.md new file mode 100644 index 00000000000..aa1ac17604e --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/Cat.md @@ -0,0 +1,12 @@ +# Org.OpenAPITools.Model.Cat + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**ClassName** | **string** | | +**Color** | **string** | | [optional] [default to "red"] +**Declawed** | **bool** | | [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-netcore/OpenAPIClient-ConditionalSerialization/docs/CatAllOf.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/CatAllOf.md new file mode 100644 index 00000000000..6cbaaa14e81 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/CatAllOf.md @@ -0,0 +1,10 @@ +# Org.OpenAPITools.Model.CatAllOf + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Declawed** | **bool** | | [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-netcore/OpenAPIClient-ConditionalSerialization/docs/Category.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/Category.md new file mode 100644 index 00000000000..032a1faeb3f --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/Category.md @@ -0,0 +1,11 @@ +# Org.OpenAPITools.Model.Category + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Id** | **long** | | [optional] +**Name** | **string** | | [default to "default-name"] + +[[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-netcore/OpenAPIClient-ConditionalSerialization/docs/ChildCat.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/ChildCat.md new file mode 100644 index 00000000000..8ce6449e5f2 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/ChildCat.md @@ -0,0 +1,11 @@ +# Org.OpenAPITools.Model.ChildCat + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Name** | **string** | | [optional] +**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-netcore/OpenAPIClient-ConditionalSerialization/docs/ChildCatAllOf.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/ChildCatAllOf.md new file mode 100644 index 00000000000..864d33e80e7 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/ChildCatAllOf.md @@ -0,0 +1,11 @@ +# Org.OpenAPITools.Model.ChildCatAllOf + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Name** | **string** | | [optional] +**PetType** | **string** | | [optional] [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-netcore/OpenAPIClient-ConditionalSerialization/docs/ClassModel.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/ClassModel.md new file mode 100644 index 00000000000..f39982657c8 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/ClassModel.md @@ -0,0 +1,11 @@ +# Org.OpenAPITools.Model.ClassModel +Model for testing model with \"_class\" property + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Class** | **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-netcore/OpenAPIClient-ConditionalSerialization/docs/ComplexQuadrilateral.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/ComplexQuadrilateral.md new file mode 100644 index 00000000000..65a6097ce3f --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/ComplexQuadrilateral.md @@ -0,0 +1,11 @@ +# Org.OpenAPITools.Model.ComplexQuadrilateral + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**ShapeType** | **string** | | +**QuadrilateralType** | **string** | | + +[[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-netcore/OpenAPIClient-ConditionalSerialization/docs/DanishPig.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/DanishPig.md new file mode 100644 index 00000000000..d9cf6527a3f --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/DanishPig.md @@ -0,0 +1,10 @@ +# Org.OpenAPITools.Model.DanishPig + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**ClassName** | **string** | | + +[[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-netcore/OpenAPIClient-ConditionalSerialization/docs/DefaultApi.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/DefaultApi.md new file mode 100644 index 00000000000..6f5de6b6851 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/DefaultApi.md @@ -0,0 +1,73 @@ +# Org.OpenAPITools.Api.DefaultApi + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**FooGet**](DefaultApi.md#fooget) | **GET** /foo | + + + +# **FooGet** +> InlineResponseDefault FooGet () + + + +### 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 FooGetExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io:80/v2"; + var apiInstance = new DefaultApi(config); + + try + { + InlineResponseDefault result = apiInstance.FooGet(); + Debug.WriteLine(result); + } + catch (ApiException e) + { + Debug.Print("Exception when calling DefaultApi.FooGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +### Parameters +This endpoint does not need any parameter. + +### Return type + +[**InlineResponseDefault**](InlineResponseDefault.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **0** | response | - | + +[[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-netcore/OpenAPIClient-ConditionalSerialization/docs/Dog.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/Dog.md new file mode 100644 index 00000000000..3aa00144e9a --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/Dog.md @@ -0,0 +1,12 @@ +# Org.OpenAPITools.Model.Dog + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**ClassName** | **string** | | +**Color** | **string** | | [optional] [default to "red"] +**Breed** | **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-netcore/OpenAPIClient-ConditionalSerialization/docs/DogAllOf.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/DogAllOf.md new file mode 100644 index 00000000000..c1096f2c310 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/DogAllOf.md @@ -0,0 +1,10 @@ +# Org.OpenAPITools.Model.DogAllOf + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Breed** | **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-netcore/OpenAPIClient-ConditionalSerialization/docs/Drawing.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/Drawing.md new file mode 100644 index 00000000000..6b7122940af --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/Drawing.md @@ -0,0 +1,13 @@ +# Org.OpenAPITools.Model.Drawing + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**MainShape** | [**Shape**](Shape.md) | | [optional] +**ShapeOrNull** | [**ShapeOrNull**](ShapeOrNull.md) | | [optional] +**NullableShape** | [**NullableShape**](NullableShape.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-netcore/OpenAPIClient-ConditionalSerialization/docs/EnumArrays.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/EnumArrays.md new file mode 100644 index 00000000000..8881585a4c7 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/EnumArrays.md @@ -0,0 +1,11 @@ +# Org.OpenAPITools.Model.EnumArrays + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**JustSymbol** | **string** | | [optional] +**ArrayEnum** | **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-netcore/OpenAPIClient-ConditionalSerialization/docs/EnumClass.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/EnumClass.md new file mode 100644 index 00000000000..38f309437db --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/EnumClass.md @@ -0,0 +1,9 @@ +# Org.OpenAPITools.Model.EnumClass + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +[[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-netcore/OpenAPIClient-ConditionalSerialization/docs/EnumTest.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/EnumTest.md new file mode 100644 index 00000000000..5ce3c4addd9 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/EnumTest.md @@ -0,0 +1,18 @@ +# Org.OpenAPITools.Model.EnumTest + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**EnumString** | **string** | | [optional] +**EnumStringRequired** | **string** | | +**EnumInteger** | **int** | | [optional] +**EnumIntegerOnly** | **int** | | [optional] +**EnumNumber** | **double** | | [optional] +**OuterEnum** | **OuterEnum** | | [optional] +**OuterEnumInteger** | **OuterEnumInteger** | | [optional] +**OuterEnumDefaultValue** | **OuterEnumDefaultValue** | | [optional] +**OuterEnumIntegerDefaultValue** | **OuterEnumIntegerDefaultValue** | | [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-netcore/OpenAPIClient-ConditionalSerialization/docs/EquilateralTriangle.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/EquilateralTriangle.md new file mode 100644 index 00000000000..ab06d96ca30 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/EquilateralTriangle.md @@ -0,0 +1,11 @@ +# Org.OpenAPITools.Model.EquilateralTriangle + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**ShapeType** | **string** | | +**TriangleType** | **string** | | + +[[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-netcore/OpenAPIClient-ConditionalSerialization/docs/FakeApi.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/FakeApi.md new file mode 100644 index 00000000000..af8d565abfb --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/FakeApi.md @@ -0,0 +1,1126 @@ +# Org.OpenAPITools.Api.FakeApi + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**FakeHealthGet**](FakeApi.md#fakehealthget) | **GET** /fake/health | Health check endpoint +[**FakeOuterBooleanSerialize**](FakeApi.md#fakeouterbooleanserialize) | **POST** /fake/outer/boolean | +[**FakeOuterCompositeSerialize**](FakeApi.md#fakeoutercompositeserialize) | **POST** /fake/outer/composite | +[**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 +[**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 +[**TestEndpointParameters**](FakeApi.md#testendpointparameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 +[**TestEnumParameters**](FakeApi.md#testenumparameters) | **GET** /fake | To test enum parameters +[**TestGroupParameters**](FakeApi.md#testgroupparameters) | **DELETE** /fake | Fake endpoint to test group parameters (optional) +[**TestInlineAdditionalProperties**](FakeApi.md#testinlineadditionalproperties) | **POST** /fake/inline-additionalProperties | test inline additionalProperties +[**TestJsonFormData**](FakeApi.md#testjsonformdata) | **GET** /fake/jsonFormData | test json serialization of form data +[**TestQueryParameterCollectionFormat**](FakeApi.md#testqueryparametercollectionformat) | **PUT** /fake/test-query-paramters | + + + +# **FakeHealthGet** +> HealthCheckResult FakeHealthGet () + +Health check endpoint + +### 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 FakeHealthGetExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io:80/v2"; + var apiInstance = new FakeApi(config); + + try + { + // Health check endpoint + HealthCheckResult result = apiInstance.FakeHealthGet(); + Debug.WriteLine(result); + } + catch (ApiException e) + { + Debug.Print("Exception when calling FakeApi.FakeHealthGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +### Parameters +This endpoint does not need any parameter. + +### Return type + +[**HealthCheckResult**](HealthCheckResult.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | The instance started successfully | - | + +[[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) + + +# **FakeOuterBooleanSerialize** +> bool FakeOuterBooleanSerialize (bool? body = null) + + + +Test serialization of outer boolean types + +### 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 FakeOuterBooleanSerializeExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io:80/v2"; + var apiInstance = new FakeApi(config); + var body = true; // bool? | Input boolean as post body (optional) + + try + { + bool result = apiInstance.FakeOuterBooleanSerialize(body); + Debug.WriteLine(result); + } + catch (ApiException e) + { + Debug.Print("Exception when calling FakeApi.FakeOuterBooleanSerialize: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | **bool?**| Input boolean as post body | [optional] + +### Return type + +**bool** + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: */* + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | Output boolean | - | + +[[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) + + +# **FakeOuterCompositeSerialize** +> OuterComposite FakeOuterCompositeSerialize (OuterComposite outerComposite = null) + + + +Test serialization of object with outer number type + +### 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 FakeOuterCompositeSerializeExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io:80/v2"; + var apiInstance = new FakeApi(config); + var outerComposite = new OuterComposite(); // OuterComposite | Input composite as post body (optional) + + try + { + OuterComposite result = apiInstance.FakeOuterCompositeSerialize(outerComposite); + Debug.WriteLine(result); + } + catch (ApiException e) + { + Debug.Print("Exception when calling FakeApi.FakeOuterCompositeSerialize: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **outerComposite** | [**OuterComposite**](OuterComposite.md)| Input composite as post body | [optional] + +### Return type + +[**OuterComposite**](OuterComposite.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: */* + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | Output composite | - | + +[[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) + + +# **FakeOuterNumberSerialize** +> decimal FakeOuterNumberSerialize (decimal? body = null) + + + +Test serialization of outer number types + +### 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 FakeOuterNumberSerializeExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io:80/v2"; + var apiInstance = new FakeApi(config); + var body = 8.14; // decimal? | Input number as post body (optional) + + try + { + decimal result = apiInstance.FakeOuterNumberSerialize(body); + Debug.WriteLine(result); + } + catch (ApiException e) + { + Debug.Print("Exception when calling FakeApi.FakeOuterNumberSerialize: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | **decimal?**| Input number as post body | [optional] + +### Return type + +**decimal** + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: */* + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | Output number | - | + +[[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) + + +# **FakeOuterStringSerialize** +> string FakeOuterStringSerialize (string body = null) + + + +Test serialization of outer string types + +### 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 FakeOuterStringSerializeExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io:80/v2"; + var apiInstance = new FakeApi(config); + var body = body_example; // string | Input string as post body (optional) + + try + { + string result = apiInstance.FakeOuterStringSerialize(body); + Debug.WriteLine(result); + } + catch (ApiException e) + { + Debug.Print("Exception when calling FakeApi.FakeOuterStringSerialize: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | **string**| Input string as post body | [optional] + +### Return type + +**string** + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: */* + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | Output string | - | + +[[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) + + +# **GetArrayOfEnums** +> List<OuterEnum> GetArrayOfEnums () + +Array of Enums + +### 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 GetArrayOfEnumsExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io:80/v2"; + var apiInstance = new FakeApi(config); + + try + { + // Array of Enums + List result = apiInstance.GetArrayOfEnums(); + Debug.WriteLine(result); + } + catch (ApiException e) + { + Debug.Print("Exception when calling FakeApi.GetArrayOfEnums: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +### Parameters +This endpoint does not need any parameter. + +### Return type + +[**List<OuterEnum>**](OuterEnum.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | Got named array of enums | - | + +[[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) + + + +For this test, the body for this request much reference a schema named `File`. + +### 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 TestBodyWithFileSchemaExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io:80/v2"; + var apiInstance = new FakeApi(config); + var fileSchemaTestClass = new FileSchemaTestClass(); // FileSchemaTestClass | + + try + { + apiInstance.TestBodyWithFileSchema(fileSchemaTestClass); + } + catch (ApiException e) + { + Debug.Print("Exception when calling FakeApi.TestBodyWithFileSchema: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **fileSchemaTestClass** | [**FileSchemaTestClass**](FileSchemaTestClass.md)| | + +### 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** | 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) + + +# **TestBodyWithQueryParams** +> void TestBodyWithQueryParams (string query, User user) + + + +### 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 TestBodyWithQueryParamsExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io:80/v2"; + var apiInstance = new FakeApi(config); + var query = query_example; // string | + var user = new User(); // User | + + try + { + apiInstance.TestBodyWithQueryParams(query, user); + } + catch (ApiException e) + { + Debug.Print("Exception when calling FakeApi.TestBodyWithQueryParams: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **query** | **string**| | + **user** | [**User**](User.md)| | + +### 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** | 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) + + +# **TestClientModel** +> ModelClient TestClientModel (ModelClient modelClient) + +To test \"client\" model + +To test \"client\" model + +### 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 TestClientModelExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io:80/v2"; + var apiInstance = new FakeApi(config); + var modelClient = new ModelClient(); // ModelClient | client model + + try + { + // To test \"client\" model + ModelClient result = apiInstance.TestClientModel(modelClient); + Debug.WriteLine(result); + } + catch (ApiException e) + { + Debug.Print("Exception when calling FakeApi.TestClientModel: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **modelClient** | [**ModelClient**](ModelClient.md)| client model | + +### Return type + +[**ModelClient**](ModelClient.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) + + +# **TestEndpointParameters** +> void TestEndpointParameters (decimal number, double _double, string patternWithoutDelimiter, byte[] _byte, int? integer = null, int? int32 = null, long? int64 = null, float? _float = null, string _string = null, System.IO.Stream binary = null, DateTime? date = null, DateTime? dateTime = null, string password = null, string callback = null) + +Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + +Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + +### 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 TestEndpointParametersExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io:80/v2"; + // Configure HTTP basic authorization: http_basic_test + config.Username = "YOUR_USERNAME"; + config.Password = "YOUR_PASSWORD"; + + var apiInstance = new FakeApi(config); + var number = 8.14; // decimal | None + var _double = 1.2D; // double | None + var patternWithoutDelimiter = patternWithoutDelimiter_example; // string | None + var _byte = BYTE_ARRAY_DATA_HERE; // byte[] | None + var integer = 56; // int? | None (optional) + var int32 = 56; // int? | None (optional) + var int64 = 789; // long? | None (optional) + var _float = 3.4F; // float? | None (optional) + var _string = _string_example; // string | None (optional) + var binary = BINARY_DATA_HERE; // System.IO.Stream | None (optional) + var date = 2013-10-20; // DateTime? | None (optional) + var dateTime = 2013-10-20T19:20:30+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) + + try + { + // Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + apiInstance.TestEndpointParameters(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, _string, binary, date, dateTime, password, callback); + } + catch (ApiException e) + { + Debug.Print("Exception when calling FakeApi.TestEndpointParameters: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **number** | **decimal**| None | + **_double** | **double**| None | + **patternWithoutDelimiter** | **string**| None | + **_byte** | **byte[]**| None | + **integer** | **int?**| None | [optional] + **int32** | **int?**| None | [optional] + **int64** | **long?**| None | [optional] + **_float** | **float?**| None | [optional] + **_string** | **string**| None | [optional] + **binary** | **System.IO.Stream****System.IO.Stream**| None | [optional] + **date** | **DateTime?**| None | [optional] + **dateTime** | **DateTime?**| None | [optional] [default to "2010-02-01T10:20:10.111110+01:00"] + **password** | **string**| None | [optional] + **callback** | **string**| None | [optional] + +### Return type + +void (empty response body) + +### Authorization + +[http_basic_test](../README.md#http_basic_test) + +### HTTP request headers + + - **Content-Type**: application/x-www-form-urlencoded + - **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **400** | Invalid username supplied | - | +| **404** | User not found | - | + +[[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) + + +# **TestEnumParameters** +> void TestEnumParameters (List enumHeaderStringArray = null, string enumHeaderString = null, List enumQueryStringArray = null, string enumQueryString = null, int? enumQueryInteger = null, double? enumQueryDouble = null, List enumFormStringArray = null, string enumFormString = null) + +To test enum parameters + +To test enum parameters + +### 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 TestEnumParametersExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io:80/v2"; + var apiInstance = new FakeApi(config); + var enumHeaderStringArray = enumHeaderStringArray_example; // List | Header parameter enum test (string array) (optional) + var enumHeaderString = enumHeaderString_example; // string | Header parameter enum test (string) (optional) (default to -efg) + var enumQueryStringArray = enumQueryStringArray_example; // List | Query parameter enum test (string array) (optional) + var enumQueryString = enumQueryString_example; // string | Query parameter enum test (string) (optional) (default to -efg) + var enumQueryInteger = 56; // int? | Query parameter enum test (double) (optional) + var enumQueryDouble = 1.2D; // double? | Query parameter enum test (double) (optional) + var enumFormStringArray = new List(); // List | Form parameter enum test (string array) (optional) (default to $) + var enumFormString = enumFormString_example; // string | Form parameter enum test (string) (optional) (default to -efg) + + try + { + // To test enum parameters + apiInstance.TestEnumParameters(enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble, enumFormStringArray, enumFormString); + } + catch (ApiException e) + { + Debug.Print("Exception when calling FakeApi.TestEnumParameters: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **enumHeaderStringArray** | **List<string>**| Header parameter enum test (string array) | [optional] + **enumHeaderString** | **string**| Header parameter enum test (string) | [optional] [default to -efg] + **enumQueryStringArray** | **List<string>**| Query parameter enum test (string array) | [optional] + **enumQueryString** | **string**| Query parameter enum test (string) | [optional] [default to -efg] + **enumQueryInteger** | **int?**| Query parameter enum test (double) | [optional] + **enumQueryDouble** | **double?**| Query parameter enum test (double) | [optional] + **enumFormStringArray** | [**List<string>**](string.md)| Form parameter enum test (string array) | [optional] [default to $] + **enumFormString** | **string**| Form parameter enum test (string) | [optional] [default to -efg] + +### Return type + +void (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 | +|-------------|-------------|------------------| +| **400** | Invalid request | - | +| **404** | Not found | - | + +[[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) + + +# **TestGroupParameters** +> void TestGroupParameters (int requiredStringGroup, bool requiredBooleanGroup, long requiredInt64Group, int? stringGroup = null, bool? booleanGroup = null, long? int64Group = null) + +Fake endpoint to test group parameters (optional) + +Fake endpoint to test group parameters (optional) + +### 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 TestGroupParametersExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io:80/v2"; + // Configure Bearer token for authorization: bearer_test + config.AccessToken = "YOUR_BEARER_TOKEN"; + + var apiInstance = new FakeApi(config); + var requiredStringGroup = 56; // int | Required String in group parameters + var requiredBooleanGroup = true; // bool | Required Boolean in group parameters + var requiredInt64Group = 789; // long | Required Integer in group parameters + var stringGroup = 56; // int? | String in group parameters (optional) + var booleanGroup = true; // bool? | Boolean in group parameters (optional) + var int64Group = 789; // long? | Integer in group parameters (optional) + + try + { + // Fake endpoint to test group parameters (optional) + apiInstance.TestGroupParameters(requiredStringGroup, requiredBooleanGroup, requiredInt64Group, stringGroup, booleanGroup, int64Group); + } + catch (ApiException e) + { + Debug.Print("Exception when calling FakeApi.TestGroupParameters: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **requiredStringGroup** | **int**| Required String in group parameters | + **requiredBooleanGroup** | **bool**| Required Boolean in group parameters | + **requiredInt64Group** | **long**| Required Integer in group parameters | + **stringGroup** | **int?**| String in group parameters | [optional] + **booleanGroup** | **bool?**| Boolean in group parameters | [optional] + **int64Group** | **long?**| Integer in group parameters | [optional] + +### Return type + +void (empty response body) + +### Authorization + +[bearer_test](../README.md#bearer_test) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **400** | Someting wrong | - | + +[[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) + + +# **TestInlineAdditionalProperties** +> void TestInlineAdditionalProperties (Dictionary requestBody) + +test inline 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 TestInlineAdditionalPropertiesExample + { + 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 inline additionalProperties + apiInstance.TestInlineAdditionalProperties(requestBody); + } + catch (ApiException e) + { + Debug.Print("Exception when calling FakeApi.TestInlineAdditionalProperties: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **requestBody** | [**Dictionary<string, string>**](string.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) + + +# **TestJsonFormData** +> void TestJsonFormData (string param, string param2) + +test json serialization of form data + +### 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 TestJsonFormDataExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io:80/v2"; + var apiInstance = new FakeApi(config); + var param = param_example; // string | field1 + var param2 = param2_example; // string | field2 + + try + { + // test json serialization of form data + apiInstance.TestJsonFormData(param, param2); + } + catch (ApiException e) + { + Debug.Print("Exception when calling FakeApi.TestJsonFormData: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **param** | **string**| field1 | + **param2** | **string**| field2 | + +### Return type + +void (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 | - | + +[[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) + + +# **TestQueryParameterCollectionFormat** +> void TestQueryParameterCollectionFormat (List pipe, List ioutil, List http, List url, List context) + + + +To test the collection format in query parameters + +### 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 TestQueryParameterCollectionFormatExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io:80/v2"; + var apiInstance = new FakeApi(config); + var pipe = new List(); // List | + var ioutil = new List(); // List | + var http = new List(); // List | + var url = new List(); // List | + var context = new List(); // List | + + try + { + apiInstance.TestQueryParameterCollectionFormat(pipe, ioutil, http, url, context); + } + catch (ApiException e) + { + Debug.Print("Exception when calling FakeApi.TestQueryParameterCollectionFormat: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **pipe** | [**List<string>**](string.md)| | + **ioutil** | [**List<string>**](string.md)| | + **http** | [**List<string>**](string.md)| | + **url** | [**List<string>**](string.md)| | + **context** | [**List<string>**](string.md)| | + +### Return type + +void (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 | +|-------------|-------------|------------------| +| **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) + diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/FakeClassnameTags123Api.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/FakeClassnameTags123Api.md new file mode 100644 index 00000000000..13235fbd10f --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/FakeClassnameTags123Api.md @@ -0,0 +1,85 @@ +# Org.OpenAPITools.Api.FakeClassnameTags123Api + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**TestClassname**](FakeClassnameTags123Api.md#testclassname) | **PATCH** /fake_classname_test | To test class name in snake case + + + +# **TestClassname** +> ModelClient TestClassname (ModelClient modelClient) + +To test class name in snake case + +To test class name in snake case + +### 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 TestClassnameExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io:80/v2"; + // 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 FakeClassnameTags123Api(config); + var modelClient = new ModelClient(); // ModelClient | client model + + try + { + // To test class name in snake case + ModelClient result = apiInstance.TestClassname(modelClient); + Debug.WriteLine(result); + } + catch (ApiException e) + { + Debug.Print("Exception when calling FakeClassnameTags123Api.TestClassname: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **modelClient** | [**ModelClient**](ModelClient.md)| client model | + +### Return type + +[**ModelClient**](ModelClient.md) + +### Authorization + +[api_key_query](../README.md#api_key_query) + +### 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) + diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/File.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/File.md new file mode 100644 index 00000000000..28959feda08 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/File.md @@ -0,0 +1,11 @@ +# Org.OpenAPITools.Model.File +Must be named `File` for test. + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**SourceURI** | **string** | Test capitalization | [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-netcore/OpenAPIClient-ConditionalSerialization/docs/FileSchemaTestClass.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/FileSchemaTestClass.md new file mode 100644 index 00000000000..0ce4be56cc7 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/FileSchemaTestClass.md @@ -0,0 +1,11 @@ +# Org.OpenAPITools.Model.FileSchemaTestClass + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**File** | [**File**](File.md) | | [optional] +**Files** | [**List<File>**](File.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-netcore/OpenAPIClient-ConditionalSerialization/docs/Foo.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/Foo.md new file mode 100644 index 00000000000..92cf4572321 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/Foo.md @@ -0,0 +1,10 @@ +# Org.OpenAPITools.Model.Foo + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Bar** | **string** | | [optional] [default to "bar"] + +[[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-netcore/OpenAPIClient-ConditionalSerialization/docs/FormatTest.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/FormatTest.md new file mode 100644 index 00000000000..39a70be7ad4 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/FormatTest.md @@ -0,0 +1,25 @@ +# Org.OpenAPITools.Model.FormatTest + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Integer** | **int** | | [optional] +**Int32** | **int** | | [optional] +**Int64** | **long** | | [optional] +**Number** | **decimal** | | +**Float** | **float** | | [optional] +**Double** | **double** | | [optional] +**Decimal** | **decimal** | | [optional] +**String** | **string** | | [optional] +**Byte** | **byte[]** | | +**Binary** | **System.IO.Stream** | | [optional] +**Date** | **DateTime** | | +**DateTime** | **DateTime** | | [optional] +**Uuid** | **Guid** | | [optional] +**Password** | **string** | | +**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] + +[[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-netcore/OpenAPIClient-ConditionalSerialization/docs/Fruit.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/Fruit.md new file mode 100644 index 00000000000..56b1c9f00ab --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/Fruit.md @@ -0,0 +1,13 @@ +# Org.OpenAPITools.Model.Fruit + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Color** | **string** | | [optional] +**Cultivar** | **string** | | [optional] +**Origin** | **string** | | [optional] +**LengthCm** | **decimal** | | [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-netcore/OpenAPIClient-ConditionalSerialization/docs/FruitReq.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/FruitReq.md new file mode 100644 index 00000000000..5db6b0e2d1d --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/FruitReq.md @@ -0,0 +1,13 @@ +# Org.OpenAPITools.Model.FruitReq + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Cultivar** | **string** | | +**Mealy** | **bool** | | [optional] +**LengthCm** | **decimal** | | +**Sweet** | **bool** | | [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-netcore/OpenAPIClient-ConditionalSerialization/docs/GmFruit.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/GmFruit.md new file mode 100644 index 00000000000..2cc2d496e67 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/GmFruit.md @@ -0,0 +1,13 @@ +# Org.OpenAPITools.Model.GmFruit + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Color** | **string** | | [optional] +**Cultivar** | **string** | | [optional] +**Origin** | **string** | | [optional] +**LengthCm** | **decimal** | | [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-netcore/OpenAPIClient-ConditionalSerialization/docs/GrandparentAnimal.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/GrandparentAnimal.md new file mode 100644 index 00000000000..461ebfe34c2 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/GrandparentAnimal.md @@ -0,0 +1,10 @@ +# Org.OpenAPITools.Model.GrandparentAnimal + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**PetType** | **string** | | + +[[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-netcore/OpenAPIClient-ConditionalSerialization/docs/HasOnlyReadOnly.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/HasOnlyReadOnly.md new file mode 100644 index 00000000000..64549c18b0a --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/HasOnlyReadOnly.md @@ -0,0 +1,11 @@ +# Org.OpenAPITools.Model.HasOnlyReadOnly + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Bar** | **string** | | [optional] [readonly] +**Foo** | **string** | | [optional] [readonly] + +[[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-netcore/OpenAPIClient-ConditionalSerialization/docs/HealthCheckResult.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/HealthCheckResult.md new file mode 100644 index 00000000000..f7d1a7eb688 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/HealthCheckResult.md @@ -0,0 +1,11 @@ +# Org.OpenAPITools.Model.HealthCheckResult +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 +------------ | ------------- | ------------- | ------------- +**NullableMessage** | **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-netcore/OpenAPIClient-ConditionalSerialization/docs/InlineResponseDefault.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/InlineResponseDefault.md new file mode 100644 index 00000000000..e3d55e133f3 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/InlineResponseDefault.md @@ -0,0 +1,10 @@ +# Org.OpenAPITools.Model.InlineResponseDefault + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**String** | [**Foo**](Foo.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-netcore/OpenAPIClient-ConditionalSerialization/docs/IsoscelesTriangle.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/IsoscelesTriangle.md new file mode 100644 index 00000000000..f0eef14fabb --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/IsoscelesTriangle.md @@ -0,0 +1,11 @@ +# Org.OpenAPITools.Model.IsoscelesTriangle + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**ShapeType** | **string** | | +**TriangleType** | **string** | | + +[[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-netcore/OpenAPIClient-ConditionalSerialization/docs/List.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/List.md new file mode 100644 index 00000000000..2862c7e5321 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/List.md @@ -0,0 +1,10 @@ +# Org.OpenAPITools.Model.List + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**_123List** | **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-netcore/OpenAPIClient-ConditionalSerialization/docs/Mammal.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/Mammal.md new file mode 100644 index 00000000000..aab8f4db9c7 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/Mammal.md @@ -0,0 +1,13 @@ +# Org.OpenAPITools.Model.Mammal + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**HasBaleen** | **bool** | | [optional] +**HasTeeth** | **bool** | | [optional] +**ClassName** | **string** | | +**Type** | **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-netcore/OpenAPIClient-ConditionalSerialization/docs/MapTest.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/MapTest.md new file mode 100644 index 00000000000..dc1ebba4e76 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/MapTest.md @@ -0,0 +1,13 @@ +# Org.OpenAPITools.Model.MapTest + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**MapMapOfString** | **Dictionary<string, Dictionary<string, string>>** | | [optional] +**MapOfEnumString** | **Dictionary<string, string>** | | [optional] +**DirectMap** | **Dictionary<string, bool>** | | [optional] +**IndirectMap** | **Dictionary<string, bool>** | | [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-netcore/OpenAPIClient-ConditionalSerialization/docs/MixedPropertiesAndAdditionalPropertiesClass.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/MixedPropertiesAndAdditionalPropertiesClass.md new file mode 100644 index 00000000000..5f57db957d7 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/MixedPropertiesAndAdditionalPropertiesClass.md @@ -0,0 +1,12 @@ +# Org.OpenAPITools.Model.MixedPropertiesAndAdditionalPropertiesClass + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Uuid** | **Guid** | | [optional] +**DateTime** | **DateTime** | | [optional] +**Map** | [**Dictionary<string, Animal>**](Animal.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-netcore/OpenAPIClient-ConditionalSerialization/docs/Model200Response.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/Model200Response.md new file mode 100644 index 00000000000..31f4d86fe43 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/Model200Response.md @@ -0,0 +1,12 @@ +# Org.OpenAPITools.Model.Model200Response +Model for testing model name starting with number + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Name** | **int** | | [optional] +**Class** | **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-netcore/OpenAPIClient-ConditionalSerialization/docs/ModelClient.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/ModelClient.md new file mode 100644 index 00000000000..c29a6287433 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/ModelClient.md @@ -0,0 +1,10 @@ +# Org.OpenAPITools.Model.ModelClient + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**_Client** | **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-netcore/OpenAPIClient-ConditionalSerialization/docs/Name.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/Name.md new file mode 100644 index 00000000000..692af702b5b --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/Name.md @@ -0,0 +1,14 @@ +# Org.OpenAPITools.Model.Name +Model for testing model name same as property name + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**_Name** | **int** | | +**SnakeCase** | **int** | | [optional] [readonly] +**Property** | **string** | | [optional] +**_123Number** | **int** | | [optional] [readonly] + +[[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-netcore/OpenAPIClient-ConditionalSerialization/docs/NullableClass.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/NullableClass.md new file mode 100644 index 00000000000..7bab4fa20ee --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/NullableClass.md @@ -0,0 +1,21 @@ +# Org.OpenAPITools.Model.NullableClass + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**IntegerProp** | **int?** | | [optional] +**NumberProp** | **decimal?** | | [optional] +**BooleanProp** | **bool?** | | [optional] +**StringProp** | **string** | | [optional] +**DateProp** | **DateTime?** | | [optional] +**DatetimeProp** | **DateTime?** | | [optional] +**ArrayNullableProp** | **List<Object>** | | [optional] +**ArrayAndItemsNullableProp** | **List<Object>** | | [optional] +**ArrayItemsNullable** | **List<Object>** | | [optional] +**ObjectNullableProp** | **Dictionary<string, Object>** | | [optional] +**ObjectAndItemsNullableProp** | **Dictionary<string, Object>** | | [optional] +**ObjectItemsNullable** | **Dictionary<string, 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-netcore/OpenAPIClient-ConditionalSerialization/docs/NullableShape.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/NullableShape.md new file mode 100644 index 00000000000..f8fb004da80 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/NullableShape.md @@ -0,0 +1,12 @@ +# Org.OpenAPITools.Model.NullableShape +The value may be a shape or the 'null' value. The 'nullable' attribute was introduced in OAS schema >= 3.0 and has been deprecated in OAS schema >= 3.1. + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**ShapeType** | **string** | | +**QuadrilateralType** | **string** | | + +[[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-netcore/OpenAPIClient-ConditionalSerialization/docs/NumberOnly.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/NumberOnly.md new file mode 100644 index 00000000000..14a7c0f1071 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/NumberOnly.md @@ -0,0 +1,10 @@ +# Org.OpenAPITools.Model.NumberOnly + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**JustNumber** | **decimal** | | [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-netcore/OpenAPIClient-ConditionalSerialization/docs/Order.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/Order.md new file mode 100644 index 00000000000..66c55c3b473 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/Order.md @@ -0,0 +1,15 @@ +# Org.OpenAPITools.Model.Order + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**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-netcore/OpenAPIClient-ConditionalSerialization/docs/OuterComposite.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/OuterComposite.md new file mode 100644 index 00000000000..eb42bcc1aaa --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/OuterComposite.md @@ -0,0 +1,12 @@ +# Org.OpenAPITools.Model.OuterComposite + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**MyNumber** | **decimal** | | [optional] +**MyString** | **string** | | [optional] +**MyBoolean** | **bool** | | [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-netcore/OpenAPIClient-ConditionalSerialization/docs/OuterEnum.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/OuterEnum.md new file mode 100644 index 00000000000..245765c7845 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/OuterEnum.md @@ -0,0 +1,9 @@ +# Org.OpenAPITools.Model.OuterEnum + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +[[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-netcore/OpenAPIClient-ConditionalSerialization/docs/OuterEnumDefaultValue.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/OuterEnumDefaultValue.md new file mode 100644 index 00000000000..3ffaa1086a6 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/OuterEnumDefaultValue.md @@ -0,0 +1,9 @@ +# Org.OpenAPITools.Model.OuterEnumDefaultValue + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +[[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-netcore/OpenAPIClient-ConditionalSerialization/docs/OuterEnumInteger.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/OuterEnumInteger.md new file mode 100644 index 00000000000..567858392db --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/OuterEnumInteger.md @@ -0,0 +1,9 @@ +# Org.OpenAPITools.Model.OuterEnumInteger + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +[[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-netcore/OpenAPIClient-ConditionalSerialization/docs/OuterEnumIntegerDefaultValue.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/OuterEnumIntegerDefaultValue.md new file mode 100644 index 00000000000..35c75a44372 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/OuterEnumIntegerDefaultValue.md @@ -0,0 +1,9 @@ +# Org.OpenAPITools.Model.OuterEnumIntegerDefaultValue + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +[[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-netcore/OpenAPIClient-ConditionalSerialization/docs/ParentPet.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/ParentPet.md new file mode 100644 index 00000000000..0e18ba6d591 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/ParentPet.md @@ -0,0 +1,10 @@ +# Org.OpenAPITools.Model.ParentPet + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**PetType** | **string** | | + +[[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-netcore/OpenAPIClient-ConditionalSerialization/docs/Pet.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/Pet.md new file mode 100644 index 00000000000..c7224764e2d --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/Pet.md @@ -0,0 +1,15 @@ +# Org.OpenAPITools.Model.Pet + +## 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** | **string** | pet status in the store | [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-netcore/OpenAPIClient-ConditionalSerialization/docs/PetApi.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/PetApi.md new file mode 100644 index 00000000000..47820f406dd --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/PetApi.md @@ -0,0 +1,689 @@ +# Org.OpenAPITools.Api.PetApi + +All URIs are relative to *http://petstore.swagger.io:80/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 +[**UploadFileWithRequiredFile**](PetApi.md#uploadfilewithrequiredfile) | **POST** /fake/{petId}/uploadImageWithRequiredFile | uploads an image (required) + + + +# **AddPet** +> void AddPet (Pet pet) + +Add a new pet to the store + +### 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 AddPetExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io:80/v2"; + // Configure OAuth2 access token for authorization: petstore_auth + config.AccessToken = "YOUR_ACCESS_TOKEN"; + + var apiInstance = new PetApi(config); + var pet = new Pet(); // Pet | Pet object that needs to be added to the store + + try + { + // Add a new pet to the store + apiInstance.AddPet(pet); + } + catch (ApiException e) + { + Debug.Print("Exception when calling PetApi.AddPet: " + 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 | + +### Return type + +void (empty response body) + +### Authorization + +[http_signature_test](../README.md#http_signature_test), [petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: application/json, application/xml + - **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **405** | Invalid input | - | + +[[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) + + +# **DeletePet** +> void DeletePet (long petId, string apiKey = null) + +Deletes a pet + +### 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 DeletePetExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io:80/v2"; + // Configure OAuth2 access token for authorization: petstore_auth + config.AccessToken = "YOUR_ACCESS_TOKEN"; + + var apiInstance = new PetApi(config); + var petId = 789; // long | Pet id to delete + var apiKey = apiKey_example; // string | (optional) + + try + { + // Deletes a pet + apiInstance.DeletePet(petId, apiKey); + } + catch (ApiException e) + { + Debug.Print("Exception when calling PetApi.DeletePet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **long**| Pet id to delete | + **apiKey** | **string**| | [optional] + +### Return type + +void (empty response body) + +### 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 | - | + +[[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) + + +# **FindPetsByStatus** +> List<Pet> FindPetsByStatus (List status) + +Finds Pets by status + +Multiple status values can be provided with comma separated strings + +### 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 FindPetsByStatusExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io:80/v2"; + // Configure OAuth2 access token for authorization: petstore_auth + config.AccessToken = "YOUR_ACCESS_TOKEN"; + + var apiInstance = new PetApi(config); + var status = status_example; // List | Status values that need to be considered for filter + + try + { + // Finds Pets by status + List result = apiInstance.FindPetsByStatus(status); + Debug.WriteLine(result); + } + catch (ApiException e) + { + Debug.Print("Exception when calling PetApi.FindPetsByStatus: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **status** | **List<string>**| Status values that need to be considered for filter | + +### Return type + +[**List<Pet>**](Pet.md) + +### Authorization + +[http_signature_test](../README.md#http_signature_test), [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 | - | + +[[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) + + +# **FindPetsByTags** +> List<Pet> FindPetsByTags (List tags) + +Finds Pets by tags + +Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + +### 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 FindPetsByTagsExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io:80/v2"; + // Configure OAuth2 access token for authorization: petstore_auth + config.AccessToken = "YOUR_ACCESS_TOKEN"; + + var apiInstance = new PetApi(config); + var tags = new List(); // List | Tags to filter by + + try + { + // Finds Pets by tags + List result = apiInstance.FindPetsByTags(tags); + Debug.WriteLine(result); + } + catch (ApiException e) + { + Debug.Print("Exception when calling PetApi.FindPetsByTags: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **tags** | [**List<string>**](string.md)| Tags to filter by | + +### Return type + +[**List<Pet>**](Pet.md) + +### Authorization + +[http_signature_test](../README.md#http_signature_test), [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 | - | + +[[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) + + +# **GetPetById** +> Pet GetPetById (long petId) + +Find pet by ID + +Returns a single pet + +### 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 GetPetByIdExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io:80/v2"; + // Configure API key authorization: api_key + 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"); + + var apiInstance = new PetApi(config); + var petId = 789; // long | ID of pet to return + + try + { + // Find pet by ID + Pet result = apiInstance.GetPetById(petId); + Debug.WriteLine(result); + } + catch (ApiException e) + { + Debug.Print("Exception when calling PetApi.GetPetById: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +### 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 | - | + +[[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) + + +# **UpdatePet** +> void UpdatePet (Pet pet) + +Update an existing pet + +### 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 UpdatePetExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io:80/v2"; + // Configure OAuth2 access token for authorization: petstore_auth + config.AccessToken = "YOUR_ACCESS_TOKEN"; + + var apiInstance = new PetApi(config); + var pet = new Pet(); // Pet | Pet object that needs to be added to the store + + try + { + // Update an existing pet + apiInstance.UpdatePet(pet); + } + catch (ApiException e) + { + Debug.Print("Exception when calling PetApi.UpdatePet: " + 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 | + +### Return type + +void (empty response body) + +### Authorization + +[http_signature_test](../README.md#http_signature_test), [petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: application/json, application/xml + - **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **400** | Invalid ID supplied | - | +| **404** | Pet not found | - | +| **405** | Validation exception | - | + +[[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) + + +# **UpdatePetWithForm** +> void UpdatePetWithForm (long petId, string name = null, string status = null) + +Updates a pet in the store with form data + +### 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 UpdatePetWithFormExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io:80/v2"; + // Configure OAuth2 access token for authorization: petstore_auth + config.AccessToken = "YOUR_ACCESS_TOKEN"; + + var apiInstance = new PetApi(config); + var petId = 789; // long | ID of pet that needs to be updated + var name = name_example; // string | Updated name of the pet (optional) + var status = status_example; // string | Updated status of the pet (optional) + + try + { + // Updates a pet in the store with form data + apiInstance.UpdatePetWithForm(petId, name, status); + } + catch (ApiException e) + { + Debug.Print("Exception when calling PetApi.UpdatePetWithForm: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +### 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 (empty response body) + +### 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 | - | + +[[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) + + +# **UploadFile** +> ApiResponse UploadFile (long petId, string additionalMetadata = null, System.IO.Stream file = null) + +uploads an image + +### 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 UploadFileExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io:80/v2"; + // Configure OAuth2 access token for authorization: petstore_auth + config.AccessToken = "YOUR_ACCESS_TOKEN"; + + var apiInstance = new PetApi(config); + var petId = 789; // long | ID of pet to update + var additionalMetadata = additionalMetadata_example; // string | Additional data to pass to server (optional) + var file = BINARY_DATA_HERE; // System.IO.Stream | file to upload (optional) + + try + { + // uploads an image + ApiResponse result = apiInstance.UploadFile(petId, additionalMetadata, file); + Debug.WriteLine(result); + } + catch (ApiException e) + { + Debug.Print("Exception when calling PetApi.UploadFile: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **long**| ID of pet to update | + **additionalMetadata** | **string**| Additional data to pass to server | [optional] + **file** | **System.IO.Stream****System.IO.Stream**| file to upload | [optional] + +### Return type + +[**ApiResponse**](ApiResponse.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 | - | + +[[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) + + +# **UploadFileWithRequiredFile** +> ApiResponse UploadFileWithRequiredFile (long petId, System.IO.Stream requiredFile, string additionalMetadata = null) + +uploads an image (required) + +### 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 UploadFileWithRequiredFileExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io:80/v2"; + // Configure OAuth2 access token for authorization: petstore_auth + config.AccessToken = "YOUR_ACCESS_TOKEN"; + + var apiInstance = new PetApi(config); + var petId = 789; // long | ID of pet to update + var requiredFile = BINARY_DATA_HERE; // System.IO.Stream | file to upload + var additionalMetadata = additionalMetadata_example; // string | Additional data to pass to server (optional) + + try + { + // uploads an image (required) + ApiResponse result = apiInstance.UploadFileWithRequiredFile(petId, requiredFile, additionalMetadata); + Debug.WriteLine(result); + } + catch (ApiException e) + { + Debug.Print("Exception when calling PetApi.UploadFileWithRequiredFile: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **long**| ID of pet to update | + **requiredFile** | **System.IO.Stream****System.IO.Stream**| file to upload | + **additionalMetadata** | **string**| Additional data to pass to server | [optional] + +### Return type + +[**ApiResponse**](ApiResponse.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 | - | + +[[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-netcore/OpenAPIClient-ConditionalSerialization/docs/Pig.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/Pig.md new file mode 100644 index 00000000000..6e86d0760d5 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/Pig.md @@ -0,0 +1,10 @@ +# Org.OpenAPITools.Model.Pig + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**ClassName** | **string** | | + +[[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-netcore/OpenAPIClient-ConditionalSerialization/docs/Quadrilateral.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/Quadrilateral.md new file mode 100644 index 00000000000..0165ddcc0e4 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/Quadrilateral.md @@ -0,0 +1,11 @@ +# Org.OpenAPITools.Model.Quadrilateral + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**ShapeType** | **string** | | +**QuadrilateralType** | **string** | | + +[[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-netcore/OpenAPIClient-ConditionalSerialization/docs/QuadrilateralInterface.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/QuadrilateralInterface.md new file mode 100644 index 00000000000..6daf340a141 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/QuadrilateralInterface.md @@ -0,0 +1,10 @@ +# Org.OpenAPITools.Model.QuadrilateralInterface + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**QuadrilateralType** | **string** | | + +[[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-netcore/OpenAPIClient-ConditionalSerialization/docs/ReadOnlyFirst.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/ReadOnlyFirst.md new file mode 100644 index 00000000000..b3f4a17ea34 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/ReadOnlyFirst.md @@ -0,0 +1,11 @@ +# Org.OpenAPITools.Model.ReadOnlyFirst + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Bar** | **string** | | [optional] [readonly] +**Baz** | **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-netcore/OpenAPIClient-ConditionalSerialization/docs/Return.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/Return.md new file mode 100644 index 00000000000..2c7c97e09da --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/Return.md @@ -0,0 +1,11 @@ +# Org.OpenAPITools.Model.Return +Model for testing reserved words + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**_Return** | **int** | | [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-netcore/OpenAPIClient-ConditionalSerialization/docs/ScaleneTriangle.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/ScaleneTriangle.md new file mode 100644 index 00000000000..76da8f1de81 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/ScaleneTriangle.md @@ -0,0 +1,11 @@ +# Org.OpenAPITools.Model.ScaleneTriangle + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**ShapeType** | **string** | | +**TriangleType** | **string** | | + +[[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-netcore/OpenAPIClient-ConditionalSerialization/docs/Shape.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/Shape.md new file mode 100644 index 00000000000..9a54628cd41 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/Shape.md @@ -0,0 +1,11 @@ +# Org.OpenAPITools.Model.Shape + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**ShapeType** | **string** | | +**QuadrilateralType** | **string** | | + +[[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-netcore/OpenAPIClient-ConditionalSerialization/docs/ShapeInterface.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/ShapeInterface.md new file mode 100644 index 00000000000..57456d6793f --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/ShapeInterface.md @@ -0,0 +1,10 @@ +# Org.OpenAPITools.Model.ShapeInterface + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**ShapeType** | **string** | | + +[[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-netcore/OpenAPIClient-ConditionalSerialization/docs/ShapeOrNull.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/ShapeOrNull.md new file mode 100644 index 00000000000..cbf61ebe77a --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/ShapeOrNull.md @@ -0,0 +1,12 @@ +# Org.OpenAPITools.Model.ShapeOrNull +The value may be a shape or the 'null' value. This is introduced in OAS schema >= 3.1. + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**ShapeType** | **string** | | +**QuadrilateralType** | **string** | | + +[[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-netcore/OpenAPIClient-ConditionalSerialization/docs/SimpleQuadrilateral.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/SimpleQuadrilateral.md new file mode 100644 index 00000000000..c329495425d --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/SimpleQuadrilateral.md @@ -0,0 +1,11 @@ +# Org.OpenAPITools.Model.SimpleQuadrilateral + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**ShapeType** | **string** | | +**QuadrilateralType** | **string** | | + +[[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-netcore/OpenAPIClient-ConditionalSerialization/docs/SpecialModelName.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/SpecialModelName.md new file mode 100644 index 00000000000..648179799e1 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/SpecialModelName.md @@ -0,0 +1,11 @@ +# Org.OpenAPITools.Model.SpecialModelName + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**SpecialPropertyName** | **long** | | [optional] +**_SpecialModelName** | **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-netcore/OpenAPIClient-ConditionalSerialization/docs/StoreApi.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/StoreApi.md new file mode 100644 index 00000000000..24e2480d5de --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/StoreApi.md @@ -0,0 +1,298 @@ +# Org.OpenAPITools.Api.StoreApi + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**DeleteOrder**](StoreApi.md#deleteorder) | **DELETE** /store/order/{order_id} | Delete purchase order by ID +[**GetInventory**](StoreApi.md#getinventory) | **GET** /store/inventory | Returns pet inventories by status +[**GetOrderById**](StoreApi.md#getorderbyid) | **GET** /store/order/{order_id} | Find purchase order by ID +[**PlaceOrder**](StoreApi.md#placeorder) | **POST** /store/order | Place an order for a pet + + + +# **DeleteOrder** +> void DeleteOrder (string 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 +```csharp +using System.Collections.Generic; +using System.Diagnostics; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Client; +using Org.OpenAPITools.Model; + +namespace Example +{ + public class DeleteOrderExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io:80/v2"; + var apiInstance = new StoreApi(config); + var orderId = orderId_example; // string | ID of the order that needs to be deleted + + try + { + // Delete purchase order by ID + apiInstance.DeleteOrder(orderId); + } + catch (ApiException e) + { + Debug.Print("Exception when calling StoreApi.DeleteOrder: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **orderId** | **string**| ID of the order that needs to be deleted | + +### Return type + +void (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 | - | + +[[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) + + +# **GetInventory** +> Dictionary<string, int> GetInventory () + +Returns pet inventories by status + +Returns a map of status codes to quantities + +### 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 GetInventoryExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io:80/v2"; + // Configure API key authorization: api_key + 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"); + + var apiInstance = new StoreApi(config); + + try + { + // Returns pet inventories by status + Dictionary result = apiInstance.GetInventory(); + Debug.WriteLine(result); + } + catch (ApiException e) + { + Debug.Print("Exception when calling StoreApi.GetInventory: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +### Parameters +This endpoint does not need any parameter. + +### Return type + +**Dictionary** + +### 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 | - | + +[[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) + + +# **GetOrderById** +> Order GetOrderById (long orderId) + +Find purchase order by ID + +For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + +### 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 GetOrderByIdExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io:80/v2"; + var apiInstance = new StoreApi(config); + var orderId = 789; // long | ID of pet that needs to be fetched + + try + { + // Find purchase order by ID + Order result = apiInstance.GetOrderById(orderId); + Debug.WriteLine(result); + } + catch (ApiException e) + { + Debug.Print("Exception when calling StoreApi.GetOrderById: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +### 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 | - | + +[[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) + + +# **PlaceOrder** +> Order PlaceOrder (Order order) + +Place an order for a pet + +### 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 PlaceOrderExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io:80/v2"; + var apiInstance = new StoreApi(config); + var order = new Order(); // Order | order placed for purchasing the pet + + try + { + // Place an order for a pet + Order result = apiInstance.PlaceOrder(order); + Debug.WriteLine(result); + } + catch (ApiException e) + { + Debug.Print("Exception when calling StoreApi.PlaceOrder: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +### 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 | - | + +[[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-netcore/OpenAPIClient-ConditionalSerialization/docs/Tag.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/Tag.md new file mode 100644 index 00000000000..fdd22eb31fd --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/Tag.md @@ -0,0 +1,11 @@ +# Org.OpenAPITools.Model.Tag + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Id** | **long** | | [optional] +**Name** | **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-netcore/OpenAPIClient-ConditionalSerialization/docs/Triangle.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/Triangle.md new file mode 100644 index 00000000000..c4d0452b4e8 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/Triangle.md @@ -0,0 +1,11 @@ +# Org.OpenAPITools.Model.Triangle + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**ShapeType** | **string** | | +**TriangleType** | **string** | | + +[[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-netcore/OpenAPIClient-ConditionalSerialization/docs/TriangleInterface.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/TriangleInterface.md new file mode 100644 index 00000000000..e0d8b5a5913 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/TriangleInterface.md @@ -0,0 +1,10 @@ +# Org.OpenAPITools.Model.TriangleInterface + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**TriangleType** | **string** | | + +[[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-netcore/OpenAPIClient-ConditionalSerialization/docs/User.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/User.md new file mode 100644 index 00000000000..b0cd4dc042b --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/User.md @@ -0,0 +1,21 @@ +# Org.OpenAPITools.Model.User + +## 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] +**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] + +[[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-netcore/OpenAPIClient-ConditionalSerialization/docs/UserApi.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/UserApi.md new file mode 100644 index 00000000000..aa12c26c69f --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/UserApi.md @@ -0,0 +1,573 @@ +# Org.OpenAPITools.Api.UserApi + +All URIs are relative to *http://petstore.swagger.io:80/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 user) + +Create user + +This can only be done by the logged in user. + +### 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 CreateUserExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io:80/v2"; + var apiInstance = new UserApi(config); + var user = new User(); // User | Created user object + + try + { + // Create user + apiInstance.CreateUser(user); + } + catch (ApiException e) + { + Debug.Print("Exception when calling UserApi.CreateUser: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **user** | [**User**](User.md)| Created user object | + +### 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 | +|-------------|-------------|------------------| +| **0** | 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) + + +# **CreateUsersWithArrayInput** +> void CreateUsersWithArrayInput (List user) + +Creates list of users with given input array + +### 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 CreateUsersWithArrayInputExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io:80/v2"; + var apiInstance = new UserApi(config); + var user = new List(); // List | List of user object + + try + { + // Creates list of users with given input array + apiInstance.CreateUsersWithArrayInput(user); + } + catch (ApiException e) + { + Debug.Print("Exception when calling UserApi.CreateUsersWithArrayInput: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **user** | [**List<User>**](User.md)| List of user object | + +### 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 | +|-------------|-------------|------------------| +| **0** | 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) + + +# **CreateUsersWithListInput** +> void CreateUsersWithListInput (List user) + +Creates list of users with given input array + +### 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 CreateUsersWithListInputExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io:80/v2"; + var apiInstance = new UserApi(config); + var user = new List(); // List | List of user object + + try + { + // Creates list of users with given input array + apiInstance.CreateUsersWithListInput(user); + } + catch (ApiException e) + { + Debug.Print("Exception when calling UserApi.CreateUsersWithListInput: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **user** | [**List<User>**](User.md)| List of user object | + +### 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 | +|-------------|-------------|------------------| +| **0** | 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) + + +# **DeleteUser** +> void DeleteUser (string username) + +Delete user + +This can only be done by the logged in user. + +### 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 DeleteUserExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io:80/v2"; + var apiInstance = new UserApi(config); + var username = username_example; // string | The name that needs to be deleted + + try + { + // Delete user + apiInstance.DeleteUser(username); + } + catch (ApiException e) + { + Debug.Print("Exception when calling UserApi.DeleteUser: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **string**| The name that needs to be deleted | + +### Return type + +void (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 username supplied | - | +| **404** | User not found | - | + +[[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) + + +# **GetUserByName** +> User GetUserByName (string username) + +Get user by user name + +### 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 GetUserByNameExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io:80/v2"; + var apiInstance = new UserApi(config); + var username = username_example; // string | The name that needs to be fetched. Use user1 for testing. + + try + { + // Get user by user name + User result = apiInstance.GetUserByName(username); + Debug.WriteLine(result); + } + catch (ApiException e) + { + Debug.Print("Exception when calling UserApi.GetUserByName: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +### 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 | - | + +[[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) + + +# **LoginUser** +> string LoginUser (string username, string password) + +Logs user into the system + +### 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 LoginUserExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io:80/v2"; + var apiInstance = new UserApi(config); + var username = username_example; // string | The user name for login + var password = password_example; // string | The password for login in clear text + + try + { + // Logs user into the system + string result = apiInstance.LoginUser(username, password); + Debug.WriteLine(result); + } + catch (ApiException e) + { + Debug.Print("Exception when calling UserApi.LoginUser: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +### 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 | * 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) + + +# **LogoutUser** +> void LogoutUser () + +Logs out current logged in user session + +### 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 LogoutUserExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io:80/v2"; + var apiInstance = new UserApi(config); + + try + { + // Logs out current logged in user session + apiInstance.LogoutUser(); + } + catch (ApiException e) + { + Debug.Print("Exception when calling UserApi.LogoutUser: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +### 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**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **0** | 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) + + +# **UpdateUser** +> void UpdateUser (string username, User user) + +Updated user + +This can only be done by the logged in user. + +### 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 UpdateUserExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io:80/v2"; + var apiInstance = new UserApi(config); + var username = username_example; // string | name that need to be deleted + var user = new User(); // User | Updated user object + + try + { + // Updated user + apiInstance.UpdateUser(username, user); + } + catch (ApiException e) + { + Debug.Print("Exception when calling UserApi.UpdateUser: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **string**| name that need to be deleted | + **user** | [**User**](User.md)| Updated user object | + +### 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 | +|-------------|-------------|------------------| +| **400** | Invalid user supplied | - | +| **404** | User not found | - | + +[[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-netcore/OpenAPIClient-ConditionalSerialization/docs/Whale.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/Whale.md new file mode 100644 index 00000000000..5fc3dc7f85c --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/Whale.md @@ -0,0 +1,12 @@ +# Org.OpenAPITools.Model.Whale + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**HasBaleen** | **bool** | | [optional] +**HasTeeth** | **bool** | | [optional] +**ClassName** | **string** | | + +[[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-netcore/OpenAPIClient-ConditionalSerialization/docs/Zebra.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/Zebra.md new file mode 100644 index 00000000000..31e686adf0e --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/docs/Zebra.md @@ -0,0 +1,11 @@ +# Org.OpenAPITools.Model.Zebra + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Type** | **string** | | [optional] +**ClassName** | **string** | | + +[[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-netcore/OpenAPIClient-ConditionalSerialization/git_push.sh b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/git_push.sh new file mode 100644 index 00000000000..ced3be2b0c7 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/git_push.sh @@ -0,0 +1,58 @@ +#!/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-pestore-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-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Api/AnotherFakeApiTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Api/AnotherFakeApiTests.cs new file mode 100644 index 00000000000..1d46982928d --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Api/AnotherFakeApiTests.cs @@ -0,0 +1,69 @@ +/* + * 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.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 AnotherFakeApi + /// + /// + /// 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 AnotherFakeApiTests : IDisposable + { + private AnotherFakeApi instance; + + public AnotherFakeApiTests() + { + instance = new AnotherFakeApi(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of AnotherFakeApi + /// + [Fact] + public void InstanceTest() + { + // TODO uncomment below to test 'IsType' AnotherFakeApi + //Assert.IsType(instance); + } + + /// + /// Test Call123TestSpecialTags + /// + [Fact] + public void Call123TestSpecialTagsTest() + { + // TODO uncomment below to test the method and replace null with proper value + //ModelClient modelClient = null; + //var response = instance.Call123TestSpecialTags(modelClient); + //Assert.IsType(response); + } + } +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Api/DefaultApiTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Api/DefaultApiTests.cs new file mode 100644 index 00000000000..76a930092ba --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Api/DefaultApiTests.cs @@ -0,0 +1,68 @@ +/* + * 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.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 FooGet + /// + [Fact] + public void FooGetTest() + { + // TODO uncomment below to test the method and replace null with proper value + //var response = instance.FooGet(); + //Assert.IsType(response); + } + } +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Api/FakeApiTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Api/FakeApiTests.cs new file mode 100644 index 00000000000..994cd46d38a --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Api/FakeApiTests.cs @@ -0,0 +1,258 @@ +/* + * 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.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 FakeApi + /// + /// + /// 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 FakeApiTests : IDisposable + { + private FakeApi instance; + + public FakeApiTests() + { + instance = new FakeApi(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of FakeApi + /// + [Fact] + public void InstanceTest() + { + // TODO uncomment below to test 'IsType' FakeApi + //Assert.IsType(instance); + } + + /// + /// Test FakeHealthGet + /// + [Fact] + public void FakeHealthGetTest() + { + // TODO uncomment below to test the method and replace null with proper value + //var response = instance.FakeHealthGet(); + //Assert.IsType(response); + } + + /// + /// Test FakeOuterBooleanSerialize + /// + [Fact] + public void FakeOuterBooleanSerializeTest() + { + // TODO uncomment below to test the method and replace null with proper value + //bool? body = null; + //var response = instance.FakeOuterBooleanSerialize(body); + //Assert.IsType(response); + } + + /// + /// Test FakeOuterCompositeSerialize + /// + [Fact] + public void FakeOuterCompositeSerializeTest() + { + // TODO uncomment below to test the method and replace null with proper value + //OuterComposite outerComposite = null; + //var response = instance.FakeOuterCompositeSerialize(outerComposite); + //Assert.IsType(response); + } + + /// + /// Test FakeOuterNumberSerialize + /// + [Fact] + public void FakeOuterNumberSerializeTest() + { + // TODO uncomment below to test the method and replace null with proper value + //decimal? body = null; + //var response = instance.FakeOuterNumberSerialize(body); + //Assert.IsType(response); + } + + /// + /// Test FakeOuterStringSerialize + /// + [Fact] + public void FakeOuterStringSerializeTest() + { + // TODO uncomment below to test the method and replace null with proper value + //string body = null; + //var response = instance.FakeOuterStringSerialize(body); + //Assert.IsType(response); + } + + /// + /// Test GetArrayOfEnums + /// + [Fact] + public void GetArrayOfEnumsTest() + { + // TODO uncomment below to test the method and replace null with proper value + //var response = instance.GetArrayOfEnums(); + //Assert.IsType>(response); + } + + /// + /// Test TestBodyWithFileSchema + /// + [Fact] + public void TestBodyWithFileSchemaTest() + { + // TODO uncomment below to test the method and replace null with proper value + //FileSchemaTestClass fileSchemaTestClass = null; + //instance.TestBodyWithFileSchema(fileSchemaTestClass); + } + + /// + /// Test TestBodyWithQueryParams + /// + [Fact] + public void TestBodyWithQueryParamsTest() + { + // TODO uncomment below to test the method and replace null with proper value + //string query = null; + //User user = null; + //instance.TestBodyWithQueryParams(query, user); + } + + /// + /// Test TestClientModel + /// + [Fact] + public void TestClientModelTest() + { + // TODO uncomment below to test the method and replace null with proper value + //ModelClient modelClient = null; + //var response = instance.TestClientModel(modelClient); + //Assert.IsType(response); + } + + /// + /// Test TestEndpointParameters + /// + [Fact] + public void TestEndpointParametersTest() + { + // TODO uncomment below to test the method and replace null with proper value + //decimal number = null; + //double _double = null; + //string patternWithoutDelimiter = null; + //byte[] _byte = null; + //int? integer = null; + //int? int32 = null; + //long? int64 = null; + //float? _float = null; + //string _string = null; + //System.IO.Stream binary = null; + //DateTime? date = null; + //DateTime? dateTime = null; + //string password = null; + //string callback = null; + //instance.TestEndpointParameters(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, _string, binary, date, dateTime, password, callback); + } + + /// + /// Test TestEnumParameters + /// + [Fact] + public void TestEnumParametersTest() + { + // TODO uncomment below to test the method and replace null with proper value + //List enumHeaderStringArray = null; + //string enumHeaderString = null; + //List enumQueryStringArray = null; + //string enumQueryString = null; + //int? enumQueryInteger = null; + //double? enumQueryDouble = null; + //List enumFormStringArray = null; + //string enumFormString = null; + //instance.TestEnumParameters(enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble, enumFormStringArray, enumFormString); + } + + /// + /// Test TestGroupParameters + /// + [Fact] + public void TestGroupParametersTest() + { + // TODO uncomment below to test the method and replace null with proper value + //int requiredStringGroup = null; + //bool requiredBooleanGroup = null; + //long requiredInt64Group = null; + //int? stringGroup = null; + //bool? booleanGroup = null; + //long? int64Group = null; + //instance.TestGroupParameters(requiredStringGroup, requiredBooleanGroup, requiredInt64Group, stringGroup, booleanGroup, int64Group); + } + + /// + /// Test TestInlineAdditionalProperties + /// + [Fact] + public void TestInlineAdditionalPropertiesTest() + { + // TODO uncomment below to test the method and replace null with proper value + //Dictionary requestBody = null; + //instance.TestInlineAdditionalProperties(requestBody); + } + + /// + /// Test TestJsonFormData + /// + [Fact] + public void TestJsonFormDataTest() + { + // TODO uncomment below to test the method and replace null with proper value + //string param = null; + //string param2 = null; + //instance.TestJsonFormData(param, param2); + } + + /// + /// Test TestQueryParameterCollectionFormat + /// + [Fact] + public void TestQueryParameterCollectionFormatTest() + { + // TODO uncomment below to test the method and replace null with proper value + //List pipe = null; + //List ioutil = null; + //List http = null; + //List url = null; + //List context = null; + //instance.TestQueryParameterCollectionFormat(pipe, ioutil, http, url, context); + } + } +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Api/FakeClassnameTags123ApiTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Api/FakeClassnameTags123ApiTests.cs new file mode 100644 index 00000000000..bbfd4a586e7 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Api/FakeClassnameTags123ApiTests.cs @@ -0,0 +1,69 @@ +/* + * 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.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 FakeClassnameTags123Api + /// + /// + /// 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 FakeClassnameTags123ApiTests : IDisposable + { + private FakeClassnameTags123Api instance; + + public FakeClassnameTags123ApiTests() + { + instance = new FakeClassnameTags123Api(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of FakeClassnameTags123Api + /// + [Fact] + public void InstanceTest() + { + // TODO uncomment below to test 'IsType' FakeClassnameTags123Api + //Assert.IsType(instance); + } + + /// + /// Test TestClassname + /// + [Fact] + public void TestClassnameTest() + { + // TODO uncomment below to test the method and replace null with proper value + //ModelClient modelClient = null; + //var response = instance.TestClassname(modelClient); + //Assert.IsType(response); + } + } +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Api/PetApiTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Api/PetApiTests.cs new file mode 100644 index 00000000000..67386764145 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Api/PetApiTests.cs @@ -0,0 +1,168 @@ +/* + * 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.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 PetApi + /// + /// + /// 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 PetApiTests : IDisposable + { + private PetApi instance; + + public PetApiTests() + { + instance = new PetApi(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of PetApi + /// + [Fact] + public void InstanceTest() + { + // TODO uncomment below to test 'IsType' PetApi + //Assert.IsType(instance); + } + + /// + /// Test AddPet + /// + [Fact] + public void AddPetTest() + { + // TODO uncomment below to test the method and replace null with proper value + //Pet pet = null; + //instance.AddPet(pet); + } + + /// + /// Test DeletePet + /// + [Fact] + public void DeletePetTest() + { + // TODO uncomment below to test the method and replace null with proper value + //long petId = null; + //string apiKey = null; + //instance.DeletePet(petId, apiKey); + } + + /// + /// Test FindPetsByStatus + /// + [Fact] + public void FindPetsByStatusTest() + { + // TODO uncomment below to test the method and replace null with proper value + //List status = null; + //var response = instance.FindPetsByStatus(status); + //Assert.IsType>(response); + } + + /// + /// Test FindPetsByTags + /// + [Fact] + public void FindPetsByTagsTest() + { + // TODO uncomment below to test the method and replace null with proper value + //List tags = null; + //var response = instance.FindPetsByTags(tags); + //Assert.IsType>(response); + } + + /// + /// Test GetPetById + /// + [Fact] + public void GetPetByIdTest() + { + // TODO uncomment below to test the method and replace null with proper value + //long petId = null; + //var response = instance.GetPetById(petId); + //Assert.IsType(response); + } + + /// + /// Test UpdatePet + /// + [Fact] + public void UpdatePetTest() + { + // TODO uncomment below to test the method and replace null with proper value + //Pet pet = null; + //instance.UpdatePet(pet); + } + + /// + /// Test UpdatePetWithForm + /// + [Fact] + public void UpdatePetWithFormTest() + { + // TODO uncomment below to test the method and replace null with proper value + //long petId = null; + //string name = null; + //string status = null; + //instance.UpdatePetWithForm(petId, name, status); + } + + /// + /// Test UploadFile + /// + [Fact] + public void UploadFileTest() + { + // TODO uncomment below to test the method and replace null with proper value + //long petId = null; + //string additionalMetadata = null; + //System.IO.Stream file = null; + //var response = instance.UploadFile(petId, additionalMetadata, file); + //Assert.IsType(response); + } + + /// + /// Test UploadFileWithRequiredFile + /// + [Fact] + public void UploadFileWithRequiredFileTest() + { + // TODO uncomment below to test the method and replace null with proper value + //long petId = null; + //System.IO.Stream requiredFile = null; + //string additionalMetadata = null; + //var response = instance.UploadFileWithRequiredFile(petId, requiredFile, additionalMetadata); + //Assert.IsType(response); + } + } +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Api/StoreApiTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Api/StoreApiTests.cs new file mode 100644 index 00000000000..48e9f32748d --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Api/StoreApiTests.cs @@ -0,0 +1,103 @@ +/* + * 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.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 StoreApi + /// + /// + /// 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 StoreApiTests : IDisposable + { + private StoreApi instance; + + public StoreApiTests() + { + instance = new StoreApi(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of StoreApi + /// + [Fact] + public void InstanceTest() + { + // TODO uncomment below to test 'IsType' StoreApi + //Assert.IsType(instance); + } + + /// + /// Test DeleteOrder + /// + [Fact] + public void DeleteOrderTest() + { + // TODO uncomment below to test the method and replace null with proper value + //string orderId = null; + //instance.DeleteOrder(orderId); + } + + /// + /// Test GetInventory + /// + [Fact] + public void GetInventoryTest() + { + // TODO uncomment below to test the method and replace null with proper value + //var response = instance.GetInventory(); + //Assert.IsType>(response); + } + + /// + /// Test GetOrderById + /// + [Fact] + public void GetOrderByIdTest() + { + // TODO uncomment below to test the method and replace null with proper value + //long orderId = null; + //var response = instance.GetOrderById(orderId); + //Assert.IsType(response); + } + + /// + /// Test PlaceOrder + /// + [Fact] + public void PlaceOrderTest() + { + // TODO uncomment below to test the method and replace null with proper value + //Order order = null; + //var response = instance.PlaceOrder(order); + //Assert.IsType(response); + } + } +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Api/UserApiTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Api/UserApiTests.cs new file mode 100644 index 00000000000..792db5819a0 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Api/UserApiTests.cs @@ -0,0 +1,148 @@ +/* + * 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.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 UserApi + /// + /// + /// 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 UserApiTests : IDisposable + { + private UserApi instance; + + public UserApiTests() + { + instance = new UserApi(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of UserApi + /// + [Fact] + public void InstanceTest() + { + // TODO uncomment below to test 'IsType' UserApi + //Assert.IsType(instance); + } + + /// + /// Test CreateUser + /// + [Fact] + public void CreateUserTest() + { + // TODO uncomment below to test the method and replace null with proper value + //User user = null; + //instance.CreateUser(user); + } + + /// + /// Test CreateUsersWithArrayInput + /// + [Fact] + public void CreateUsersWithArrayInputTest() + { + // TODO uncomment below to test the method and replace null with proper value + //List user = null; + //instance.CreateUsersWithArrayInput(user); + } + + /// + /// Test CreateUsersWithListInput + /// + [Fact] + public void CreateUsersWithListInputTest() + { + // TODO uncomment below to test the method and replace null with proper value + //List user = null; + //instance.CreateUsersWithListInput(user); + } + + /// + /// Test DeleteUser + /// + [Fact] + public void DeleteUserTest() + { + // TODO uncomment below to test the method and replace null with proper value + //string username = null; + //instance.DeleteUser(username); + } + + /// + /// Test GetUserByName + /// + [Fact] + public void GetUserByNameTest() + { + // TODO uncomment below to test the method and replace null with proper value + //string username = null; + //var response = instance.GetUserByName(username); + //Assert.IsType(response); + } + + /// + /// Test LoginUser + /// + [Fact] + public void LoginUserTest() + { + // TODO uncomment below to test the method and replace null with proper value + //string username = null; + //string password = null; + //var response = instance.LoginUser(username, password); + //Assert.IsType(response); + } + + /// + /// Test LogoutUser + /// + [Fact] + public void LogoutUserTest() + { + // TODO uncomment below to test the method and replace null with proper value + //instance.LogoutUser(); + } + + /// + /// Test UpdateUser + /// + [Fact] + public void UpdateUserTest() + { + // TODO uncomment below to test the method and replace null with proper value + //string username = null; + //User user = null; + //instance.UpdateUser(username, user); + } + } +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/AdditionalPropertiesClassTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/AdditionalPropertiesClassTests.cs new file mode 100644 index 00000000000..9ab029ed097 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/AdditionalPropertiesClassTests.cs @@ -0,0 +1,126 @@ +/* + * 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.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing AdditionalPropertiesClass + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class AdditionalPropertiesClassTests : IDisposable + { + // TODO uncomment below to declare an instance variable for AdditionalPropertiesClass + //private AdditionalPropertiesClass instance; + + public AdditionalPropertiesClassTests() + { + // TODO uncomment below to create an instance of AdditionalPropertiesClass + //instance = new AdditionalPropertiesClass(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of AdditionalPropertiesClass + /// + [Fact] + public void AdditionalPropertiesClassInstanceTest() + { + // TODO uncomment below to test "IsType" AdditionalPropertiesClass + //Assert.IsType(instance); + } + + + /// + /// Test the property 'MapProperty' + /// + [Fact] + public void MapPropertyTest() + { + // TODO unit test for the property 'MapProperty' + } + /// + /// Test the property 'MapOfMapProperty' + /// + [Fact] + public void MapOfMapPropertyTest() + { + // TODO unit test for the property 'MapOfMapProperty' + } + /// + /// Test the property 'Anytype1' + /// + [Fact] + public void Anytype1Test() + { + // TODO unit test for the property 'Anytype1' + } + /// + /// Test the property 'MapWithUndeclaredPropertiesAnytype1' + /// + [Fact] + public void MapWithUndeclaredPropertiesAnytype1Test() + { + // TODO unit test for the property 'MapWithUndeclaredPropertiesAnytype1' + } + /// + /// Test the property 'MapWithUndeclaredPropertiesAnytype2' + /// + [Fact] + public void MapWithUndeclaredPropertiesAnytype2Test() + { + // TODO unit test for the property 'MapWithUndeclaredPropertiesAnytype2' + } + /// + /// Test the property 'MapWithUndeclaredPropertiesAnytype3' + /// + [Fact] + public void MapWithUndeclaredPropertiesAnytype3Test() + { + // TODO unit test for the property 'MapWithUndeclaredPropertiesAnytype3' + } + /// + /// Test the property 'EmptyMap' + /// + [Fact] + public void EmptyMapTest() + { + // TODO unit test for the property 'EmptyMap' + } + /// + /// Test the property 'MapWithUndeclaredPropertiesString' + /// + [Fact] + public void MapWithUndeclaredPropertiesStringTest() + { + // TODO unit test for the property 'MapWithUndeclaredPropertiesString' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/AnimalTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/AnimalTests.cs new file mode 100644 index 00000000000..291231a91be --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/AnimalTests.cs @@ -0,0 +1,96 @@ +/* + * 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.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing Animal + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class AnimalTests : IDisposable + { + // TODO uncomment below to declare an instance variable for Animal + //private Animal instance; + + public AnimalTests() + { + // TODO uncomment below to create an instance of Animal + //instance = new Animal(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of Animal + /// + [Fact] + public void AnimalInstanceTest() + { + // TODO uncomment below to test "IsType" Animal + //Assert.IsType(instance); + } + + /// + /// Test deserialize a Dog from type Animal + /// + [Fact] + public void DogDeserializeFromAnimalTest() + { + // TODO uncomment below to test deserialize a Dog from type Animal + //Assert.IsType(JsonConvert.DeserializeObject(new Dog().ToJson())); + } + /// + /// Test deserialize a Cat from type Animal + /// + [Fact] + public void CatDeserializeFromAnimalTest() + { + // TODO uncomment below to test deserialize a Cat from type Animal + //Assert.IsType(JsonConvert.DeserializeObject(new Cat().ToJson())); + } + + /// + /// Test the property 'ClassName' + /// + [Fact] + public void ClassNameTest() + { + // TODO unit test for the property 'ClassName' + } + /// + /// Test the property 'Color' + /// + [Fact] + public void ColorTest() + { + // TODO unit test for the property 'Color' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/ApiResponseTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/ApiResponseTests.cs new file mode 100644 index 00000000000..2a2e098e608 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/ApiResponseTests.cs @@ -0,0 +1,86 @@ +/* + * 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.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing ApiResponse + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class ApiResponseTests : IDisposable + { + // TODO uncomment below to declare an instance variable for ApiResponse + //private ApiResponse instance; + + public ApiResponseTests() + { + // TODO uncomment below to create an instance of ApiResponse + //instance = new ApiResponse(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of ApiResponse + /// + [Fact] + public void ApiResponseInstanceTest() + { + // TODO uncomment below to test "IsType" ApiResponse + //Assert.IsType(instance); + } + + + /// + /// Test the property 'Code' + /// + [Fact] + public void CodeTest() + { + // TODO unit test for the property 'Code' + } + /// + /// Test the property 'Type' + /// + [Fact] + public void TypeTest() + { + // TODO unit test for the property 'Type' + } + /// + /// Test the property 'Message' + /// + [Fact] + public void MessageTest() + { + // TODO unit test for the property 'Message' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/AppleReqTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/AppleReqTests.cs new file mode 100644 index 00000000000..f945f659368 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/AppleReqTests.cs @@ -0,0 +1,78 @@ +/* + * 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.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing AppleReq + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class AppleReqTests : IDisposable + { + // TODO uncomment below to declare an instance variable for AppleReq + //private AppleReq instance; + + public AppleReqTests() + { + // TODO uncomment below to create an instance of AppleReq + //instance = new AppleReq(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of AppleReq + /// + [Fact] + public void AppleReqInstanceTest() + { + // TODO uncomment below to test "IsType" AppleReq + //Assert.IsType(instance); + } + + + /// + /// Test the property 'Cultivar' + /// + [Fact] + public void CultivarTest() + { + // TODO unit test for the property 'Cultivar' + } + /// + /// Test the property 'Mealy' + /// + [Fact] + public void MealyTest() + { + // TODO unit test for the property 'Mealy' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/AppleTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/AppleTests.cs new file mode 100644 index 00000000000..468d60184ad --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/AppleTests.cs @@ -0,0 +1,78 @@ +/* + * 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.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing Apple + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class AppleTests : IDisposable + { + // TODO uncomment below to declare an instance variable for Apple + //private Apple instance; + + public AppleTests() + { + // TODO uncomment below to create an instance of Apple + //instance = new Apple(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of Apple + /// + [Fact] + public void AppleInstanceTest() + { + // TODO uncomment below to test "IsType" Apple + //Assert.IsType(instance); + } + + + /// + /// Test the property 'Cultivar' + /// + [Fact] + public void CultivarTest() + { + // TODO unit test for the property 'Cultivar' + } + /// + /// Test the property 'Origin' + /// + [Fact] + public void OriginTest() + { + // TODO unit test for the property 'Origin' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/ArrayOfArrayOfNumberOnlyTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/ArrayOfArrayOfNumberOnlyTests.cs new file mode 100644 index 00000000000..0b259d7d391 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/ArrayOfArrayOfNumberOnlyTests.cs @@ -0,0 +1,70 @@ +/* + * 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.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing ArrayOfArrayOfNumberOnly + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class ArrayOfArrayOfNumberOnlyTests : IDisposable + { + // TODO uncomment below to declare an instance variable for ArrayOfArrayOfNumberOnly + //private ArrayOfArrayOfNumberOnly instance; + + public ArrayOfArrayOfNumberOnlyTests() + { + // TODO uncomment below to create an instance of ArrayOfArrayOfNumberOnly + //instance = new ArrayOfArrayOfNumberOnly(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of ArrayOfArrayOfNumberOnly + /// + [Fact] + public void ArrayOfArrayOfNumberOnlyInstanceTest() + { + // TODO uncomment below to test "IsType" ArrayOfArrayOfNumberOnly + //Assert.IsType(instance); + } + + + /// + /// Test the property 'ArrayArrayNumber' + /// + [Fact] + public void ArrayArrayNumberTest() + { + // TODO unit test for the property 'ArrayArrayNumber' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/ArrayOfNumberOnlyTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/ArrayOfNumberOnlyTests.cs new file mode 100644 index 00000000000..27f312ad25f --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/ArrayOfNumberOnlyTests.cs @@ -0,0 +1,70 @@ +/* + * 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.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing ArrayOfNumberOnly + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class ArrayOfNumberOnlyTests : IDisposable + { + // TODO uncomment below to declare an instance variable for ArrayOfNumberOnly + //private ArrayOfNumberOnly instance; + + public ArrayOfNumberOnlyTests() + { + // TODO uncomment below to create an instance of ArrayOfNumberOnly + //instance = new ArrayOfNumberOnly(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of ArrayOfNumberOnly + /// + [Fact] + public void ArrayOfNumberOnlyInstanceTest() + { + // TODO uncomment below to test "IsType" ArrayOfNumberOnly + //Assert.IsType(instance); + } + + + /// + /// Test the property 'ArrayNumber' + /// + [Fact] + public void ArrayNumberTest() + { + // TODO unit test for the property 'ArrayNumber' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/ArrayTestTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/ArrayTestTests.cs new file mode 100644 index 00000000000..a433e8c87cf --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/ArrayTestTests.cs @@ -0,0 +1,86 @@ +/* + * 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.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing ArrayTest + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class ArrayTestTests : IDisposable + { + // TODO uncomment below to declare an instance variable for ArrayTest + //private ArrayTest instance; + + public ArrayTestTests() + { + // TODO uncomment below to create an instance of ArrayTest + //instance = new ArrayTest(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of ArrayTest + /// + [Fact] + public void ArrayTestInstanceTest() + { + // TODO uncomment below to test "IsType" ArrayTest + //Assert.IsType(instance); + } + + + /// + /// Test the property 'ArrayOfString' + /// + [Fact] + public void ArrayOfStringTest() + { + // TODO unit test for the property 'ArrayOfString' + } + /// + /// Test the property 'ArrayArrayOfInteger' + /// + [Fact] + public void ArrayArrayOfIntegerTest() + { + // TODO unit test for the property 'ArrayArrayOfInteger' + } + /// + /// Test the property 'ArrayArrayOfModel' + /// + [Fact] + public void ArrayArrayOfModelTest() + { + // TODO unit test for the property 'ArrayArrayOfModel' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/BananaReqTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/BananaReqTests.cs new file mode 100644 index 00000000000..8a6eeb82eee --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/BananaReqTests.cs @@ -0,0 +1,78 @@ +/* + * 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.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing BananaReq + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class BananaReqTests : IDisposable + { + // TODO uncomment below to declare an instance variable for BananaReq + //private BananaReq instance; + + public BananaReqTests() + { + // TODO uncomment below to create an instance of BananaReq + //instance = new BananaReq(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of BananaReq + /// + [Fact] + public void BananaReqInstanceTest() + { + // TODO uncomment below to test "IsType" BananaReq + //Assert.IsType(instance); + } + + + /// + /// Test the property 'LengthCm' + /// + [Fact] + public void LengthCmTest() + { + // TODO unit test for the property 'LengthCm' + } + /// + /// Test the property 'Sweet' + /// + [Fact] + public void SweetTest() + { + // TODO unit test for the property 'Sweet' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/BananaTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/BananaTests.cs new file mode 100644 index 00000000000..8d8cc376b03 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/BananaTests.cs @@ -0,0 +1,70 @@ +/* + * 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.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing Banana + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class BananaTests : IDisposable + { + // TODO uncomment below to declare an instance variable for Banana + //private Banana instance; + + public BananaTests() + { + // TODO uncomment below to create an instance of Banana + //instance = new Banana(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of Banana + /// + [Fact] + public void BananaInstanceTest() + { + // TODO uncomment below to test "IsType" Banana + //Assert.IsType(instance); + } + + + /// + /// Test the property 'LengthCm' + /// + [Fact] + public void LengthCmTest() + { + // TODO unit test for the property 'LengthCm' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/BasquePigTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/BasquePigTests.cs new file mode 100644 index 00000000000..3cdccaa7595 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/BasquePigTests.cs @@ -0,0 +1,70 @@ +/* + * 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.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing BasquePig + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class BasquePigTests : IDisposable + { + // TODO uncomment below to declare an instance variable for BasquePig + //private BasquePig instance; + + public BasquePigTests() + { + // TODO uncomment below to create an instance of BasquePig + //instance = new BasquePig(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of BasquePig + /// + [Fact] + public void BasquePigInstanceTest() + { + // TODO uncomment below to test "IsType" BasquePig + //Assert.IsType(instance); + } + + + /// + /// Test the property 'ClassName' + /// + [Fact] + public void ClassNameTest() + { + // TODO unit test for the property 'ClassName' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/CapitalizationTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/CapitalizationTests.cs new file mode 100644 index 00000000000..185c83666fc --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/CapitalizationTests.cs @@ -0,0 +1,110 @@ +/* + * 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.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing Capitalization + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class CapitalizationTests : IDisposable + { + // TODO uncomment below to declare an instance variable for Capitalization + //private Capitalization instance; + + public CapitalizationTests() + { + // TODO uncomment below to create an instance of Capitalization + //instance = new Capitalization(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of Capitalization + /// + [Fact] + public void CapitalizationInstanceTest() + { + // TODO uncomment below to test "IsType" Capitalization + //Assert.IsType(instance); + } + + + /// + /// Test the property 'SmallCamel' + /// + [Fact] + public void SmallCamelTest() + { + // TODO unit test for the property 'SmallCamel' + } + /// + /// Test the property 'CapitalCamel' + /// + [Fact] + public void CapitalCamelTest() + { + // TODO unit test for the property 'CapitalCamel' + } + /// + /// Test the property 'SmallSnake' + /// + [Fact] + public void SmallSnakeTest() + { + // TODO unit test for the property 'SmallSnake' + } + /// + /// Test the property 'CapitalSnake' + /// + [Fact] + public void CapitalSnakeTest() + { + // TODO unit test for the property 'CapitalSnake' + } + /// + /// Test the property 'SCAETHFlowPoints' + /// + [Fact] + public void SCAETHFlowPointsTest() + { + // TODO unit test for the property 'SCAETHFlowPoints' + } + /// + /// Test the property 'ATT_NAME' + /// + [Fact] + public void ATT_NAMETest() + { + // TODO unit test for the property 'ATT_NAME' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/CatAllOfTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/CatAllOfTests.cs new file mode 100644 index 00000000000..fb51c28489c --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/CatAllOfTests.cs @@ -0,0 +1,70 @@ +/* + * 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.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing CatAllOf + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class CatAllOfTests : IDisposable + { + // TODO uncomment below to declare an instance variable for CatAllOf + //private CatAllOf instance; + + public CatAllOfTests() + { + // TODO uncomment below to create an instance of CatAllOf + //instance = new CatAllOf(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of CatAllOf + /// + [Fact] + public void CatAllOfInstanceTest() + { + // TODO uncomment below to test "IsType" CatAllOf + //Assert.IsType(instance); + } + + + /// + /// Test the property 'Declawed' + /// + [Fact] + public void DeclawedTest() + { + // TODO unit test for the property 'Declawed' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/CatTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/CatTests.cs new file mode 100644 index 00000000000..701ba760282 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/CatTests.cs @@ -0,0 +1,70 @@ +/* + * 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.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing Cat + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class CatTests : IDisposable + { + // TODO uncomment below to declare an instance variable for Cat + //private Cat instance; + + public CatTests() + { + // TODO uncomment below to create an instance of Cat + //instance = new Cat(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of Cat + /// + [Fact] + public void CatInstanceTest() + { + // TODO uncomment below to test "IsType" Cat + //Assert.IsType(instance); + } + + + /// + /// Test the property 'Declawed' + /// + [Fact] + public void DeclawedTest() + { + // TODO unit test for the property 'Declawed' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/CategoryTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/CategoryTests.cs new file mode 100644 index 00000000000..6ce48e601e4 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/CategoryTests.cs @@ -0,0 +1,78 @@ +/* + * 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.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing Category + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class CategoryTests : IDisposable + { + // TODO uncomment below to declare an instance variable for Category + //private Category instance; + + public CategoryTests() + { + // TODO uncomment below to create an instance of Category + //instance = new Category(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of Category + /// + [Fact] + public void CategoryInstanceTest() + { + // TODO uncomment below to test "IsType" Category + //Assert.IsType(instance); + } + + + /// + /// Test the property 'Id' + /// + [Fact] + public void IdTest() + { + // TODO unit test for the property 'Id' + } + /// + /// Test the property 'Name' + /// + [Fact] + public void NameTest() + { + // TODO unit test for the property 'Name' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/ChildCatAllOfTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/ChildCatAllOfTests.cs new file mode 100644 index 00000000000..49a53932490 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/ChildCatAllOfTests.cs @@ -0,0 +1,78 @@ +/* + * 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.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing ChildCatAllOf + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class ChildCatAllOfTests : IDisposable + { + // TODO uncomment below to declare an instance variable for ChildCatAllOf + //private ChildCatAllOf instance; + + public ChildCatAllOfTests() + { + // TODO uncomment below to create an instance of ChildCatAllOf + //instance = new ChildCatAllOf(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of ChildCatAllOf + /// + [Fact] + public void ChildCatAllOfInstanceTest() + { + // TODO uncomment below to test "IsType" ChildCatAllOf + //Assert.IsType(instance); + } + + + /// + /// Test the property 'Name' + /// + [Fact] + public void NameTest() + { + // TODO unit test for the property 'Name' + } + /// + /// Test the property 'PetType' + /// + [Fact] + public void PetTypeTest() + { + // TODO unit test for the property 'PetType' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/ChildCatTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/ChildCatTests.cs new file mode 100644 index 00000000000..68566fd8d56 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/ChildCatTests.cs @@ -0,0 +1,78 @@ +/* + * 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.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing ChildCat + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class ChildCatTests : IDisposable + { + // TODO uncomment below to declare an instance variable for ChildCat + //private ChildCat instance; + + public ChildCatTests() + { + // TODO uncomment below to create an instance of ChildCat + //instance = new ChildCat(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of ChildCat + /// + [Fact] + public void ChildCatInstanceTest() + { + // TODO uncomment below to test "IsType" ChildCat + //Assert.IsType(instance); + } + + + /// + /// Test the property 'Name' + /// + [Fact] + public void NameTest() + { + // TODO unit test for the property 'Name' + } + /// + /// Test the property 'PetType' + /// + [Fact] + public void PetTypeTest() + { + // TODO unit test for the property 'PetType' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/ClassModelTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/ClassModelTests.cs new file mode 100644 index 00000000000..d29472e83aa --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/ClassModelTests.cs @@ -0,0 +1,70 @@ +/* + * 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.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing ClassModel + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class ClassModelTests : IDisposable + { + // TODO uncomment below to declare an instance variable for ClassModel + //private ClassModel instance; + + public ClassModelTests() + { + // TODO uncomment below to create an instance of ClassModel + //instance = new ClassModel(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of ClassModel + /// + [Fact] + public void ClassModelInstanceTest() + { + // TODO uncomment below to test "IsType" ClassModel + //Assert.IsType(instance); + } + + + /// + /// Test the property 'Class' + /// + [Fact] + public void ClassTest() + { + // TODO unit test for the property 'Class' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/ComplexQuadrilateralTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/ComplexQuadrilateralTests.cs new file mode 100644 index 00000000000..b3529280c8d --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/ComplexQuadrilateralTests.cs @@ -0,0 +1,78 @@ +/* + * 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.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing ComplexQuadrilateral + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class ComplexQuadrilateralTests : IDisposable + { + // TODO uncomment below to declare an instance variable for ComplexQuadrilateral + //private ComplexQuadrilateral instance; + + public ComplexQuadrilateralTests() + { + // TODO uncomment below to create an instance of ComplexQuadrilateral + //instance = new ComplexQuadrilateral(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of ComplexQuadrilateral + /// + [Fact] + public void ComplexQuadrilateralInstanceTest() + { + // TODO uncomment below to test "IsType" ComplexQuadrilateral + //Assert.IsType(instance); + } + + + /// + /// Test the property 'ShapeType' + /// + [Fact] + public void ShapeTypeTest() + { + // TODO unit test for the property 'ShapeType' + } + /// + /// Test the property 'QuadrilateralType' + /// + [Fact] + public void QuadrilateralTypeTest() + { + // TODO unit test for the property 'QuadrilateralType' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/DanishPigTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/DanishPigTests.cs new file mode 100644 index 00000000000..572d9bffa79 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/DanishPigTests.cs @@ -0,0 +1,70 @@ +/* + * 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.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing DanishPig + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class DanishPigTests : IDisposable + { + // TODO uncomment below to declare an instance variable for DanishPig + //private DanishPig instance; + + public DanishPigTests() + { + // TODO uncomment below to create an instance of DanishPig + //instance = new DanishPig(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of DanishPig + /// + [Fact] + public void DanishPigInstanceTest() + { + // TODO uncomment below to test "IsType" DanishPig + //Assert.IsType(instance); + } + + + /// + /// Test the property 'ClassName' + /// + [Fact] + public void ClassNameTest() + { + // TODO unit test for the property 'ClassName' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/DogAllOfTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/DogAllOfTests.cs new file mode 100644 index 00000000000..b22a4442096 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/DogAllOfTests.cs @@ -0,0 +1,70 @@ +/* + * 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.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing DogAllOf + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class DogAllOfTests : IDisposable + { + // TODO uncomment below to declare an instance variable for DogAllOf + //private DogAllOf instance; + + public DogAllOfTests() + { + // TODO uncomment below to create an instance of DogAllOf + //instance = new DogAllOf(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of DogAllOf + /// + [Fact] + public void DogAllOfInstanceTest() + { + // TODO uncomment below to test "IsType" DogAllOf + //Assert.IsType(instance); + } + + + /// + /// Test the property 'Breed' + /// + [Fact] + public void BreedTest() + { + // TODO unit test for the property 'Breed' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/DogTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/DogTests.cs new file mode 100644 index 00000000000..992f93a51fd --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/DogTests.cs @@ -0,0 +1,70 @@ +/* + * 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.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing Dog + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class DogTests : IDisposable + { + // TODO uncomment below to declare an instance variable for Dog + //private Dog instance; + + public DogTests() + { + // TODO uncomment below to create an instance of Dog + //instance = new Dog(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of Dog + /// + [Fact] + public void DogInstanceTest() + { + // TODO uncomment below to test "IsType" Dog + //Assert.IsType(instance); + } + + + /// + /// Test the property 'Breed' + /// + [Fact] + public void BreedTest() + { + // TODO unit test for the property 'Breed' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/DrawingTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/DrawingTests.cs new file mode 100644 index 00000000000..0709ad9eeb3 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/DrawingTests.cs @@ -0,0 +1,94 @@ +/* + * 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.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing Drawing + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class DrawingTests : IDisposable + { + // TODO uncomment below to declare an instance variable for Drawing + //private Drawing instance; + + public DrawingTests() + { + // TODO uncomment below to create an instance of Drawing + //instance = new Drawing(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of Drawing + /// + [Fact] + public void DrawingInstanceTest() + { + // TODO uncomment below to test "IsType" Drawing + //Assert.IsType(instance); + } + + + /// + /// Test the property 'MainShape' + /// + [Fact] + public void MainShapeTest() + { + // TODO unit test for the property 'MainShape' + } + /// + /// Test the property 'ShapeOrNull' + /// + [Fact] + public void ShapeOrNullTest() + { + // TODO unit test for the property 'ShapeOrNull' + } + /// + /// Test the property 'NullableShape' + /// + [Fact] + public void NullableShapeTest() + { + // TODO unit test for the property 'NullableShape' + } + /// + /// Test the property 'Shapes' + /// + [Fact] + public void ShapesTest() + { + // TODO unit test for the property 'Shapes' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/EnumArraysTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/EnumArraysTests.cs new file mode 100644 index 00000000000..5779ca29477 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/EnumArraysTests.cs @@ -0,0 +1,78 @@ +/* + * 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.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing EnumArrays + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class EnumArraysTests : IDisposable + { + // TODO uncomment below to declare an instance variable for EnumArrays + //private EnumArrays instance; + + public EnumArraysTests() + { + // TODO uncomment below to create an instance of EnumArrays + //instance = new EnumArrays(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of EnumArrays + /// + [Fact] + public void EnumArraysInstanceTest() + { + // TODO uncomment below to test "IsType" EnumArrays + //Assert.IsType(instance); + } + + + /// + /// Test the property 'JustSymbol' + /// + [Fact] + public void JustSymbolTest() + { + // TODO unit test for the property 'JustSymbol' + } + /// + /// Test the property 'ArrayEnum' + /// + [Fact] + public void ArrayEnumTest() + { + // TODO unit test for the property 'ArrayEnum' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/EnumClassTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/EnumClassTests.cs new file mode 100644 index 00000000000..a17738c5cbc --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/EnumClassTests.cs @@ -0,0 +1,62 @@ +/* + * 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.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing EnumClass + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class EnumClassTests : IDisposable + { + // TODO uncomment below to declare an instance variable for EnumClass + //private EnumClass instance; + + public EnumClassTests() + { + // TODO uncomment below to create an instance of EnumClass + //instance = new EnumClass(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of EnumClass + /// + [Fact] + public void EnumClassInstanceTest() + { + // TODO uncomment below to test "IsType" EnumClass + //Assert.IsType(instance); + } + + + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/EnumTestTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/EnumTestTests.cs new file mode 100644 index 00000000000..4f81b845d49 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/EnumTestTests.cs @@ -0,0 +1,134 @@ +/* + * 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.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing EnumTest + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class EnumTestTests : IDisposable + { + // TODO uncomment below to declare an instance variable for EnumTest + //private EnumTest instance; + + public EnumTestTests() + { + // TODO uncomment below to create an instance of EnumTest + //instance = new EnumTest(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of EnumTest + /// + [Fact] + public void EnumTestInstanceTest() + { + // TODO uncomment below to test "IsType" EnumTest + //Assert.IsType(instance); + } + + + /// + /// Test the property 'EnumString' + /// + [Fact] + public void EnumStringTest() + { + // TODO unit test for the property 'EnumString' + } + /// + /// Test the property 'EnumStringRequired' + /// + [Fact] + public void EnumStringRequiredTest() + { + // TODO unit test for the property 'EnumStringRequired' + } + /// + /// Test the property 'EnumInteger' + /// + [Fact] + public void EnumIntegerTest() + { + // TODO unit test for the property 'EnumInteger' + } + /// + /// Test the property 'EnumIntegerOnly' + /// + [Fact] + public void EnumIntegerOnlyTest() + { + // TODO unit test for the property 'EnumIntegerOnly' + } + /// + /// Test the property 'EnumNumber' + /// + [Fact] + public void EnumNumberTest() + { + // TODO unit test for the property 'EnumNumber' + } + /// + /// Test the property 'OuterEnum' + /// + [Fact] + public void OuterEnumTest() + { + // TODO unit test for the property 'OuterEnum' + } + /// + /// Test the property 'OuterEnumInteger' + /// + [Fact] + public void OuterEnumIntegerTest() + { + // TODO unit test for the property 'OuterEnumInteger' + } + /// + /// Test the property 'OuterEnumDefaultValue' + /// + [Fact] + public void OuterEnumDefaultValueTest() + { + // TODO unit test for the property 'OuterEnumDefaultValue' + } + /// + /// Test the property 'OuterEnumIntegerDefaultValue' + /// + [Fact] + public void OuterEnumIntegerDefaultValueTest() + { + // TODO unit test for the property 'OuterEnumIntegerDefaultValue' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/EquilateralTriangleTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/EquilateralTriangleTests.cs new file mode 100644 index 00000000000..4663cb667de --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/EquilateralTriangleTests.cs @@ -0,0 +1,78 @@ +/* + * 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.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing EquilateralTriangle + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class EquilateralTriangleTests : IDisposable + { + // TODO uncomment below to declare an instance variable for EquilateralTriangle + //private EquilateralTriangle instance; + + public EquilateralTriangleTests() + { + // TODO uncomment below to create an instance of EquilateralTriangle + //instance = new EquilateralTriangle(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of EquilateralTriangle + /// + [Fact] + public void EquilateralTriangleInstanceTest() + { + // TODO uncomment below to test "IsType" EquilateralTriangle + //Assert.IsType(instance); + } + + + /// + /// Test the property 'ShapeType' + /// + [Fact] + public void ShapeTypeTest() + { + // TODO unit test for the property 'ShapeType' + } + /// + /// Test the property 'TriangleType' + /// + [Fact] + public void TriangleTypeTest() + { + // TODO unit test for the property 'TriangleType' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/FileSchemaTestClassTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/FileSchemaTestClassTests.cs new file mode 100644 index 00000000000..9f45b4fe89d --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/FileSchemaTestClassTests.cs @@ -0,0 +1,78 @@ +/* + * 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.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing FileSchemaTestClass + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class FileSchemaTestClassTests : IDisposable + { + // TODO uncomment below to declare an instance variable for FileSchemaTestClass + //private FileSchemaTestClass instance; + + public FileSchemaTestClassTests() + { + // TODO uncomment below to create an instance of FileSchemaTestClass + //instance = new FileSchemaTestClass(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of FileSchemaTestClass + /// + [Fact] + public void FileSchemaTestClassInstanceTest() + { + // TODO uncomment below to test "IsType" FileSchemaTestClass + //Assert.IsType(instance); + } + + + /// + /// Test the property 'File' + /// + [Fact] + public void FileTest() + { + // TODO unit test for the property 'File' + } + /// + /// Test the property 'Files' + /// + [Fact] + public void FilesTest() + { + // TODO unit test for the property 'Files' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/FileTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/FileTests.cs new file mode 100644 index 00000000000..761bb72a844 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/FileTests.cs @@ -0,0 +1,70 @@ +/* + * 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.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing File + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class FileTests : IDisposable + { + // TODO uncomment below to declare an instance variable for File + //private File instance; + + public FileTests() + { + // TODO uncomment below to create an instance of File + //instance = new File(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of File + /// + [Fact] + public void FileInstanceTest() + { + // TODO uncomment below to test "IsType" File + //Assert.IsType(instance); + } + + + /// + /// Test the property 'SourceURI' + /// + [Fact] + public void SourceURITest() + { + // TODO unit test for the property 'SourceURI' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/FooTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/FooTests.cs new file mode 100644 index 00000000000..0b6ed52edbd --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/FooTests.cs @@ -0,0 +1,70 @@ +/* + * 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.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing Foo + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class FooTests : IDisposable + { + // TODO uncomment below to declare an instance variable for Foo + //private Foo instance; + + public FooTests() + { + // TODO uncomment below to create an instance of Foo + //instance = new Foo(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of Foo + /// + [Fact] + public void FooInstanceTest() + { + // TODO uncomment below to test "IsType" Foo + //Assert.IsType(instance); + } + + + /// + /// Test the property 'Bar' + /// + [Fact] + public void BarTest() + { + // TODO unit test for the property 'Bar' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/FormatTestTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/FormatTestTests.cs new file mode 100644 index 00000000000..97332800e9a --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/FormatTestTests.cs @@ -0,0 +1,190 @@ +/* + * 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.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing FormatTest + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class FormatTestTests : IDisposable + { + // TODO uncomment below to declare an instance variable for FormatTest + //private FormatTest instance; + + public FormatTestTests() + { + // TODO uncomment below to create an instance of FormatTest + //instance = new FormatTest(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of FormatTest + /// + [Fact] + public void FormatTestInstanceTest() + { + // TODO uncomment below to test "IsType" FormatTest + //Assert.IsType(instance); + } + + + /// + /// Test the property 'Integer' + /// + [Fact] + public void IntegerTest() + { + // TODO unit test for the property 'Integer' + } + /// + /// Test the property 'Int32' + /// + [Fact] + public void Int32Test() + { + // TODO unit test for the property 'Int32' + } + /// + /// Test the property 'Int64' + /// + [Fact] + public void Int64Test() + { + // TODO unit test for the property 'Int64' + } + /// + /// Test the property 'Number' + /// + [Fact] + public void NumberTest() + { + // TODO unit test for the property 'Number' + } + /// + /// Test the property 'Float' + /// + [Fact] + public void FloatTest() + { + // TODO unit test for the property 'Float' + } + /// + /// Test the property 'Double' + /// + [Fact] + public void DoubleTest() + { + // TODO unit test for the property 'Double' + } + /// + /// Test the property 'Decimal' + /// + [Fact] + public void DecimalTest() + { + // TODO unit test for the property 'Decimal' + } + /// + /// Test the property 'String' + /// + [Fact] + public void StringTest() + { + // TODO unit test for the property 'String' + } + /// + /// Test the property 'Byte' + /// + [Fact] + public void ByteTest() + { + // TODO unit test for the property 'Byte' + } + /// + /// Test the property 'Binary' + /// + [Fact] + public void BinaryTest() + { + // TODO unit test for the property 'Binary' + } + /// + /// Test the property 'Date' + /// + [Fact] + public void DateTest() + { + // TODO unit test for the property 'Date' + } + /// + /// Test the property 'DateTime' + /// + [Fact] + public void DateTimeTest() + { + // TODO unit test for the property 'DateTime' + } + /// + /// Test the property 'Uuid' + /// + [Fact] + public void UuidTest() + { + // TODO unit test for the property 'Uuid' + } + /// + /// Test the property 'Password' + /// + [Fact] + public void PasswordTest() + { + // TODO unit test for the property 'Password' + } + /// + /// Test the property 'PatternWithDigits' + /// + [Fact] + public void PatternWithDigitsTest() + { + // TODO unit test for the property 'PatternWithDigits' + } + /// + /// Test the property 'PatternWithDigitsAndDelimiter' + /// + [Fact] + public void PatternWithDigitsAndDelimiterTest() + { + // TODO unit test for the property 'PatternWithDigitsAndDelimiter' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/FruitReqTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/FruitReqTests.cs new file mode 100644 index 00000000000..5ea9e3ffc1d --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/FruitReqTests.cs @@ -0,0 +1,94 @@ +/* + * 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.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing FruitReq + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class FruitReqTests : IDisposable + { + // TODO uncomment below to declare an instance variable for FruitReq + //private FruitReq instance; + + public FruitReqTests() + { + // TODO uncomment below to create an instance of FruitReq + //instance = new FruitReq(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of FruitReq + /// + [Fact] + public void FruitReqInstanceTest() + { + // TODO uncomment below to test "IsType" FruitReq + //Assert.IsType(instance); + } + + + /// + /// Test the property 'Cultivar' + /// + [Fact] + public void CultivarTest() + { + // TODO unit test for the property 'Cultivar' + } + /// + /// Test the property 'Mealy' + /// + [Fact] + public void MealyTest() + { + // TODO unit test for the property 'Mealy' + } + /// + /// Test the property 'LengthCm' + /// + [Fact] + public void LengthCmTest() + { + // TODO unit test for the property 'LengthCm' + } + /// + /// Test the property 'Sweet' + /// + [Fact] + public void SweetTest() + { + // TODO unit test for the property 'Sweet' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/FruitTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/FruitTests.cs new file mode 100644 index 00000000000..91e069bb42f --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/FruitTests.cs @@ -0,0 +1,94 @@ +/* + * 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.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing Fruit + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class FruitTests : IDisposable + { + // TODO uncomment below to declare an instance variable for Fruit + //private Fruit instance; + + public FruitTests() + { + // TODO uncomment below to create an instance of Fruit + //instance = new Fruit(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of Fruit + /// + [Fact] + public void FruitInstanceTest() + { + // TODO uncomment below to test "IsType" Fruit + //Assert.IsType(instance); + } + + + /// + /// Test the property 'Color' + /// + [Fact] + public void ColorTest() + { + // TODO unit test for the property 'Color' + } + /// + /// Test the property 'Cultivar' + /// + [Fact] + public void CultivarTest() + { + // TODO unit test for the property 'Cultivar' + } + /// + /// Test the property 'Origin' + /// + [Fact] + public void OriginTest() + { + // TODO unit test for the property 'Origin' + } + /// + /// Test the property 'LengthCm' + /// + [Fact] + public void LengthCmTest() + { + // TODO unit test for the property 'LengthCm' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/GmFruitTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/GmFruitTests.cs new file mode 100644 index 00000000000..08fb0e07a1c --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/GmFruitTests.cs @@ -0,0 +1,94 @@ +/* + * 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.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing GmFruit + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class GmFruitTests : IDisposable + { + // TODO uncomment below to declare an instance variable for GmFruit + //private GmFruit instance; + + public GmFruitTests() + { + // TODO uncomment below to create an instance of GmFruit + //instance = new GmFruit(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of GmFruit + /// + [Fact] + public void GmFruitInstanceTest() + { + // TODO uncomment below to test "IsType" GmFruit + //Assert.IsType(instance); + } + + + /// + /// Test the property 'Color' + /// + [Fact] + public void ColorTest() + { + // TODO unit test for the property 'Color' + } + /// + /// Test the property 'Cultivar' + /// + [Fact] + public void CultivarTest() + { + // TODO unit test for the property 'Cultivar' + } + /// + /// Test the property 'Origin' + /// + [Fact] + public void OriginTest() + { + // TODO unit test for the property 'Origin' + } + /// + /// Test the property 'LengthCm' + /// + [Fact] + public void LengthCmTest() + { + // TODO unit test for the property 'LengthCm' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/GrandparentAnimalTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/GrandparentAnimalTests.cs new file mode 100644 index 00000000000..75f4fd8b0e5 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/GrandparentAnimalTests.cs @@ -0,0 +1,88 @@ +/* + * 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.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing GrandparentAnimal + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class GrandparentAnimalTests : IDisposable + { + // TODO uncomment below to declare an instance variable for GrandparentAnimal + //private GrandparentAnimal instance; + + public GrandparentAnimalTests() + { + // TODO uncomment below to create an instance of GrandparentAnimal + //instance = new GrandparentAnimal(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of GrandparentAnimal + /// + [Fact] + public void GrandparentAnimalInstanceTest() + { + // TODO uncomment below to test "IsType" GrandparentAnimal + //Assert.IsType(instance); + } + + /// + /// Test deserialize a ParentPet from type GrandparentAnimal + /// + [Fact] + public void ParentPetDeserializeFromGrandparentAnimalTest() + { + // TODO uncomment below to test deserialize a ParentPet from type GrandparentAnimal + //Assert.IsType(JsonConvert.DeserializeObject(new ParentPet().ToJson())); + } + /// + /// Test deserialize a ChildCat from type ParentPet + /// + [Fact] + public void ChildCatDeserializeFromParentPetTest() + { + // TODO uncomment below to test deserialize a ChildCat from type ParentPet + //Assert.IsType(JsonConvert.DeserializeObject(new ChildCat().ToJson())); + } + + /// + /// Test the property 'PetType' + /// + [Fact] + public void PetTypeTest() + { + // TODO unit test for the property 'PetType' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/HasOnlyReadOnlyTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/HasOnlyReadOnlyTests.cs new file mode 100644 index 00000000000..651a9f0ce30 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/HasOnlyReadOnlyTests.cs @@ -0,0 +1,78 @@ +/* + * 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.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing HasOnlyReadOnly + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class HasOnlyReadOnlyTests : IDisposable + { + // TODO uncomment below to declare an instance variable for HasOnlyReadOnly + //private HasOnlyReadOnly instance; + + public HasOnlyReadOnlyTests() + { + // TODO uncomment below to create an instance of HasOnlyReadOnly + //instance = new HasOnlyReadOnly(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of HasOnlyReadOnly + /// + [Fact] + public void HasOnlyReadOnlyInstanceTest() + { + // TODO uncomment below to test "IsType" HasOnlyReadOnly + //Assert.IsType(instance); + } + + + /// + /// Test the property 'Bar' + /// + [Fact] + public void BarTest() + { + // TODO unit test for the property 'Bar' + } + /// + /// Test the property 'Foo' + /// + [Fact] + public void FooTest() + { + // TODO unit test for the property 'Foo' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/HealthCheckResultTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/HealthCheckResultTests.cs new file mode 100644 index 00000000000..857190a3334 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/HealthCheckResultTests.cs @@ -0,0 +1,70 @@ +/* + * 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.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing HealthCheckResult + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class HealthCheckResultTests : IDisposable + { + // TODO uncomment below to declare an instance variable for HealthCheckResult + //private HealthCheckResult instance; + + public HealthCheckResultTests() + { + // TODO uncomment below to create an instance of HealthCheckResult + //instance = new HealthCheckResult(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of HealthCheckResult + /// + [Fact] + public void HealthCheckResultInstanceTest() + { + // TODO uncomment below to test "IsType" HealthCheckResult + //Assert.IsType(instance); + } + + + /// + /// Test the property 'NullableMessage' + /// + [Fact] + public void NullableMessageTest() + { + // TODO unit test for the property 'NullableMessage' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/InlineResponseDefaultTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/InlineResponseDefaultTests.cs new file mode 100644 index 00000000000..7731f80c16d --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/InlineResponseDefaultTests.cs @@ -0,0 +1,70 @@ +/* + * 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.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing InlineResponseDefault + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class InlineResponseDefaultTests : IDisposable + { + // TODO uncomment below to declare an instance variable for InlineResponseDefault + //private InlineResponseDefault instance; + + public InlineResponseDefaultTests() + { + // TODO uncomment below to create an instance of InlineResponseDefault + //instance = new InlineResponseDefault(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of InlineResponseDefault + /// + [Fact] + public void InlineResponseDefaultInstanceTest() + { + // TODO uncomment below to test "IsType" InlineResponseDefault + //Assert.IsType(instance); + } + + + /// + /// Test the property 'String' + /// + [Fact] + public void StringTest() + { + // TODO unit test for the property 'String' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/IsoscelesTriangleTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/IsoscelesTriangleTests.cs new file mode 100644 index 00000000000..755c417cc54 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/IsoscelesTriangleTests.cs @@ -0,0 +1,78 @@ +/* + * 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.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing IsoscelesTriangle + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class IsoscelesTriangleTests : IDisposable + { + // TODO uncomment below to declare an instance variable for IsoscelesTriangle + //private IsoscelesTriangle instance; + + public IsoscelesTriangleTests() + { + // TODO uncomment below to create an instance of IsoscelesTriangle + //instance = new IsoscelesTriangle(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of IsoscelesTriangle + /// + [Fact] + public void IsoscelesTriangleInstanceTest() + { + // TODO uncomment below to test "IsType" IsoscelesTriangle + //Assert.IsType(instance); + } + + + /// + /// Test the property 'ShapeType' + /// + [Fact] + public void ShapeTypeTest() + { + // TODO unit test for the property 'ShapeType' + } + /// + /// Test the property 'TriangleType' + /// + [Fact] + public void TriangleTypeTest() + { + // TODO unit test for the property 'TriangleType' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/ListTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/ListTests.cs new file mode 100644 index 00000000000..2ed828d0520 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/ListTests.cs @@ -0,0 +1,70 @@ +/* + * 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.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing List + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class ListTests : IDisposable + { + // TODO uncomment below to declare an instance variable for List + //private List instance; + + public ListTests() + { + // TODO uncomment below to create an instance of List + //instance = new List(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of List + /// + [Fact] + public void ListInstanceTest() + { + // TODO uncomment below to test "IsType" List + //Assert.IsType(instance); + } + + + /// + /// Test the property '_123List' + /// + [Fact] + public void _123ListTest() + { + // TODO unit test for the property '_123List' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/MammalTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/MammalTests.cs new file mode 100644 index 00000000000..7b46cbf0645 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/MammalTests.cs @@ -0,0 +1,94 @@ +/* + * 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.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing Mammal + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class MammalTests : IDisposable + { + // TODO uncomment below to declare an instance variable for Mammal + //private Mammal instance; + + public MammalTests() + { + // TODO uncomment below to create an instance of Mammal + //instance = new Mammal(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of Mammal + /// + [Fact] + public void MammalInstanceTest() + { + // TODO uncomment below to test "IsType" Mammal + //Assert.IsType(instance); + } + + + /// + /// Test the property 'HasBaleen' + /// + [Fact] + public void HasBaleenTest() + { + // TODO unit test for the property 'HasBaleen' + } + /// + /// Test the property 'HasTeeth' + /// + [Fact] + public void HasTeethTest() + { + // TODO unit test for the property 'HasTeeth' + } + /// + /// Test the property 'ClassName' + /// + [Fact] + public void ClassNameTest() + { + // TODO unit test for the property 'ClassName' + } + /// + /// Test the property 'Type' + /// + [Fact] + public void TypeTest() + { + // TODO unit test for the property 'Type' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/MapTestTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/MapTestTests.cs new file mode 100644 index 00000000000..20036e1c905 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/MapTestTests.cs @@ -0,0 +1,94 @@ +/* + * 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.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing MapTest + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class MapTestTests : IDisposable + { + // TODO uncomment below to declare an instance variable for MapTest + //private MapTest instance; + + public MapTestTests() + { + // TODO uncomment below to create an instance of MapTest + //instance = new MapTest(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of MapTest + /// + [Fact] + public void MapTestInstanceTest() + { + // TODO uncomment below to test "IsType" MapTest + //Assert.IsType(instance); + } + + + /// + /// Test the property 'MapMapOfString' + /// + [Fact] + public void MapMapOfStringTest() + { + // TODO unit test for the property 'MapMapOfString' + } + /// + /// Test the property 'MapOfEnumString' + /// + [Fact] + public void MapOfEnumStringTest() + { + // TODO unit test for the property 'MapOfEnumString' + } + /// + /// Test the property 'DirectMap' + /// + [Fact] + public void DirectMapTest() + { + // TODO unit test for the property 'DirectMap' + } + /// + /// Test the property 'IndirectMap' + /// + [Fact] + public void IndirectMapTest() + { + // TODO unit test for the property 'IndirectMap' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/MixedPropertiesAndAdditionalPropertiesClassTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/MixedPropertiesAndAdditionalPropertiesClassTests.cs new file mode 100644 index 00000000000..f56cd715f45 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/MixedPropertiesAndAdditionalPropertiesClassTests.cs @@ -0,0 +1,86 @@ +/* + * 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.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing MixedPropertiesAndAdditionalPropertiesClass + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class MixedPropertiesAndAdditionalPropertiesClassTests : IDisposable + { + // TODO uncomment below to declare an instance variable for MixedPropertiesAndAdditionalPropertiesClass + //private MixedPropertiesAndAdditionalPropertiesClass instance; + + public MixedPropertiesAndAdditionalPropertiesClassTests() + { + // TODO uncomment below to create an instance of MixedPropertiesAndAdditionalPropertiesClass + //instance = new MixedPropertiesAndAdditionalPropertiesClass(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of MixedPropertiesAndAdditionalPropertiesClass + /// + [Fact] + public void MixedPropertiesAndAdditionalPropertiesClassInstanceTest() + { + // TODO uncomment below to test "IsType" MixedPropertiesAndAdditionalPropertiesClass + //Assert.IsType(instance); + } + + + /// + /// Test the property 'Uuid' + /// + [Fact] + public void UuidTest() + { + // TODO unit test for the property 'Uuid' + } + /// + /// Test the property 'DateTime' + /// + [Fact] + public void DateTimeTest() + { + // TODO unit test for the property 'DateTime' + } + /// + /// Test the property 'Map' + /// + [Fact] + public void MapTest() + { + // TODO unit test for the property 'Map' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/Model200ResponseTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/Model200ResponseTests.cs new file mode 100644 index 00000000000..e25478618f2 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/Model200ResponseTests.cs @@ -0,0 +1,78 @@ +/* + * 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.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing Model200Response + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class Model200ResponseTests : IDisposable + { + // TODO uncomment below to declare an instance variable for Model200Response + //private Model200Response instance; + + public Model200ResponseTests() + { + // TODO uncomment below to create an instance of Model200Response + //instance = new Model200Response(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of Model200Response + /// + [Fact] + public void Model200ResponseInstanceTest() + { + // TODO uncomment below to test "IsType" Model200Response + //Assert.IsType(instance); + } + + + /// + /// Test the property 'Name' + /// + [Fact] + public void NameTest() + { + // TODO unit test for the property 'Name' + } + /// + /// Test the property 'Class' + /// + [Fact] + public void ClassTest() + { + // TODO unit test for the property 'Class' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/ModelClientTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/ModelClientTests.cs new file mode 100644 index 00000000000..24a9e263158 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/ModelClientTests.cs @@ -0,0 +1,70 @@ +/* + * 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.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing ModelClient + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class ModelClientTests : IDisposable + { + // TODO uncomment below to declare an instance variable for ModelClient + //private ModelClient instance; + + public ModelClientTests() + { + // TODO uncomment below to create an instance of ModelClient + //instance = new ModelClient(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of ModelClient + /// + [Fact] + public void ModelClientInstanceTest() + { + // TODO uncomment below to test "IsType" ModelClient + //Assert.IsType(instance); + } + + + /// + /// Test the property '_Client' + /// + [Fact] + public void _ClientTest() + { + // TODO unit test for the property '_Client' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/NameTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/NameTests.cs new file mode 100644 index 00000000000..c390049e66d --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/NameTests.cs @@ -0,0 +1,94 @@ +/* + * 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.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing Name + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class NameTests : IDisposable + { + // TODO uncomment below to declare an instance variable for Name + //private Name instance; + + public NameTests() + { + // TODO uncomment below to create an instance of Name + //instance = new Name(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of Name + /// + [Fact] + public void NameInstanceTest() + { + // TODO uncomment below to test "IsType" Name + //Assert.IsType(instance); + } + + + /// + /// Test the property '_Name' + /// + [Fact] + public void _NameTest() + { + // TODO unit test for the property '_Name' + } + /// + /// Test the property 'SnakeCase' + /// + [Fact] + public void SnakeCaseTest() + { + // TODO unit test for the property 'SnakeCase' + } + /// + /// Test the property 'Property' + /// + [Fact] + public void PropertyTest() + { + // TODO unit test for the property 'Property' + } + /// + /// Test the property '_123Number' + /// + [Fact] + public void _123NumberTest() + { + // TODO unit test for the property '_123Number' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/NullableClassTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/NullableClassTests.cs new file mode 100644 index 00000000000..8f00505612a --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/NullableClassTests.cs @@ -0,0 +1,158 @@ +/* + * 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.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing NullableClass + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class NullableClassTests : IDisposable + { + // TODO uncomment below to declare an instance variable for NullableClass + //private NullableClass instance; + + public NullableClassTests() + { + // TODO uncomment below to create an instance of NullableClass + //instance = new NullableClass(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of NullableClass + /// + [Fact] + public void NullableClassInstanceTest() + { + // TODO uncomment below to test "IsType" NullableClass + //Assert.IsType(instance); + } + + + /// + /// Test the property 'IntegerProp' + /// + [Fact] + public void IntegerPropTest() + { + // TODO unit test for the property 'IntegerProp' + } + /// + /// Test the property 'NumberProp' + /// + [Fact] + public void NumberPropTest() + { + // TODO unit test for the property 'NumberProp' + } + /// + /// Test the property 'BooleanProp' + /// + [Fact] + public void BooleanPropTest() + { + // TODO unit test for the property 'BooleanProp' + } + /// + /// Test the property 'StringProp' + /// + [Fact] + public void StringPropTest() + { + // TODO unit test for the property 'StringProp' + } + /// + /// Test the property 'DateProp' + /// + [Fact] + public void DatePropTest() + { + // TODO unit test for the property 'DateProp' + } + /// + /// Test the property 'DatetimeProp' + /// + [Fact] + public void DatetimePropTest() + { + // TODO unit test for the property 'DatetimeProp' + } + /// + /// Test the property 'ArrayNullableProp' + /// + [Fact] + public void ArrayNullablePropTest() + { + // TODO unit test for the property 'ArrayNullableProp' + } + /// + /// Test the property 'ArrayAndItemsNullableProp' + /// + [Fact] + public void ArrayAndItemsNullablePropTest() + { + // TODO unit test for the property 'ArrayAndItemsNullableProp' + } + /// + /// Test the property 'ArrayItemsNullable' + /// + [Fact] + public void ArrayItemsNullableTest() + { + // TODO unit test for the property 'ArrayItemsNullable' + } + /// + /// Test the property 'ObjectNullableProp' + /// + [Fact] + public void ObjectNullablePropTest() + { + // TODO unit test for the property 'ObjectNullableProp' + } + /// + /// Test the property 'ObjectAndItemsNullableProp' + /// + [Fact] + 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' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/NullableShapeTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/NullableShapeTests.cs new file mode 100644 index 00000000000..5662f91d6e6 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/NullableShapeTests.cs @@ -0,0 +1,78 @@ +/* + * 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.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing NullableShape + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class NullableShapeTests : IDisposable + { + // TODO uncomment below to declare an instance variable for NullableShape + //private NullableShape instance; + + public NullableShapeTests() + { + // TODO uncomment below to create an instance of NullableShape + //instance = new NullableShape(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of NullableShape + /// + [Fact] + public void NullableShapeInstanceTest() + { + // TODO uncomment below to test "IsType" NullableShape + //Assert.IsType(instance); + } + + + /// + /// Test the property 'ShapeType' + /// + [Fact] + public void ShapeTypeTest() + { + // TODO unit test for the property 'ShapeType' + } + /// + /// Test the property 'QuadrilateralType' + /// + [Fact] + public void QuadrilateralTypeTest() + { + // TODO unit test for the property 'QuadrilateralType' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/NumberOnlyTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/NumberOnlyTests.cs new file mode 100644 index 00000000000..3a06cb020b2 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/NumberOnlyTests.cs @@ -0,0 +1,70 @@ +/* + * 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.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing NumberOnly + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class NumberOnlyTests : IDisposable + { + // TODO uncomment below to declare an instance variable for NumberOnly + //private NumberOnly instance; + + public NumberOnlyTests() + { + // TODO uncomment below to create an instance of NumberOnly + //instance = new NumberOnly(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of NumberOnly + /// + [Fact] + public void NumberOnlyInstanceTest() + { + // TODO uncomment below to test "IsType" NumberOnly + //Assert.IsType(instance); + } + + + /// + /// Test the property 'JustNumber' + /// + [Fact] + public void JustNumberTest() + { + // TODO unit test for the property 'JustNumber' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/OrderTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/OrderTests.cs new file mode 100644 index 00000000000..cf5c561c547 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/OrderTests.cs @@ -0,0 +1,110 @@ +/* + * 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.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing Order + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class OrderTests : IDisposable + { + // TODO uncomment below to declare an instance variable for Order + //private Order instance; + + public OrderTests() + { + // TODO uncomment below to create an instance of Order + //instance = new Order(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of Order + /// + [Fact] + public void OrderInstanceTest() + { + // TODO uncomment below to test "IsType" Order + //Assert.IsType(instance); + } + + + /// + /// Test the property 'Id' + /// + [Fact] + public void IdTest() + { + // TODO unit test for the property 'Id' + } + /// + /// Test the property 'PetId' + /// + [Fact] + public void PetIdTest() + { + // TODO unit test for the property 'PetId' + } + /// + /// Test the property 'Quantity' + /// + [Fact] + public void QuantityTest() + { + // TODO unit test for the property 'Quantity' + } + /// + /// Test the property 'ShipDate' + /// + [Fact] + public void ShipDateTest() + { + // TODO unit test for the property 'ShipDate' + } + /// + /// Test the property 'Status' + /// + [Fact] + 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-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/OuterCompositeTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/OuterCompositeTests.cs new file mode 100644 index 00000000000..2efda0db59c --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/OuterCompositeTests.cs @@ -0,0 +1,86 @@ +/* + * 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.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing OuterComposite + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class OuterCompositeTests : IDisposable + { + // TODO uncomment below to declare an instance variable for OuterComposite + //private OuterComposite instance; + + public OuterCompositeTests() + { + // TODO uncomment below to create an instance of OuterComposite + //instance = new OuterComposite(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of OuterComposite + /// + [Fact] + public void OuterCompositeInstanceTest() + { + // TODO uncomment below to test "IsType" OuterComposite + //Assert.IsType(instance); + } + + + /// + /// Test the property 'MyNumber' + /// + [Fact] + public void MyNumberTest() + { + // TODO unit test for the property 'MyNumber' + } + /// + /// Test the property 'MyString' + /// + [Fact] + public void MyStringTest() + { + // TODO unit test for the property 'MyString' + } + /// + /// Test the property 'MyBoolean' + /// + [Fact] + public void MyBooleanTest() + { + // TODO unit test for the property 'MyBoolean' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/OuterEnumDefaultValueTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/OuterEnumDefaultValueTests.cs new file mode 100644 index 00000000000..986fff774c4 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/OuterEnumDefaultValueTests.cs @@ -0,0 +1,62 @@ +/* + * 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.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing OuterEnumDefaultValue + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class OuterEnumDefaultValueTests : IDisposable + { + // TODO uncomment below to declare an instance variable for OuterEnumDefaultValue + //private OuterEnumDefaultValue instance; + + public OuterEnumDefaultValueTests() + { + // TODO uncomment below to create an instance of OuterEnumDefaultValue + //instance = new OuterEnumDefaultValue(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of OuterEnumDefaultValue + /// + [Fact] + public void OuterEnumDefaultValueInstanceTest() + { + // TODO uncomment below to test "IsType" OuterEnumDefaultValue + //Assert.IsType(instance); + } + + + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/OuterEnumIntegerDefaultValueTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/OuterEnumIntegerDefaultValueTests.cs new file mode 100644 index 00000000000..015d5dab945 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/OuterEnumIntegerDefaultValueTests.cs @@ -0,0 +1,62 @@ +/* + * 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.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing OuterEnumIntegerDefaultValue + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class OuterEnumIntegerDefaultValueTests : IDisposable + { + // TODO uncomment below to declare an instance variable for OuterEnumIntegerDefaultValue + //private OuterEnumIntegerDefaultValue instance; + + public OuterEnumIntegerDefaultValueTests() + { + // TODO uncomment below to create an instance of OuterEnumIntegerDefaultValue + //instance = new OuterEnumIntegerDefaultValue(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of OuterEnumIntegerDefaultValue + /// + [Fact] + public void OuterEnumIntegerDefaultValueInstanceTest() + { + // TODO uncomment below to test "IsType" OuterEnumIntegerDefaultValue + //Assert.IsType(instance); + } + + + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/OuterEnumIntegerTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/OuterEnumIntegerTests.cs new file mode 100644 index 00000000000..385e899110a --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/OuterEnumIntegerTests.cs @@ -0,0 +1,62 @@ +/* + * 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.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing OuterEnumInteger + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class OuterEnumIntegerTests : IDisposable + { + // TODO uncomment below to declare an instance variable for OuterEnumInteger + //private OuterEnumInteger instance; + + public OuterEnumIntegerTests() + { + // TODO uncomment below to create an instance of OuterEnumInteger + //instance = new OuterEnumInteger(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of OuterEnumInteger + /// + [Fact] + public void OuterEnumIntegerInstanceTest() + { + // TODO uncomment below to test "IsType" OuterEnumInteger + //Assert.IsType(instance); + } + + + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/OuterEnumTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/OuterEnumTests.cs new file mode 100644 index 00000000000..f47304767b9 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/OuterEnumTests.cs @@ -0,0 +1,62 @@ +/* + * 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.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing OuterEnum + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class OuterEnumTests : IDisposable + { + // TODO uncomment below to declare an instance variable for OuterEnum + //private OuterEnum instance; + + public OuterEnumTests() + { + // TODO uncomment below to create an instance of OuterEnum + //instance = new OuterEnum(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of OuterEnum + /// + [Fact] + public void OuterEnumInstanceTest() + { + // TODO uncomment below to test "IsType" OuterEnum + //Assert.IsType(instance); + } + + + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/ParentPetTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/ParentPetTests.cs new file mode 100644 index 00000000000..1e17568ed33 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/ParentPetTests.cs @@ -0,0 +1,71 @@ +/* + * 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.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing ParentPet + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class ParentPetTests : IDisposable + { + // TODO uncomment below to declare an instance variable for ParentPet + //private ParentPet instance; + + public ParentPetTests() + { + // TODO uncomment below to create an instance of ParentPet + //instance = new ParentPet(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of ParentPet + /// + [Fact] + public void ParentPetInstanceTest() + { + // TODO uncomment below to test "IsType" ParentPet + //Assert.IsType(instance); + } + + /// + /// Test deserialize a ChildCat from type ParentPet + /// + [Fact] + public void ChildCatDeserializeFromParentPetTest() + { + // TODO uncomment below to test deserialize a ChildCat from type ParentPet + //Assert.IsType(JsonConvert.DeserializeObject(new ChildCat().ToJson())); + } + + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/PetTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/PetTests.cs new file mode 100644 index 00000000000..154e66f8dfc --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/PetTests.cs @@ -0,0 +1,110 @@ +/* + * 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.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing Pet + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class PetTests : IDisposable + { + // TODO uncomment below to declare an instance variable for Pet + //private Pet instance; + + public PetTests() + { + // TODO uncomment below to create an instance of Pet + //instance = new Pet(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of Pet + /// + [Fact] + public void PetInstanceTest() + { + // TODO uncomment below to test "IsType" Pet + //Assert.IsType(instance); + } + + + /// + /// Test the property 'Id' + /// + [Fact] + public void IdTest() + { + // TODO unit test for the property 'Id' + } + /// + /// Test the property 'Category' + /// + [Fact] + public void CategoryTest() + { + // TODO unit test for the property 'Category' + } + /// + /// Test the property 'Name' + /// + [Fact] + public void NameTest() + { + // TODO unit test for the property 'Name' + } + /// + /// Test the property 'PhotoUrls' + /// + [Fact] + public void PhotoUrlsTest() + { + // TODO unit test for the property 'PhotoUrls' + } + /// + /// Test the property 'Tags' + /// + [Fact] + public void TagsTest() + { + // TODO unit test for the property 'Tags' + } + /// + /// Test the property 'Status' + /// + [Fact] + public void StatusTest() + { + // TODO unit test for the property 'Status' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/PigTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/PigTests.cs new file mode 100644 index 00000000000..55cf2189046 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/PigTests.cs @@ -0,0 +1,70 @@ +/* + * 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.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing Pig + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class PigTests : IDisposable + { + // TODO uncomment below to declare an instance variable for Pig + //private Pig instance; + + public PigTests() + { + // TODO uncomment below to create an instance of Pig + //instance = new Pig(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of Pig + /// + [Fact] + public void PigInstanceTest() + { + // TODO uncomment below to test "IsType" Pig + //Assert.IsType(instance); + } + + + /// + /// Test the property 'ClassName' + /// + [Fact] + public void ClassNameTest() + { + // TODO unit test for the property 'ClassName' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/QuadrilateralInterfaceTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/QuadrilateralInterfaceTests.cs new file mode 100644 index 00000000000..6eef9f4c816 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/QuadrilateralInterfaceTests.cs @@ -0,0 +1,70 @@ +/* + * 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.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing QuadrilateralInterface + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class QuadrilateralInterfaceTests : IDisposable + { + // TODO uncomment below to declare an instance variable for QuadrilateralInterface + //private QuadrilateralInterface instance; + + public QuadrilateralInterfaceTests() + { + // TODO uncomment below to create an instance of QuadrilateralInterface + //instance = new QuadrilateralInterface(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of QuadrilateralInterface + /// + [Fact] + public void QuadrilateralInterfaceInstanceTest() + { + // TODO uncomment below to test "IsType" QuadrilateralInterface + //Assert.IsType(instance); + } + + + /// + /// Test the property 'QuadrilateralType' + /// + [Fact] + public void QuadrilateralTypeTest() + { + // TODO unit test for the property 'QuadrilateralType' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/QuadrilateralTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/QuadrilateralTests.cs new file mode 100644 index 00000000000..26826681a47 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/QuadrilateralTests.cs @@ -0,0 +1,78 @@ +/* + * 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.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing Quadrilateral + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class QuadrilateralTests : IDisposable + { + // TODO uncomment below to declare an instance variable for Quadrilateral + //private Quadrilateral instance; + + public QuadrilateralTests() + { + // TODO uncomment below to create an instance of Quadrilateral + //instance = new Quadrilateral(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of Quadrilateral + /// + [Fact] + public void QuadrilateralInstanceTest() + { + // TODO uncomment below to test "IsType" Quadrilateral + //Assert.IsType(instance); + } + + + /// + /// Test the property 'ShapeType' + /// + [Fact] + public void ShapeTypeTest() + { + // TODO unit test for the property 'ShapeType' + } + /// + /// Test the property 'QuadrilateralType' + /// + [Fact] + public void QuadrilateralTypeTest() + { + // TODO unit test for the property 'QuadrilateralType' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/ReadOnlyFirstTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/ReadOnlyFirstTests.cs new file mode 100644 index 00000000000..dc3d0fad54c --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/ReadOnlyFirstTests.cs @@ -0,0 +1,78 @@ +/* + * 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.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing ReadOnlyFirst + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class ReadOnlyFirstTests : IDisposable + { + // TODO uncomment below to declare an instance variable for ReadOnlyFirst + //private ReadOnlyFirst instance; + + public ReadOnlyFirstTests() + { + // TODO uncomment below to create an instance of ReadOnlyFirst + //instance = new ReadOnlyFirst(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of ReadOnlyFirst + /// + [Fact] + public void ReadOnlyFirstInstanceTest() + { + // TODO uncomment below to test "IsType" ReadOnlyFirst + //Assert.IsType(instance); + } + + + /// + /// Test the property 'Bar' + /// + [Fact] + public void BarTest() + { + // TODO unit test for the property 'Bar' + } + /// + /// Test the property 'Baz' + /// + [Fact] + public void BazTest() + { + // TODO unit test for the property 'Baz' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/ReturnTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/ReturnTests.cs new file mode 100644 index 00000000000..c8c1d6510d2 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/ReturnTests.cs @@ -0,0 +1,70 @@ +/* + * 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.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing Return + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class ReturnTests : IDisposable + { + // TODO uncomment below to declare an instance variable for Return + //private Return instance; + + public ReturnTests() + { + // TODO uncomment below to create an instance of Return + //instance = new Return(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of Return + /// + [Fact] + public void ReturnInstanceTest() + { + // TODO uncomment below to test "IsType" Return + //Assert.IsType(instance); + } + + + /// + /// Test the property '_Return' + /// + [Fact] + public void _ReturnTest() + { + // TODO unit test for the property '_Return' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/ScaleneTriangleTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/ScaleneTriangleTests.cs new file mode 100644 index 00000000000..04cb9f1ab6b --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/ScaleneTriangleTests.cs @@ -0,0 +1,78 @@ +/* + * 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.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing ScaleneTriangle + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class ScaleneTriangleTests : IDisposable + { + // TODO uncomment below to declare an instance variable for ScaleneTriangle + //private ScaleneTriangle instance; + + public ScaleneTriangleTests() + { + // TODO uncomment below to create an instance of ScaleneTriangle + //instance = new ScaleneTriangle(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of ScaleneTriangle + /// + [Fact] + public void ScaleneTriangleInstanceTest() + { + // TODO uncomment below to test "IsType" ScaleneTriangle + //Assert.IsType(instance); + } + + + /// + /// Test the property 'ShapeType' + /// + [Fact] + public void ShapeTypeTest() + { + // TODO unit test for the property 'ShapeType' + } + /// + /// Test the property 'TriangleType' + /// + [Fact] + public void TriangleTypeTest() + { + // TODO unit test for the property 'TriangleType' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/SerializeBasedOnInitialization.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/SerializeBasedOnInitialization.cs new file mode 100644 index 00000000000..5fdb80097d8 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/SerializeBasedOnInitialization.cs @@ -0,0 +1,52 @@ +using Org.OpenAPITools.Model; +using System; +using System.Collections.Generic; +using System.Text; +using Xunit; +namespace Org.OpenAPITools.Test.Model +{ + public class SerializeBasedOnInitialization + { + public SerializeBasedOnInitialization() + { + + } + + /// + /// Apple has two properties, here we serialize only origin property + /// + [Fact] + public void SerializeAppleOrigin() + { + Apple apple = new Apple(); + apple.Origin = "India"; + string expectedJson = "{\r\n \"origin\": \"India\"\r\n}"; + Assert.Equal(expectedJson, apple.ToJson()); + } + + /// + /// Apple has two properties, here we serialize only cultivar property + /// + [Fact] + public void SerializeAppleCultivate() + { + Apple apple = new Apple(); + apple.Cultivar = "Kashmiri"; + string expectedJson = "{\r\n \"cultivar\": \"Kashmiri\"\r\n}"; + Assert.Equal(expectedJson, apple.ToJson()); + } + + /// + /// Here we serialze all the properties of Apple that it origin and cultivar both. + /// + [Fact] + public void SerializeApple() + { + Apple apple = new Apple(); + apple.Origin = "India"; + apple.Cultivar = "Kashmiri"; + string expectedJson = "{\r\n \"cultivar\": \"Kashmiri\",\r\n \"origin\": \"India\"\r\n}"; + Assert.Equal(expectedJson, apple.ToJson()); + } + } +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/ShapeInterfaceTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/ShapeInterfaceTests.cs new file mode 100644 index 00000000000..7bd0bc86f96 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/ShapeInterfaceTests.cs @@ -0,0 +1,70 @@ +/* + * 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.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing ShapeInterface + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class ShapeInterfaceTests : IDisposable + { + // TODO uncomment below to declare an instance variable for ShapeInterface + //private ShapeInterface instance; + + public ShapeInterfaceTests() + { + // TODO uncomment below to create an instance of ShapeInterface + //instance = new ShapeInterface(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of ShapeInterface + /// + [Fact] + public void ShapeInterfaceInstanceTest() + { + // TODO uncomment below to test "IsType" ShapeInterface + //Assert.IsType(instance); + } + + + /// + /// Test the property 'ShapeType' + /// + [Fact] + public void ShapeTypeTest() + { + // TODO unit test for the property 'ShapeType' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/ShapeOrNullTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/ShapeOrNullTests.cs new file mode 100644 index 00000000000..d0af114157c --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/ShapeOrNullTests.cs @@ -0,0 +1,78 @@ +/* + * 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.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing ShapeOrNull + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class ShapeOrNullTests : IDisposable + { + // TODO uncomment below to declare an instance variable for ShapeOrNull + //private ShapeOrNull instance; + + public ShapeOrNullTests() + { + // TODO uncomment below to create an instance of ShapeOrNull + //instance = new ShapeOrNull(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of ShapeOrNull + /// + [Fact] + public void ShapeOrNullInstanceTest() + { + // TODO uncomment below to test "IsType" ShapeOrNull + //Assert.IsType(instance); + } + + + /// + /// Test the property 'ShapeType' + /// + [Fact] + public void ShapeTypeTest() + { + // TODO unit test for the property 'ShapeType' + } + /// + /// Test the property 'QuadrilateralType' + /// + [Fact] + public void QuadrilateralTypeTest() + { + // TODO unit test for the property 'QuadrilateralType' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/ShapeTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/ShapeTests.cs new file mode 100644 index 00000000000..b01bd531f85 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/ShapeTests.cs @@ -0,0 +1,78 @@ +/* + * 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.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing Shape + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class ShapeTests : IDisposable + { + // TODO uncomment below to declare an instance variable for Shape + //private Shape instance; + + public ShapeTests() + { + // TODO uncomment below to create an instance of Shape + //instance = new Shape(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of Shape + /// + [Fact] + public void ShapeInstanceTest() + { + // TODO uncomment below to test "IsType" Shape + //Assert.IsType(instance); + } + + + /// + /// Test the property 'ShapeType' + /// + [Fact] + public void ShapeTypeTest() + { + // TODO unit test for the property 'ShapeType' + } + /// + /// Test the property 'QuadrilateralType' + /// + [Fact] + public void QuadrilateralTypeTest() + { + // TODO unit test for the property 'QuadrilateralType' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/SimpleQuadrilateralTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/SimpleQuadrilateralTests.cs new file mode 100644 index 00000000000..6648e980928 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/SimpleQuadrilateralTests.cs @@ -0,0 +1,78 @@ +/* + * 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.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing SimpleQuadrilateral + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class SimpleQuadrilateralTests : IDisposable + { + // TODO uncomment below to declare an instance variable for SimpleQuadrilateral + //private SimpleQuadrilateral instance; + + public SimpleQuadrilateralTests() + { + // TODO uncomment below to create an instance of SimpleQuadrilateral + //instance = new SimpleQuadrilateral(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of SimpleQuadrilateral + /// + [Fact] + public void SimpleQuadrilateralInstanceTest() + { + // TODO uncomment below to test "IsType" SimpleQuadrilateral + //Assert.IsType(instance); + } + + + /// + /// Test the property 'ShapeType' + /// + [Fact] + public void ShapeTypeTest() + { + // TODO unit test for the property 'ShapeType' + } + /// + /// Test the property 'QuadrilateralType' + /// + [Fact] + public void QuadrilateralTypeTest() + { + // TODO unit test for the property 'QuadrilateralType' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/SpecialModelNameTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/SpecialModelNameTests.cs new file mode 100644 index 00000000000..0f0e1ff12a9 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/SpecialModelNameTests.cs @@ -0,0 +1,78 @@ +/* + * 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.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing SpecialModelName + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class SpecialModelNameTests : IDisposable + { + // TODO uncomment below to declare an instance variable for SpecialModelName + //private SpecialModelName instance; + + public SpecialModelNameTests() + { + // TODO uncomment below to create an instance of SpecialModelName + //instance = new SpecialModelName(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of SpecialModelName + /// + [Fact] + public void SpecialModelNameInstanceTest() + { + // TODO uncomment below to test "IsType" SpecialModelName + //Assert.IsType(instance); + } + + + /// + /// Test the property 'SpecialPropertyName' + /// + [Fact] + public void SpecialPropertyNameTest() + { + // TODO unit test for the property 'SpecialPropertyName' + } + /// + /// Test the property '_SpecialModelName' + /// + [Fact] + public void _SpecialModelNameTest() + { + // TODO unit test for the property '_SpecialModelName' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/TagTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/TagTests.cs new file mode 100644 index 00000000000..6d56232d0a7 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/TagTests.cs @@ -0,0 +1,78 @@ +/* + * 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.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing Tag + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class TagTests : IDisposable + { + // TODO uncomment below to declare an instance variable for Tag + //private Tag instance; + + public TagTests() + { + // TODO uncomment below to create an instance of Tag + //instance = new Tag(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of Tag + /// + [Fact] + public void TagInstanceTest() + { + // TODO uncomment below to test "IsType" Tag + //Assert.IsType(instance); + } + + + /// + /// Test the property 'Id' + /// + [Fact] + public void IdTest() + { + // TODO unit test for the property 'Id' + } + /// + /// Test the property 'Name' + /// + [Fact] + public void NameTest() + { + // TODO unit test for the property 'Name' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/TriangleInterfaceTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/TriangleInterfaceTests.cs new file mode 100644 index 00000000000..fba65470bee --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/TriangleInterfaceTests.cs @@ -0,0 +1,70 @@ +/* + * 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.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing TriangleInterface + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class TriangleInterfaceTests : IDisposable + { + // TODO uncomment below to declare an instance variable for TriangleInterface + //private TriangleInterface instance; + + public TriangleInterfaceTests() + { + // TODO uncomment below to create an instance of TriangleInterface + //instance = new TriangleInterface(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of TriangleInterface + /// + [Fact] + public void TriangleInterfaceInstanceTest() + { + // TODO uncomment below to test "IsType" TriangleInterface + //Assert.IsType(instance); + } + + + /// + /// Test the property 'TriangleType' + /// + [Fact] + public void TriangleTypeTest() + { + // TODO unit test for the property 'TriangleType' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/TriangleTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/TriangleTests.cs new file mode 100644 index 00000000000..bdaab0b4796 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/TriangleTests.cs @@ -0,0 +1,78 @@ +/* + * 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.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing Triangle + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class TriangleTests : IDisposable + { + // TODO uncomment below to declare an instance variable for Triangle + //private Triangle instance; + + public TriangleTests() + { + // TODO uncomment below to create an instance of Triangle + //instance = new Triangle(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of Triangle + /// + [Fact] + public void TriangleInstanceTest() + { + // TODO uncomment below to test "IsType" Triangle + //Assert.IsType(instance); + } + + + /// + /// Test the property 'ShapeType' + /// + [Fact] + public void ShapeTypeTest() + { + // TODO unit test for the property 'ShapeType' + } + /// + /// Test the property 'TriangleType' + /// + [Fact] + public void TriangleTypeTest() + { + // TODO unit test for the property 'TriangleType' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/UserTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/UserTests.cs new file mode 100644 index 00000000000..a7b095e4c28 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/UserTests.cs @@ -0,0 +1,158 @@ +/* + * 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.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing User + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class UserTests : IDisposable + { + // TODO uncomment below to declare an instance variable for User + //private User instance; + + public UserTests() + { + // TODO uncomment below to create an instance of User + //instance = new User(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of User + /// + [Fact] + public void UserInstanceTest() + { + // TODO uncomment below to test "IsType" User + //Assert.IsType(instance); + } + + + /// + /// Test the property 'Id' + /// + [Fact] + public void IdTest() + { + // TODO unit test for the property 'Id' + } + /// + /// Test the property 'Username' + /// + [Fact] + public void UsernameTest() + { + // TODO unit test for the property 'Username' + } + /// + /// Test the property 'FirstName' + /// + [Fact] + public void FirstNameTest() + { + // TODO unit test for the property 'FirstName' + } + /// + /// Test the property 'LastName' + /// + [Fact] + public void LastNameTest() + { + // TODO unit test for the property 'LastName' + } + /// + /// Test the property 'Email' + /// + [Fact] + public void EmailTest() + { + // TODO unit test for the property 'Email' + } + /// + /// Test the property 'Password' + /// + [Fact] + public void PasswordTest() + { + // TODO unit test for the property 'Password' + } + /// + /// Test the property 'Phone' + /// + [Fact] + public void PhoneTest() + { + // TODO unit test for the property 'Phone' + } + /// + /// Test the property 'UserStatus' + /// + [Fact] + public void UserStatusTest() + { + // TODO unit test for the property 'UserStatus' + } + /// + /// Test the property 'ObjectWithNoDeclaredProps' + /// + [Fact] + 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 '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' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/WhaleTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/WhaleTests.cs new file mode 100644 index 00000000000..09610791943 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/WhaleTests.cs @@ -0,0 +1,86 @@ +/* + * 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.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing Whale + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class WhaleTests : IDisposable + { + // TODO uncomment below to declare an instance variable for Whale + //private Whale instance; + + public WhaleTests() + { + // TODO uncomment below to create an instance of Whale + //instance = new Whale(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of Whale + /// + [Fact] + public void WhaleInstanceTest() + { + // TODO uncomment below to test "IsType" Whale + //Assert.IsType(instance); + } + + + /// + /// Test the property 'HasBaleen' + /// + [Fact] + public void HasBaleenTest() + { + // TODO unit test for the property 'HasBaleen' + } + /// + /// Test the property 'HasTeeth' + /// + [Fact] + public void HasTeethTest() + { + // TODO unit test for the property 'HasTeeth' + } + /// + /// Test the property 'ClassName' + /// + [Fact] + public void ClassNameTest() + { + // TODO unit test for the property 'ClassName' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/ZebraTests.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/ZebraTests.cs new file mode 100644 index 00000000000..f44e9213140 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/ZebraTests.cs @@ -0,0 +1,78 @@ +/* + * 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.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing Zebra + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class ZebraTests : IDisposable + { + // TODO uncomment below to declare an instance variable for Zebra + //private Zebra instance; + + public ZebraTests() + { + // TODO uncomment below to create an instance of Zebra + //instance = new Zebra(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of Zebra + /// + [Fact] + public void ZebraInstanceTest() + { + // TODO uncomment below to test "IsType" Zebra + //Assert.IsType(instance); + } + + + /// + /// Test the property 'Type' + /// + [Fact] + public void TypeTest() + { + // TODO unit test for the property 'Type' + } + /// + /// Test the property 'ClassName' + /// + [Fact] + public void ClassNameTest() + { + // TODO unit test for the property 'ClassName' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj new file mode 100644 index 00000000000..d58f7e14d8d --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj @@ -0,0 +1,20 @@ + + + + Org.OpenAPITools.Test + Org.OpenAPITools.Test + netcoreapp2.0 + false + + + + + + + + + + + + + diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Api/AnotherFakeApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Api/AnotherFakeApi.cs new file mode 100644 index 00000000000..ad48306e00c --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Api/AnotherFakeApi.cs @@ -0,0 +1,320 @@ +/* + * 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.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 IAnotherFakeApiSync : IApiAccessor + { + #region Synchronous Operations + /// + /// To test special tags + /// + /// + /// To test special tags and operation ID starting with number + /// + /// Thrown when fails to make API call + /// client model + /// ModelClient + ModelClient Call123TestSpecialTags(ModelClient modelClient); + + /// + /// To test special tags + /// + /// + /// To test special tags and operation ID starting with number + /// + /// Thrown when fails to make API call + /// client model + /// ApiResponse of ModelClient + ApiResponse Call123TestSpecialTagsWithHttpInfo(ModelClient modelClient); + #endregion Synchronous Operations + } + + /// + /// Represents a collection of functions to interact with the API endpoints + /// + public interface IAnotherFakeApiAsync : IApiAccessor + { + #region Asynchronous Operations + /// + /// To test special tags + /// + /// + /// To test special tags and operation ID starting with number + /// + /// Thrown when fails to make API call + /// client model + /// Cancellation Token to cancel the request. + /// Task of ModelClient + System.Threading.Tasks.Task Call123TestSpecialTagsAsync(ModelClient modelClient, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// To test special tags + /// + /// + /// To test special tags and operation ID starting with number + /// + /// Thrown when fails to make API call + /// client model + /// Cancellation Token to cancel the request. + /// Task of ApiResponse (ModelClient) + System.Threading.Tasks.Task> Call123TestSpecialTagsWithHttpInfoAsync(ModelClient modelClient, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + #endregion Asynchronous Operations + } + + /// + /// Represents a collection of functions to interact with the API endpoints + /// + public interface IAnotherFakeApi : IAnotherFakeApiSync, IAnotherFakeApiAsync + { + + } + + /// + /// Represents a collection of functions to interact with the API endpoints + /// + public partial class AnotherFakeApi : IAnotherFakeApi + { + private Org.OpenAPITools.Client.ExceptionFactory _exceptionFactory = (name, response) => null; + + /// + /// Initializes a new instance of the class. + /// + /// + public AnotherFakeApi() : this((string)null) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// + public AnotherFakeApi(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 AnotherFakeApi(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 AnotherFakeApi(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; } + } + + /// + /// To test special tags To test special tags and operation ID starting with number + /// + /// Thrown when fails to make API call + /// client model + /// ModelClient + public ModelClient Call123TestSpecialTags(ModelClient modelClient) + { + Org.OpenAPITools.Client.ApiResponse localVarResponse = Call123TestSpecialTagsWithHttpInfo(modelClient); + return localVarResponse.Data; + } + + /// + /// To test special tags To test special tags and operation ID starting with number + /// + /// Thrown when fails to make API call + /// client model + /// ApiResponse of ModelClient + public Org.OpenAPITools.Client.ApiResponse Call123TestSpecialTagsWithHttpInfo(ModelClient modelClient) + { + // verify the required parameter 'modelClient' is set + if (modelClient == null) + throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'modelClient' when calling AnotherFakeApi->Call123TestSpecialTags"); + + 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 = modelClient; + + + // make the HTTP request + var localVarResponse = this.Client.Patch("/another-fake/dummy", localVarRequestOptions, this.Configuration); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("Call123TestSpecialTags", localVarResponse); + if (_exception != null) throw _exception; + } + + return localVarResponse; + } + + /// + /// To test special tags To test special tags and operation ID starting with number + /// + /// Thrown when fails to make API call + /// client model + /// Cancellation Token to cancel the request. + /// Task of ModelClient + public async System.Threading.Tasks.Task Call123TestSpecialTagsAsync(ModelClient modelClient, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + Org.OpenAPITools.Client.ApiResponse localVarResponse = await Call123TestSpecialTagsWithHttpInfoAsync(modelClient, cancellationToken).ConfigureAwait(false); + return localVarResponse.Data; + } + + /// + /// To test special tags To test special tags and operation ID starting with number + /// + /// Thrown when fails to make API call + /// client model + /// Cancellation Token to cancel the request. + /// Task of ApiResponse (ModelClient) + public async System.Threading.Tasks.Task> Call123TestSpecialTagsWithHttpInfoAsync(ModelClient modelClient, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + // verify the required parameter 'modelClient' is set + if (modelClient == null) + throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'modelClient' when calling AnotherFakeApi->Call123TestSpecialTags"); + + + 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 = modelClient; + + + // make the HTTP request + + var localVarResponse = await this.AsynchronousClient.PatchAsync("/another-fake/dummy", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("Call123TestSpecialTags", localVarResponse); + if (_exception != null) throw _exception; + } + + return localVarResponse; + } + + } +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Api/DefaultApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Api/DefaultApi.cs new file mode 100644 index 00000000000..8844aca4ab7 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Api/DefaultApi.cs @@ -0,0 +1,297 @@ +/* + * 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.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 + /// InlineResponseDefault + InlineResponseDefault FooGet(); + + /// + /// + /// + /// + /// + /// + /// Thrown when fails to make API call + /// ApiResponse of InlineResponseDefault + ApiResponse FooGetWithHttpInfo(); + #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 + /// Cancellation Token to cancel the request. + /// Task of InlineResponseDefault + System.Threading.Tasks.Task FooGetAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// + /// + /// + /// + /// + /// Thrown when fails to make API call + /// Cancellation Token to cancel the request. + /// Task of ApiResponse (InlineResponseDefault) + System.Threading.Tasks.Task> FooGetWithHttpInfoAsync(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 + /// InlineResponseDefault + public InlineResponseDefault FooGet() + { + Org.OpenAPITools.Client.ApiResponse localVarResponse = FooGetWithHttpInfo(); + return localVarResponse.Data; + } + + /// + /// + /// + /// Thrown when fails to make API call + /// ApiResponse of InlineResponseDefault + public Org.OpenAPITools.Client.ApiResponse FooGetWithHttpInfo() + { + 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); + + + + // make the HTTP request + var localVarResponse = this.Client.Get("/foo", localVarRequestOptions, this.Configuration); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("FooGet", localVarResponse); + if (_exception != null) throw _exception; + } + + return localVarResponse; + } + + /// + /// + /// + /// Thrown when fails to make API call + /// Cancellation Token to cancel the request. + /// Task of InlineResponseDefault + public async System.Threading.Tasks.Task FooGetAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + Org.OpenAPITools.Client.ApiResponse localVarResponse = await FooGetWithHttpInfoAsync(cancellationToken).ConfigureAwait(false); + return localVarResponse.Data; + } + + /// + /// + /// + /// Thrown when fails to make API call + /// Cancellation Token to cancel the request. + /// Task of ApiResponse (InlineResponseDefault) + public async System.Threading.Tasks.Task> FooGetWithHttpInfoAsync(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); + + + + // make the HTTP request + + var localVarResponse = await this.AsynchronousClient.GetAsync("/foo", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("FooGet", localVarResponse); + if (_exception != null) throw _exception; + } + + return localVarResponse; + } + + } +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Api/FakeApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Api/FakeApi.cs new file mode 100644 index 00000000000..fe862283f1e --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Api/FakeApi.cs @@ -0,0 +1,2951 @@ +/* + * 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.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 IFakeApiSync : IApiAccessor + { + #region Synchronous Operations + /// + /// Health check endpoint + /// + /// Thrown when fails to make API call + /// HealthCheckResult + HealthCheckResult FakeHealthGet(); + + /// + /// Health check endpoint + /// + /// + /// + /// + /// Thrown when fails to make API call + /// ApiResponse of HealthCheckResult + ApiResponse FakeHealthGetWithHttpInfo(); + /// + /// + /// + /// + /// Test serialization of outer boolean types + /// + /// Thrown when fails to make API call + /// Input boolean as post body (optional) + /// bool + bool FakeOuterBooleanSerialize(bool? body = default(bool?)); + + /// + /// + /// + /// + /// Test serialization of outer boolean types + /// + /// Thrown when fails to make API call + /// Input boolean as post body (optional) + /// ApiResponse of bool + ApiResponse FakeOuterBooleanSerializeWithHttpInfo(bool? body = default(bool?)); + /// + /// + /// + /// + /// Test serialization of object with outer number type + /// + /// Thrown when fails to make API call + /// Input composite as post body (optional) + /// OuterComposite + OuterComposite FakeOuterCompositeSerialize(OuterComposite outerComposite = default(OuterComposite)); + + /// + /// + /// + /// + /// Test serialization of object with outer number type + /// + /// Thrown when fails to make API call + /// Input composite as post body (optional) + /// ApiResponse of OuterComposite + ApiResponse FakeOuterCompositeSerializeWithHttpInfo(OuterComposite outerComposite = default(OuterComposite)); + /// + /// + /// + /// + /// Test serialization of outer number types + /// + /// Thrown when fails to make API call + /// Input number as post body (optional) + /// decimal + decimal FakeOuterNumberSerialize(decimal? body = default(decimal?)); + + /// + /// + /// + /// + /// Test serialization of outer number types + /// + /// Thrown when fails to make API call + /// Input number as post body (optional) + /// ApiResponse of decimal + ApiResponse FakeOuterNumberSerializeWithHttpInfo(decimal? body = default(decimal?)); + /// + /// + /// + /// + /// Test serialization of outer string types + /// + /// Thrown when fails to make API call + /// Input string as post body (optional) + /// string + string FakeOuterStringSerialize(string body = default(string)); + + /// + /// + /// + /// + /// Test serialization of outer string types + /// + /// Thrown when fails to make API call + /// Input string as post body (optional) + /// ApiResponse of string + ApiResponse FakeOuterStringSerializeWithHttpInfo(string body = default(string)); + /// + /// Array of Enums + /// + /// Thrown when fails to make API call + /// List<OuterEnum> + List GetArrayOfEnums(); + + /// + /// Array of Enums + /// + /// + /// + /// + /// Thrown when fails to make API call + /// ApiResponse of List<OuterEnum> + ApiResponse> GetArrayOfEnumsWithHttpInfo(); + /// + /// + /// + /// + /// For this test, the body for this request much reference a schema named `File`. + /// + /// Thrown when fails to make API call + /// + /// + void TestBodyWithFileSchema(FileSchemaTestClass fileSchemaTestClass); + + /// + /// + /// + /// + /// For this test, the body for this request much reference a schema named `File`. + /// + /// Thrown when fails to make API call + /// + /// ApiResponse of Object(void) + ApiResponse TestBodyWithFileSchemaWithHttpInfo(FileSchemaTestClass fileSchemaTestClass); + /// + /// + /// + /// Thrown when fails to make API call + /// + /// + /// + void TestBodyWithQueryParams(string query, User user); + + /// + /// + /// + /// + /// + /// + /// Thrown when fails to make API call + /// + /// + /// ApiResponse of Object(void) + ApiResponse TestBodyWithQueryParamsWithHttpInfo(string query, User user); + /// + /// To test \"client\" model + /// + /// + /// To test \"client\" model + /// + /// Thrown when fails to make API call + /// client model + /// ModelClient + ModelClient TestClientModel(ModelClient modelClient); + + /// + /// To test \"client\" model + /// + /// + /// To test \"client\" model + /// + /// Thrown when fails to make API call + /// client model + /// ApiResponse of ModelClient + ApiResponse TestClientModelWithHttpInfo(ModelClient modelClient); + /// + /// Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + /// + /// + /// Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + /// + /// Thrown when fails to make API call + /// None + /// None + /// None + /// None + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional, default to "2010-02-01T10:20:10.111110+01:00") + /// None (optional) + /// None (optional) + /// + void TestEndpointParameters(decimal number, double _double, string patternWithoutDelimiter, byte[] _byte, int? integer = default(int?), int? int32 = default(int?), long? int64 = default(long?), float? _float = default(float?), string _string = 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)); + + /// + /// Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + /// + /// + /// Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + /// + /// Thrown when fails to make API call + /// None + /// None + /// None + /// None + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional, default to "2010-02-01T10:20:10.111110+01:00") + /// None (optional) + /// None (optional) + /// ApiResponse of Object(void) + ApiResponse TestEndpointParametersWithHttpInfo(decimal number, double _double, string patternWithoutDelimiter, byte[] _byte, int? integer = default(int?), int? int32 = default(int?), long? int64 = default(long?), float? _float = default(float?), string _string = 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)); + /// + /// To test enum parameters + /// + /// + /// To test enum parameters + /// + /// Thrown when fails to make API call + /// Header parameter enum test (string array) (optional) + /// Header parameter enum test (string) (optional, default to -efg) + /// Query parameter enum test (string array) (optional) + /// Query parameter enum test (string) (optional, default to -efg) + /// Query parameter enum test (double) (optional) + /// Query parameter enum test (double) (optional) + /// Form parameter enum test (string array) (optional, default to $) + /// Form parameter enum test (string) (optional, default to -efg) + /// + void TestEnumParameters(List enumHeaderStringArray = default(List), string enumHeaderString = default(string), List enumQueryStringArray = default(List), string enumQueryString = default(string), int? enumQueryInteger = default(int?), double? enumQueryDouble = default(double?), List enumFormStringArray = default(List), string enumFormString = default(string)); + + /// + /// To test enum parameters + /// + /// + /// To test enum parameters + /// + /// Thrown when fails to make API call + /// Header parameter enum test (string array) (optional) + /// Header parameter enum test (string) (optional, default to -efg) + /// Query parameter enum test (string array) (optional) + /// Query parameter enum test (string) (optional, default to -efg) + /// Query parameter enum test (double) (optional) + /// Query parameter enum test (double) (optional) + /// Form parameter enum test (string array) (optional, default to $) + /// Form parameter enum test (string) (optional, default to -efg) + /// ApiResponse of Object(void) + ApiResponse TestEnumParametersWithHttpInfo(List enumHeaderStringArray = default(List), string enumHeaderString = default(string), List enumQueryStringArray = default(List), string enumQueryString = default(string), int? enumQueryInteger = default(int?), double? enumQueryDouble = default(double?), List enumFormStringArray = default(List), string enumFormString = default(string)); + /// + /// Fake endpoint to test group parameters (optional) + /// + /// + /// Fake endpoint to test group parameters (optional) + /// + /// Thrown when fails to make API call + /// Required String in group parameters + /// Required Boolean in group parameters + /// Required Integer in group parameters + /// String in group parameters (optional) + /// Boolean in group parameters (optional) + /// Integer in group parameters (optional) + /// + void TestGroupParameters(int requiredStringGroup, bool requiredBooleanGroup, long requiredInt64Group, int? stringGroup = default(int?), bool? booleanGroup = default(bool?), long? int64Group = default(long?)); + + /// + /// Fake endpoint to test group parameters (optional) + /// + /// + /// Fake endpoint to test group parameters (optional) + /// + /// Thrown when fails to make API call + /// Required String in group parameters + /// Required Boolean in group parameters + /// Required Integer in group parameters + /// String in group parameters (optional) + /// Boolean in group parameters (optional) + /// Integer in group parameters (optional) + /// ApiResponse of Object(void) + ApiResponse TestGroupParametersWithHttpInfo(int requiredStringGroup, bool requiredBooleanGroup, long requiredInt64Group, int? stringGroup = default(int?), bool? booleanGroup = default(bool?), long? int64Group = default(long?)); + /// + /// test inline additionalProperties + /// + /// Thrown when fails to make API call + /// request body + /// + void TestInlineAdditionalProperties(Dictionary requestBody); + + /// + /// test inline additionalProperties + /// + /// + /// + /// + /// Thrown when fails to make API call + /// request body + /// ApiResponse of Object(void) + ApiResponse TestInlineAdditionalPropertiesWithHttpInfo(Dictionary requestBody); + /// + /// test json serialization of form data + /// + /// Thrown when fails to make API call + /// field1 + /// field2 + /// + void TestJsonFormData(string param, string param2); + + /// + /// test json serialization of form data + /// + /// + /// + /// + /// Thrown when fails to make API call + /// field1 + /// field2 + /// ApiResponse of Object(void) + ApiResponse TestJsonFormDataWithHttpInfo(string param, string param2); + /// + /// + /// + /// + /// To test the collection format in query parameters + /// + /// Thrown when fails to make API call + /// + /// + /// + /// + /// + /// + void TestQueryParameterCollectionFormat(List pipe, List ioutil, List http, List url, List context); + + /// + /// + /// + /// + /// To test the collection format in query parameters + /// + /// Thrown when fails to make API call + /// + /// + /// + /// + /// + /// ApiResponse of Object(void) + ApiResponse TestQueryParameterCollectionFormatWithHttpInfo(List pipe, List ioutil, List http, List url, List context); + #endregion Synchronous Operations + } + + /// + /// Represents a collection of functions to interact with the API endpoints + /// + public interface IFakeApiAsync : IApiAccessor + { + #region Asynchronous Operations + /// + /// Health check endpoint + /// + /// + /// + /// + /// Thrown when fails to make API call + /// Cancellation Token to cancel the request. + /// Task of HealthCheckResult + System.Threading.Tasks.Task FakeHealthGetAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// Health check endpoint + /// + /// + /// + /// + /// Thrown when fails to make API call + /// Cancellation Token to cancel the request. + /// Task of ApiResponse (HealthCheckResult) + System.Threading.Tasks.Task> FakeHealthGetWithHttpInfoAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + /// + /// + /// + /// + /// Test serialization of outer boolean types + /// + /// Thrown when fails to make API call + /// Input boolean as post body (optional) + /// Cancellation Token to cancel the request. + /// Task of bool + System.Threading.Tasks.Task FakeOuterBooleanSerializeAsync(bool? body = default(bool?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// + /// + /// + /// Test serialization of outer boolean types + /// + /// Thrown when fails to make API call + /// Input boolean as post body (optional) + /// Cancellation Token to cancel the request. + /// Task of ApiResponse (bool) + System.Threading.Tasks.Task> FakeOuterBooleanSerializeWithHttpInfoAsync(bool? body = default(bool?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + /// + /// + /// + /// + /// Test serialization of object with outer number type + /// + /// Thrown when fails to make API call + /// Input composite as post body (optional) + /// Cancellation Token to cancel the request. + /// Task of OuterComposite + System.Threading.Tasks.Task FakeOuterCompositeSerializeAsync(OuterComposite outerComposite = default(OuterComposite), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// + /// + /// + /// Test serialization of object with outer number type + /// + /// Thrown when fails to make API call + /// Input composite as post body (optional) + /// Cancellation Token to cancel the request. + /// Task of ApiResponse (OuterComposite) + System.Threading.Tasks.Task> FakeOuterCompositeSerializeWithHttpInfoAsync(OuterComposite outerComposite = default(OuterComposite), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + /// + /// + /// + /// + /// Test serialization of outer number types + /// + /// Thrown when fails to make API call + /// Input number as post body (optional) + /// Cancellation Token to cancel the request. + /// Task of decimal + System.Threading.Tasks.Task FakeOuterNumberSerializeAsync(decimal? body = default(decimal?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// + /// + /// + /// Test serialization of outer number types + /// + /// Thrown when fails to make API call + /// Input number as post body (optional) + /// Cancellation Token to cancel the request. + /// Task of ApiResponse (decimal) + System.Threading.Tasks.Task> FakeOuterNumberSerializeWithHttpInfoAsync(decimal? body = default(decimal?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + /// + /// + /// + /// + /// Test serialization of outer string types + /// + /// Thrown when fails to make API call + /// Input string as post body (optional) + /// Cancellation Token to cancel the request. + /// Task of string + System.Threading.Tasks.Task FakeOuterStringSerializeAsync(string body = default(string), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// + /// + /// + /// Test serialization of outer string types + /// + /// Thrown when fails to make API call + /// Input string as post body (optional) + /// Cancellation Token to cancel the request. + /// Task of ApiResponse (string) + System.Threading.Tasks.Task> FakeOuterStringSerializeWithHttpInfoAsync(string body = default(string), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + /// + /// Array of Enums + /// + /// + /// + /// + /// Thrown when fails to make API call + /// Cancellation Token to cancel the request. + /// Task of List<OuterEnum> + System.Threading.Tasks.Task> GetArrayOfEnumsAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// Array of Enums + /// + /// + /// + /// + /// Thrown when fails to make API call + /// Cancellation Token to cancel the request. + /// Task of ApiResponse (List<OuterEnum>) + System.Threading.Tasks.Task>> GetArrayOfEnumsWithHttpInfoAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + /// + /// + /// + /// + /// For this test, the body for this request much reference a schema named `File`. + /// + /// Thrown when fails to make API call + /// + /// Cancellation Token to cancel the request. + /// Task of void + System.Threading.Tasks.Task TestBodyWithFileSchemaAsync(FileSchemaTestClass fileSchemaTestClass, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// + /// + /// + /// For this test, the body for this request much reference a schema named `File`. + /// + /// Thrown when fails to make API call + /// + /// Cancellation Token to cancel the request. + /// Task of ApiResponse + System.Threading.Tasks.Task> TestBodyWithFileSchemaWithHttpInfoAsync(FileSchemaTestClass fileSchemaTestClass, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + /// + /// + /// + /// + /// + /// + /// Thrown when fails to make API call + /// + /// + /// Cancellation Token to cancel the request. + /// Task of void + System.Threading.Tasks.Task TestBodyWithQueryParamsAsync(string query, User user, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// + /// + /// + /// + /// + /// Thrown when fails to make API call + /// + /// + /// Cancellation Token to cancel the request. + /// Task of ApiResponse + System.Threading.Tasks.Task> TestBodyWithQueryParamsWithHttpInfoAsync(string query, User user, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + /// + /// To test \"client\" model + /// + /// + /// To test \"client\" model + /// + /// Thrown when fails to make API call + /// client model + /// Cancellation Token to cancel the request. + /// Task of ModelClient + System.Threading.Tasks.Task TestClientModelAsync(ModelClient modelClient, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// To test \"client\" model + /// + /// + /// To test \"client\" model + /// + /// Thrown when fails to make API call + /// client model + /// Cancellation Token to cancel the request. + /// Task of ApiResponse (ModelClient) + System.Threading.Tasks.Task> TestClientModelWithHttpInfoAsync(ModelClient modelClient, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + /// + /// Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + /// + /// + /// Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + /// + /// Thrown when fails to make API call + /// None + /// None + /// None + /// None + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional, default to "2010-02-01T10:20:10.111110+01:00") + /// None (optional) + /// None (optional) + /// Cancellation Token to cancel the request. + /// Task of void + System.Threading.Tasks.Task TestEndpointParametersAsync(decimal number, double _double, string patternWithoutDelimiter, byte[] _byte, int? integer = default(int?), int? int32 = default(int?), long? int64 = default(long?), float? _float = default(float?), string _string = 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), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + /// + /// + /// Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + /// + /// Thrown when fails to make API call + /// None + /// None + /// None + /// None + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional, default to "2010-02-01T10:20:10.111110+01:00") + /// None (optional) + /// None (optional) + /// Cancellation Token to cancel the request. + /// Task of ApiResponse + System.Threading.Tasks.Task> TestEndpointParametersWithHttpInfoAsync(decimal number, double _double, string patternWithoutDelimiter, byte[] _byte, int? integer = default(int?), int? int32 = default(int?), long? int64 = default(long?), float? _float = default(float?), string _string = 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), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + /// + /// To test enum parameters + /// + /// + /// To test enum parameters + /// + /// Thrown when fails to make API call + /// Header parameter enum test (string array) (optional) + /// Header parameter enum test (string) (optional, default to -efg) + /// Query parameter enum test (string array) (optional) + /// Query parameter enum test (string) (optional, default to -efg) + /// Query parameter enum test (double) (optional) + /// Query parameter enum test (double) (optional) + /// Form parameter enum test (string array) (optional, default to $) + /// Form parameter enum test (string) (optional, default to -efg) + /// Cancellation Token to cancel the request. + /// Task of void + System.Threading.Tasks.Task TestEnumParametersAsync(List enumHeaderStringArray = default(List), string enumHeaderString = default(string), List enumQueryStringArray = default(List), string enumQueryString = default(string), int? enumQueryInteger = default(int?), double? enumQueryDouble = default(double?), List enumFormStringArray = default(List), string enumFormString = default(string), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// To test enum parameters + /// + /// + /// To test enum parameters + /// + /// Thrown when fails to make API call + /// Header parameter enum test (string array) (optional) + /// Header parameter enum test (string) (optional, default to -efg) + /// Query parameter enum test (string array) (optional) + /// Query parameter enum test (string) (optional, default to -efg) + /// Query parameter enum test (double) (optional) + /// Query parameter enum test (double) (optional) + /// Form parameter enum test (string array) (optional, default to $) + /// Form parameter enum test (string) (optional, default to -efg) + /// Cancellation Token to cancel the request. + /// Task of ApiResponse + System.Threading.Tasks.Task> TestEnumParametersWithHttpInfoAsync(List enumHeaderStringArray = default(List), string enumHeaderString = default(string), List enumQueryStringArray = default(List), string enumQueryString = default(string), int? enumQueryInteger = default(int?), double? enumQueryDouble = default(double?), List enumFormStringArray = default(List), string enumFormString = default(string), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + /// + /// Fake endpoint to test group parameters (optional) + /// + /// + /// Fake endpoint to test group parameters (optional) + /// + /// Thrown when fails to make API call + /// Required String in group parameters + /// Required Boolean in group parameters + /// Required Integer in group parameters + /// String in group parameters (optional) + /// Boolean in group parameters (optional) + /// Integer in group parameters (optional) + /// Cancellation Token to cancel the request. + /// Task of void + System.Threading.Tasks.Task TestGroupParametersAsync(int requiredStringGroup, bool requiredBooleanGroup, long requiredInt64Group, int? stringGroup = default(int?), bool? booleanGroup = default(bool?), long? int64Group = default(long?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// Fake endpoint to test group parameters (optional) + /// + /// + /// Fake endpoint to test group parameters (optional) + /// + /// Thrown when fails to make API call + /// Required String in group parameters + /// Required Boolean in group parameters + /// Required Integer in group parameters + /// String in group parameters (optional) + /// Boolean in group parameters (optional) + /// Integer in group parameters (optional) + /// Cancellation Token to cancel the request. + /// Task of ApiResponse + System.Threading.Tasks.Task> TestGroupParametersWithHttpInfoAsync(int requiredStringGroup, bool requiredBooleanGroup, long requiredInt64Group, int? stringGroup = default(int?), bool? booleanGroup = default(bool?), long? int64Group = default(long?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + /// + /// test inline additionalProperties + /// + /// + /// + /// + /// Thrown when fails to make API call + /// request body + /// Cancellation Token to cancel the request. + /// Task of void + System.Threading.Tasks.Task TestInlineAdditionalPropertiesAsync(Dictionary requestBody, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// test inline additionalProperties + /// + /// + /// + /// + /// Thrown when fails to make API call + /// request body + /// Cancellation Token to cancel the request. + /// Task of ApiResponse + System.Threading.Tasks.Task> TestInlineAdditionalPropertiesWithHttpInfoAsync(Dictionary requestBody, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + /// + /// test json serialization of form data + /// + /// + /// + /// + /// Thrown when fails to make API call + /// field1 + /// field2 + /// Cancellation Token to cancel the request. + /// Task of void + System.Threading.Tasks.Task TestJsonFormDataAsync(string param, string param2, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// test json serialization of form data + /// + /// + /// + /// + /// Thrown when fails to make API call + /// field1 + /// field2 + /// Cancellation Token to cancel the request. + /// Task of ApiResponse + System.Threading.Tasks.Task> TestJsonFormDataWithHttpInfoAsync(string param, string param2, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + /// + /// + /// + /// + /// To test the collection format in query parameters + /// + /// Thrown when fails to make API call + /// + /// + /// + /// + /// + /// Cancellation Token to cancel the request. + /// Task of void + System.Threading.Tasks.Task TestQueryParameterCollectionFormatAsync(List pipe, List ioutil, List http, List url, List context, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// + /// + /// + /// To test the collection format in query parameters + /// + /// Thrown when fails to make API call + /// + /// + /// + /// + /// + /// Cancellation Token to cancel the request. + /// Task of ApiResponse + System.Threading.Tasks.Task> TestQueryParameterCollectionFormatWithHttpInfoAsync(List pipe, List ioutil, List http, List url, List context, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + #endregion Asynchronous Operations + } + + /// + /// Represents a collection of functions to interact with the API endpoints + /// + public interface IFakeApi : IFakeApiSync, IFakeApiAsync + { + + } + + /// + /// Represents a collection of functions to interact with the API endpoints + /// + public partial class FakeApi : IFakeApi + { + private Org.OpenAPITools.Client.ExceptionFactory _exceptionFactory = (name, response) => null; + + /// + /// Initializes a new instance of the class. + /// + /// + public FakeApi() : this((string)null) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// + public FakeApi(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 FakeApi(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 FakeApi(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; } + } + + /// + /// Health check endpoint + /// + /// Thrown when fails to make API call + /// HealthCheckResult + public HealthCheckResult FakeHealthGet() + { + Org.OpenAPITools.Client.ApiResponse localVarResponse = FakeHealthGetWithHttpInfo(); + return localVarResponse.Data; + } + + /// + /// Health check endpoint + /// + /// Thrown when fails to make API call + /// ApiResponse of HealthCheckResult + public Org.OpenAPITools.Client.ApiResponse FakeHealthGetWithHttpInfo() + { + 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); + + + + // make the HTTP request + var localVarResponse = this.Client.Get("/fake/health", localVarRequestOptions, this.Configuration); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("FakeHealthGet", localVarResponse); + if (_exception != null) throw _exception; + } + + return localVarResponse; + } + + /// + /// Health check endpoint + /// + /// Thrown when fails to make API call + /// Cancellation Token to cancel the request. + /// Task of HealthCheckResult + public async System.Threading.Tasks.Task FakeHealthGetAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + Org.OpenAPITools.Client.ApiResponse localVarResponse = await FakeHealthGetWithHttpInfoAsync(cancellationToken).ConfigureAwait(false); + return localVarResponse.Data; + } + + /// + /// Health check endpoint + /// + /// Thrown when fails to make API call + /// Cancellation Token to cancel the request. + /// Task of ApiResponse (HealthCheckResult) + public async System.Threading.Tasks.Task> FakeHealthGetWithHttpInfoAsync(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); + + + + // make the HTTP request + + var localVarResponse = await this.AsynchronousClient.GetAsync("/fake/health", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("FakeHealthGet", localVarResponse); + if (_exception != null) throw _exception; + } + + return localVarResponse; + } + + /// + /// Test serialization of outer boolean types + /// + /// Thrown when fails to make API call + /// Input boolean as post body (optional) + /// bool + public bool FakeOuterBooleanSerialize(bool? body = default(bool?)) + { + Org.OpenAPITools.Client.ApiResponse localVarResponse = FakeOuterBooleanSerializeWithHttpInfo(body); + return localVarResponse.Data; + } + + /// + /// Test serialization of outer boolean types + /// + /// Thrown when fails to make API call + /// Input boolean as post body (optional) + /// ApiResponse of bool + public Org.OpenAPITools.Client.ApiResponse FakeOuterBooleanSerializeWithHttpInfo(bool? body = default(bool?)) + { + 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 = body; + + + // make the HTTP request + var localVarResponse = this.Client.Post("/fake/outer/boolean", localVarRequestOptions, this.Configuration); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("FakeOuterBooleanSerialize", localVarResponse); + if (_exception != null) throw _exception; + } + + return localVarResponse; + } + + /// + /// Test serialization of outer boolean types + /// + /// Thrown when fails to make API call + /// Input boolean as post body (optional) + /// Cancellation Token to cancel the request. + /// Task of bool + public async System.Threading.Tasks.Task FakeOuterBooleanSerializeAsync(bool? body = default(bool?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + Org.OpenAPITools.Client.ApiResponse localVarResponse = await FakeOuterBooleanSerializeWithHttpInfoAsync(body, cancellationToken).ConfigureAwait(false); + return localVarResponse.Data; + } + + /// + /// Test serialization of outer boolean types + /// + /// Thrown when fails to make API call + /// Input boolean as post body (optional) + /// Cancellation Token to cancel the request. + /// Task of ApiResponse (bool) + public async System.Threading.Tasks.Task> FakeOuterBooleanSerializeWithHttpInfoAsync(bool? body = default(bool?), 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[] { + "*/*" + }; + + + 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 = body; + + + // make the HTTP request + + var localVarResponse = await this.AsynchronousClient.PostAsync("/fake/outer/boolean", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("FakeOuterBooleanSerialize", localVarResponse); + if (_exception != null) throw _exception; + } + + return localVarResponse; + } + + /// + /// Test serialization of object with outer number type + /// + /// Thrown when fails to make API call + /// Input composite as post body (optional) + /// OuterComposite + public OuterComposite FakeOuterCompositeSerialize(OuterComposite outerComposite = default(OuterComposite)) + { + Org.OpenAPITools.Client.ApiResponse localVarResponse = FakeOuterCompositeSerializeWithHttpInfo(outerComposite); + return localVarResponse.Data; + } + + /// + /// Test serialization of object with outer number type + /// + /// Thrown when fails to make API call + /// Input composite as post body (optional) + /// ApiResponse of OuterComposite + public Org.OpenAPITools.Client.ApiResponse FakeOuterCompositeSerializeWithHttpInfo(OuterComposite outerComposite = default(OuterComposite)) + { + 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 = outerComposite; + + + // make the HTTP request + var localVarResponse = this.Client.Post("/fake/outer/composite", localVarRequestOptions, this.Configuration); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("FakeOuterCompositeSerialize", localVarResponse); + if (_exception != null) throw _exception; + } + + return localVarResponse; + } + + /// + /// Test serialization of object with outer number type + /// + /// Thrown when fails to make API call + /// Input composite as post body (optional) + /// Cancellation Token to cancel the request. + /// Task of OuterComposite + public async System.Threading.Tasks.Task FakeOuterCompositeSerializeAsync(OuterComposite outerComposite = default(OuterComposite), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + Org.OpenAPITools.Client.ApiResponse localVarResponse = await FakeOuterCompositeSerializeWithHttpInfoAsync(outerComposite, cancellationToken).ConfigureAwait(false); + return localVarResponse.Data; + } + + /// + /// Test serialization of object with outer number type + /// + /// Thrown when fails to make API call + /// Input composite as post body (optional) + /// Cancellation Token to cancel the request. + /// Task of ApiResponse (OuterComposite) + public async System.Threading.Tasks.Task> FakeOuterCompositeSerializeWithHttpInfoAsync(OuterComposite outerComposite = default(OuterComposite), 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[] { + "*/*" + }; + + + 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 = outerComposite; + + + // make the HTTP request + + var localVarResponse = await this.AsynchronousClient.PostAsync("/fake/outer/composite", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("FakeOuterCompositeSerialize", localVarResponse); + if (_exception != null) throw _exception; + } + + return localVarResponse; + } + + /// + /// Test serialization of outer number types + /// + /// Thrown when fails to make API call + /// Input number as post body (optional) + /// decimal + public decimal FakeOuterNumberSerialize(decimal? body = default(decimal?)) + { + Org.OpenAPITools.Client.ApiResponse localVarResponse = FakeOuterNumberSerializeWithHttpInfo(body); + return localVarResponse.Data; + } + + /// + /// Test serialization of outer number types + /// + /// Thrown when fails to make API call + /// Input number as post body (optional) + /// ApiResponse of decimal + public Org.OpenAPITools.Client.ApiResponse FakeOuterNumberSerializeWithHttpInfo(decimal? body = default(decimal?)) + { + 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 = body; + + + // make the HTTP request + var localVarResponse = this.Client.Post("/fake/outer/number", localVarRequestOptions, this.Configuration); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("FakeOuterNumberSerialize", localVarResponse); + if (_exception != null) throw _exception; + } + + return localVarResponse; + } + + /// + /// Test serialization of outer number types + /// + /// Thrown when fails to make API call + /// Input number as post body (optional) + /// Cancellation Token to cancel the request. + /// Task of decimal + public async System.Threading.Tasks.Task FakeOuterNumberSerializeAsync(decimal? body = default(decimal?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + Org.OpenAPITools.Client.ApiResponse localVarResponse = await FakeOuterNumberSerializeWithHttpInfoAsync(body, cancellationToken).ConfigureAwait(false); + return localVarResponse.Data; + } + + /// + /// Test serialization of outer number types + /// + /// Thrown when fails to make API call + /// Input number as post body (optional) + /// Cancellation Token to cancel the request. + /// Task of ApiResponse (decimal) + public async System.Threading.Tasks.Task> FakeOuterNumberSerializeWithHttpInfoAsync(decimal? body = default(decimal?), 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[] { + "*/*" + }; + + + 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 = body; + + + // make the HTTP request + + var localVarResponse = await this.AsynchronousClient.PostAsync("/fake/outer/number", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("FakeOuterNumberSerialize", localVarResponse); + if (_exception != null) throw _exception; + } + + return localVarResponse; + } + + /// + /// Test serialization of outer string types + /// + /// Thrown when fails to make API call + /// Input string as post body (optional) + /// string + public string FakeOuterStringSerialize(string body = default(string)) + { + Org.OpenAPITools.Client.ApiResponse localVarResponse = FakeOuterStringSerializeWithHttpInfo(body); + return localVarResponse.Data; + } + + /// + /// Test serialization of outer string types + /// + /// Thrown when fails to make API call + /// Input string as post body (optional) + /// ApiResponse of string + public Org.OpenAPITools.Client.ApiResponse FakeOuterStringSerializeWithHttpInfo(string body = default(string)) + { + 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 = body; + + + // make the HTTP request + var localVarResponse = this.Client.Post("/fake/outer/string", localVarRequestOptions, this.Configuration); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("FakeOuterStringSerialize", localVarResponse); + if (_exception != null) throw _exception; + } + + return localVarResponse; + } + + /// + /// Test serialization of outer string types + /// + /// Thrown when fails to make API call + /// Input string as post body (optional) + /// Cancellation Token to cancel the request. + /// Task of string + public async System.Threading.Tasks.Task FakeOuterStringSerializeAsync(string body = default(string), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + Org.OpenAPITools.Client.ApiResponse localVarResponse = await FakeOuterStringSerializeWithHttpInfoAsync(body, cancellationToken).ConfigureAwait(false); + return localVarResponse.Data; + } + + /// + /// Test serialization of outer string types + /// + /// Thrown when fails to make API call + /// Input string as post body (optional) + /// Cancellation Token to cancel the request. + /// Task of ApiResponse (string) + public async System.Threading.Tasks.Task> FakeOuterStringSerializeWithHttpInfoAsync(string body = default(string), 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[] { + "*/*" + }; + + + 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 = body; + + + // make the HTTP request + + var localVarResponse = await this.AsynchronousClient.PostAsync("/fake/outer/string", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("FakeOuterStringSerialize", localVarResponse); + if (_exception != null) throw _exception; + } + + return localVarResponse; + } + + /// + /// Array of Enums + /// + /// Thrown when fails to make API call + /// List<OuterEnum> + public List GetArrayOfEnums() + { + Org.OpenAPITools.Client.ApiResponse> localVarResponse = GetArrayOfEnumsWithHttpInfo(); + return localVarResponse.Data; + } + + /// + /// Array of Enums + /// + /// Thrown when fails to make API call + /// ApiResponse of List<OuterEnum> + public Org.OpenAPITools.Client.ApiResponse> GetArrayOfEnumsWithHttpInfo() + { + 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); + + + + // make the HTTP request + var localVarResponse = this.Client.Get>("/fake/array-of-enums", localVarRequestOptions, this.Configuration); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("GetArrayOfEnums", localVarResponse); + if (_exception != null) throw _exception; + } + + return localVarResponse; + } + + /// + /// Array of Enums + /// + /// Thrown when fails to make API call + /// Cancellation Token to cancel the request. + /// Task of List<OuterEnum> + public async System.Threading.Tasks.Task> GetArrayOfEnumsAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + Org.OpenAPITools.Client.ApiResponse> localVarResponse = await GetArrayOfEnumsWithHttpInfoAsync(cancellationToken).ConfigureAwait(false); + return localVarResponse.Data; + } + + /// + /// Array of Enums + /// + /// Thrown when fails to make API call + /// Cancellation Token to cancel the request. + /// Task of ApiResponse (List<OuterEnum>) + public async System.Threading.Tasks.Task>> GetArrayOfEnumsWithHttpInfoAsync(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); + + + + // make the HTTP request + + var localVarResponse = await this.AsynchronousClient.GetAsync>("/fake/array-of-enums", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("GetArrayOfEnums", localVarResponse); + if (_exception != null) throw _exception; + } + + return localVarResponse; + } + + /// + /// For this test, the body for this request much reference a schema named `File`. + /// + /// Thrown when fails to make API call + /// + /// + public void TestBodyWithFileSchema(FileSchemaTestClass fileSchemaTestClass) + { + TestBodyWithFileSchemaWithHttpInfo(fileSchemaTestClass); + } + + /// + /// For this test, the body for this request much reference a schema named `File`. + /// + /// Thrown when fails to make API call + /// + /// ApiResponse of Object(void) + public Org.OpenAPITools.Client.ApiResponse TestBodyWithFileSchemaWithHttpInfo(FileSchemaTestClass fileSchemaTestClass) + { + // verify the required parameter 'fileSchemaTestClass' is set + if (fileSchemaTestClass == null) + throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'fileSchemaTestClass' when calling FakeApi->TestBodyWithFileSchema"); + + 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 = fileSchemaTestClass; + + + // make the HTTP request + var localVarResponse = this.Client.Put("/fake/body-with-file-schema", localVarRequestOptions, this.Configuration); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("TestBodyWithFileSchema", localVarResponse); + if (_exception != null) throw _exception; + } + + return localVarResponse; + } + + /// + /// For this test, the body for this request much reference a schema named `File`. + /// + /// Thrown when fails to make API call + /// + /// Cancellation Token to cancel the request. + /// Task of void + public async System.Threading.Tasks.Task TestBodyWithFileSchemaAsync(FileSchemaTestClass fileSchemaTestClass, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + await TestBodyWithFileSchemaWithHttpInfoAsync(fileSchemaTestClass, cancellationToken).ConfigureAwait(false); + } + + /// + /// For this test, the body for this request much reference a schema named `File`. + /// + /// Thrown when fails to make API call + /// + /// Cancellation Token to cancel the request. + /// Task of ApiResponse + public async System.Threading.Tasks.Task> TestBodyWithFileSchemaWithHttpInfoAsync(FileSchemaTestClass fileSchemaTestClass, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + // verify the required parameter 'fileSchemaTestClass' is set + if (fileSchemaTestClass == null) + throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'fileSchemaTestClass' when calling FakeApi->TestBodyWithFileSchema"); + + + 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 = fileSchemaTestClass; + + + // make the HTTP request + + var localVarResponse = await this.AsynchronousClient.PutAsync("/fake/body-with-file-schema", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("TestBodyWithFileSchema", localVarResponse); + if (_exception != null) throw _exception; + } + + return localVarResponse; + } + + /// + /// + /// + /// Thrown when fails to make API call + /// + /// + /// + public void TestBodyWithQueryParams(string query, User user) + { + TestBodyWithQueryParamsWithHttpInfo(query, user); + } + + /// + /// + /// + /// Thrown when fails to make API call + /// + /// + /// ApiResponse of Object(void) + public Org.OpenAPITools.Client.ApiResponse TestBodyWithQueryParamsWithHttpInfo(string query, User user) + { + // verify the required parameter 'query' is set + if (query == null) + throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'query' when calling FakeApi->TestBodyWithQueryParams"); + + // verify the required parameter 'user' is set + if (user == null) + throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'user' when calling FakeApi->TestBodyWithQueryParams"); + + 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.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("", "query", query)); + localVarRequestOptions.Data = user; + + + // make the HTTP request + var localVarResponse = this.Client.Put("/fake/body-with-query-params", localVarRequestOptions, this.Configuration); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("TestBodyWithQueryParams", localVarResponse); + if (_exception != null) throw _exception; + } + + return localVarResponse; + } + + /// + /// + /// + /// Thrown when fails to make API call + /// + /// + /// Cancellation Token to cancel the request. + /// Task of void + public async System.Threading.Tasks.Task TestBodyWithQueryParamsAsync(string query, User user, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + await TestBodyWithQueryParamsWithHttpInfoAsync(query, user, cancellationToken).ConfigureAwait(false); + } + + /// + /// + /// + /// Thrown when fails to make API call + /// + /// + /// Cancellation Token to cancel the request. + /// Task of ApiResponse + public async System.Threading.Tasks.Task> TestBodyWithQueryParamsWithHttpInfoAsync(string query, User user, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + // verify the required parameter 'query' is set + if (query == null) + throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'query' when calling FakeApi->TestBodyWithQueryParams"); + + // verify the required parameter 'user' is set + if (user == null) + throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'user' when calling FakeApi->TestBodyWithQueryParams"); + + + 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.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("", "query", query)); + localVarRequestOptions.Data = user; + + + // make the HTTP request + + var localVarResponse = await this.AsynchronousClient.PutAsync("/fake/body-with-query-params", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("TestBodyWithQueryParams", localVarResponse); + if (_exception != null) throw _exception; + } + + return localVarResponse; + } + + /// + /// To test \"client\" model To test \"client\" model + /// + /// Thrown when fails to make API call + /// client model + /// ModelClient + public ModelClient TestClientModel(ModelClient modelClient) + { + Org.OpenAPITools.Client.ApiResponse localVarResponse = TestClientModelWithHttpInfo(modelClient); + return localVarResponse.Data; + } + + /// + /// To test \"client\" model To test \"client\" model + /// + /// Thrown when fails to make API call + /// client model + /// ApiResponse of ModelClient + public Org.OpenAPITools.Client.ApiResponse TestClientModelWithHttpInfo(ModelClient modelClient) + { + // verify the required parameter 'modelClient' is set + if (modelClient == null) + throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'modelClient' when calling FakeApi->TestClientModel"); + + 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 = modelClient; + + + // make the HTTP request + var localVarResponse = this.Client.Patch("/fake", localVarRequestOptions, this.Configuration); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("TestClientModel", localVarResponse); + if (_exception != null) throw _exception; + } + + return localVarResponse; + } + + /// + /// To test \"client\" model To test \"client\" model + /// + /// Thrown when fails to make API call + /// client model + /// Cancellation Token to cancel the request. + /// Task of ModelClient + public async System.Threading.Tasks.Task TestClientModelAsync(ModelClient modelClient, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + Org.OpenAPITools.Client.ApiResponse localVarResponse = await TestClientModelWithHttpInfoAsync(modelClient, cancellationToken).ConfigureAwait(false); + return localVarResponse.Data; + } + + /// + /// To test \"client\" model To test \"client\" model + /// + /// Thrown when fails to make API call + /// client model + /// Cancellation Token to cancel the request. + /// Task of ApiResponse (ModelClient) + public async System.Threading.Tasks.Task> TestClientModelWithHttpInfoAsync(ModelClient modelClient, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + // verify the required parameter 'modelClient' is set + if (modelClient == null) + throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'modelClient' when calling FakeApi->TestClientModel"); + + + 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 = modelClient; + + + // make the HTTP request + + var localVarResponse = await this.AsynchronousClient.PatchAsync("/fake", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("TestClientModel", localVarResponse); + if (_exception != null) throw _exception; + } + + return localVarResponse; + } + + /// + /// Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + /// + /// Thrown when fails to make API call + /// None + /// None + /// None + /// None + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional, default to "2010-02-01T10:20:10.111110+01:00") + /// None (optional) + /// None (optional) + /// + public void TestEndpointParameters(decimal number, double _double, string patternWithoutDelimiter, byte[] _byte, int? integer = default(int?), int? int32 = default(int?), long? int64 = default(long?), float? _float = default(float?), string _string = 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)) + { + TestEndpointParametersWithHttpInfo(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, _string, binary, date, dateTime, password, callback); + } + + /// + /// Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + /// + /// Thrown when fails to make API call + /// None + /// None + /// None + /// None + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional, default to "2010-02-01T10:20:10.111110+01:00") + /// None (optional) + /// None (optional) + /// ApiResponse of Object(void) + public Org.OpenAPITools.Client.ApiResponse TestEndpointParametersWithHttpInfo(decimal number, double _double, string patternWithoutDelimiter, byte[] _byte, int? integer = default(int?), int? int32 = default(int?), long? int64 = default(long?), float? _float = default(float?), string _string = 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)) + { + // verify the required parameter 'patternWithoutDelimiter' is set + if (patternWithoutDelimiter == null) + throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'patternWithoutDelimiter' when calling FakeApi->TestEndpointParameters"); + + // verify the required parameter '_byte' is set + if (_byte == null) + throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter '_byte' when calling FakeApi->TestEndpointParameters"); + + Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + "application/x-www-form-urlencoded" + }; + + // 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); + + if (integer != null) + { + localVarRequestOptions.FormParameters.Add("integer", Org.OpenAPITools.Client.ClientUtils.ParameterToString(integer)); // form parameter + } + if (int32 != null) + { + localVarRequestOptions.FormParameters.Add("int32", Org.OpenAPITools.Client.ClientUtils.ParameterToString(int32)); // form parameter + } + if (int64 != null) + { + localVarRequestOptions.FormParameters.Add("int64", Org.OpenAPITools.Client.ClientUtils.ParameterToString(int64)); // form parameter + } + localVarRequestOptions.FormParameters.Add("number", Org.OpenAPITools.Client.ClientUtils.ParameterToString(number)); // form parameter + if (_float != null) + { + localVarRequestOptions.FormParameters.Add("float", Org.OpenAPITools.Client.ClientUtils.ParameterToString(_float)); // form parameter + } + localVarRequestOptions.FormParameters.Add("double", Org.OpenAPITools.Client.ClientUtils.ParameterToString(_double)); // form parameter + if (_string != null) + { + localVarRequestOptions.FormParameters.Add("string", Org.OpenAPITools.Client.ClientUtils.ParameterToString(_string)); // form parameter + } + localVarRequestOptions.FormParameters.Add("pattern_without_delimiter", Org.OpenAPITools.Client.ClientUtils.ParameterToString(patternWithoutDelimiter)); // form parameter + localVarRequestOptions.FormParameters.Add("byte", Org.OpenAPITools.Client.ClientUtils.ParameterToString(_byte)); // form parameter + if (binary != null) + { + localVarRequestOptions.FileParameters.Add("binary", binary); + } + if (date != null) + { + localVarRequestOptions.FormParameters.Add("date", Org.OpenAPITools.Client.ClientUtils.ParameterToString(date)); // form parameter + } + if (dateTime != null) + { + localVarRequestOptions.FormParameters.Add("dateTime", Org.OpenAPITools.Client.ClientUtils.ParameterToString(dateTime)); // form parameter + } + if (password != null) + { + localVarRequestOptions.FormParameters.Add("password", Org.OpenAPITools.Client.ClientUtils.ParameterToString(password)); // form parameter + } + if (callback != null) + { + localVarRequestOptions.FormParameters.Add("callback", Org.OpenAPITools.Client.ClientUtils.ParameterToString(callback)); // form parameter + } + + // authentication (http_basic_test) required + // http basic authentication required + if (!string.IsNullOrEmpty(this.Configuration.Username) || !string.IsNullOrEmpty(this.Configuration.Password)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Basic " + Org.OpenAPITools.Client.ClientUtils.Base64Encode(this.Configuration.Username + ":" + this.Configuration.Password)); + } + + // make the HTTP request + var localVarResponse = this.Client.Post("/fake", localVarRequestOptions, this.Configuration); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("TestEndpointParameters", localVarResponse); + if (_exception != null) throw _exception; + } + + return localVarResponse; + } + + /// + /// Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + /// + /// Thrown when fails to make API call + /// None + /// None + /// None + /// None + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional, default to "2010-02-01T10:20:10.111110+01:00") + /// None (optional) + /// None (optional) + /// Cancellation Token to cancel the request. + /// Task of void + public async System.Threading.Tasks.Task TestEndpointParametersAsync(decimal number, double _double, string patternWithoutDelimiter, byte[] _byte, int? integer = default(int?), int? int32 = default(int?), long? int64 = default(long?), float? _float = default(float?), string _string = 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), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + await TestEndpointParametersWithHttpInfoAsync(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, _string, binary, date, dateTime, password, callback, cancellationToken).ConfigureAwait(false); + } + + /// + /// Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + /// + /// Thrown when fails to make API call + /// None + /// None + /// None + /// None + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional) + /// None (optional, default to "2010-02-01T10:20:10.111110+01:00") + /// None (optional) + /// None (optional) + /// Cancellation Token to cancel the request. + /// Task of ApiResponse + public async System.Threading.Tasks.Task> TestEndpointParametersWithHttpInfoAsync(decimal number, double _double, string patternWithoutDelimiter, byte[] _byte, int? integer = default(int?), int? int32 = default(int?), long? int64 = default(long?), float? _float = default(float?), string _string = 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), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + // verify the required parameter 'patternWithoutDelimiter' is set + if (patternWithoutDelimiter == null) + throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'patternWithoutDelimiter' when calling FakeApi->TestEndpointParameters"); + + // verify the required parameter '_byte' is set + if (_byte == null) + throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter '_byte' when calling FakeApi->TestEndpointParameters"); + + + Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + "application/x-www-form-urlencoded" + }; + + // 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); + + if (integer != null) + { + localVarRequestOptions.FormParameters.Add("integer", Org.OpenAPITools.Client.ClientUtils.ParameterToString(integer)); // form parameter + } + if (int32 != null) + { + localVarRequestOptions.FormParameters.Add("int32", Org.OpenAPITools.Client.ClientUtils.ParameterToString(int32)); // form parameter + } + if (int64 != null) + { + localVarRequestOptions.FormParameters.Add("int64", Org.OpenAPITools.Client.ClientUtils.ParameterToString(int64)); // form parameter + } + localVarRequestOptions.FormParameters.Add("number", Org.OpenAPITools.Client.ClientUtils.ParameterToString(number)); // form parameter + if (_float != null) + { + localVarRequestOptions.FormParameters.Add("float", Org.OpenAPITools.Client.ClientUtils.ParameterToString(_float)); // form parameter + } + localVarRequestOptions.FormParameters.Add("double", Org.OpenAPITools.Client.ClientUtils.ParameterToString(_double)); // form parameter + if (_string != null) + { + localVarRequestOptions.FormParameters.Add("string", Org.OpenAPITools.Client.ClientUtils.ParameterToString(_string)); // form parameter + } + localVarRequestOptions.FormParameters.Add("pattern_without_delimiter", Org.OpenAPITools.Client.ClientUtils.ParameterToString(patternWithoutDelimiter)); // form parameter + localVarRequestOptions.FormParameters.Add("byte", Org.OpenAPITools.Client.ClientUtils.ParameterToString(_byte)); // form parameter + if (binary != null) + { + localVarRequestOptions.FileParameters.Add("binary", binary); + } + if (date != null) + { + localVarRequestOptions.FormParameters.Add("date", Org.OpenAPITools.Client.ClientUtils.ParameterToString(date)); // form parameter + } + if (dateTime != null) + { + localVarRequestOptions.FormParameters.Add("dateTime", Org.OpenAPITools.Client.ClientUtils.ParameterToString(dateTime)); // form parameter + } + if (password != null) + { + localVarRequestOptions.FormParameters.Add("password", Org.OpenAPITools.Client.ClientUtils.ParameterToString(password)); // form parameter + } + if (callback != null) + { + localVarRequestOptions.FormParameters.Add("callback", Org.OpenAPITools.Client.ClientUtils.ParameterToString(callback)); // form parameter + } + + // authentication (http_basic_test) required + // http basic authentication required + if (!string.IsNullOrEmpty(this.Configuration.Username) || !string.IsNullOrEmpty(this.Configuration.Password)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Basic " + Org.OpenAPITools.Client.ClientUtils.Base64Encode(this.Configuration.Username + ":" + this.Configuration.Password)); + } + + // make the HTTP request + + var localVarResponse = await this.AsynchronousClient.PostAsync("/fake", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("TestEndpointParameters", localVarResponse); + if (_exception != null) throw _exception; + } + + return localVarResponse; + } + + /// + /// To test enum parameters To test enum parameters + /// + /// Thrown when fails to make API call + /// Header parameter enum test (string array) (optional) + /// Header parameter enum test (string) (optional, default to -efg) + /// Query parameter enum test (string array) (optional) + /// Query parameter enum test (string) (optional, default to -efg) + /// Query parameter enum test (double) (optional) + /// Query parameter enum test (double) (optional) + /// Form parameter enum test (string array) (optional, default to $) + /// Form parameter enum test (string) (optional, default to -efg) + /// + public void TestEnumParameters(List enumHeaderStringArray = default(List), string enumHeaderString = default(string), List enumQueryStringArray = default(List), string enumQueryString = default(string), int? enumQueryInteger = default(int?), double? enumQueryDouble = default(double?), List enumFormStringArray = default(List), string enumFormString = default(string)) + { + TestEnumParametersWithHttpInfo(enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble, enumFormStringArray, enumFormString); + } + + /// + /// To test enum parameters To test enum parameters + /// + /// Thrown when fails to make API call + /// Header parameter enum test (string array) (optional) + /// Header parameter enum test (string) (optional, default to -efg) + /// Query parameter enum test (string array) (optional) + /// Query parameter enum test (string) (optional, default to -efg) + /// Query parameter enum test (double) (optional) + /// Query parameter enum test (double) (optional) + /// Form parameter enum test (string array) (optional, default to $) + /// Form parameter enum test (string) (optional, default to -efg) + /// ApiResponse of Object(void) + public Org.OpenAPITools.Client.ApiResponse TestEnumParametersWithHttpInfo(List enumHeaderStringArray = default(List), string enumHeaderString = default(string), List enumQueryStringArray = default(List), string enumQueryString = default(string), int? enumQueryInteger = default(int?), double? enumQueryDouble = default(double?), List enumFormStringArray = default(List), string enumFormString = default(string)) + { + Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + "application/x-www-form-urlencoded" + }; + + // 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); + + if (enumQueryStringArray != null) + { + localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("multi", "enum_query_string_array", enumQueryStringArray)); + } + if (enumQueryString != null) + { + localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("", "enum_query_string", enumQueryString)); + } + if (enumQueryInteger != null) + { + localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("", "enum_query_integer", enumQueryInteger)); + } + if (enumQueryDouble != null) + { + localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("", "enum_query_double", enumQueryDouble)); + } + if (enumHeaderStringArray != null) + { + localVarRequestOptions.HeaderParameters.Add("enum_header_string_array", Org.OpenAPITools.Client.ClientUtils.ParameterToString(enumHeaderStringArray)); // header parameter + } + if (enumHeaderString != null) + { + localVarRequestOptions.HeaderParameters.Add("enum_header_string", Org.OpenAPITools.Client.ClientUtils.ParameterToString(enumHeaderString)); // header parameter + } + if (enumFormStringArray != null) + { + localVarRequestOptions.FormParameters.Add("enum_form_string_array", Org.OpenAPITools.Client.ClientUtils.ParameterToString(enumFormStringArray)); // form parameter + } + if (enumFormString != null) + { + localVarRequestOptions.FormParameters.Add("enum_form_string", Org.OpenAPITools.Client.ClientUtils.ParameterToString(enumFormString)); // form parameter + } + + + // make the HTTP request + var localVarResponse = this.Client.Get("/fake", localVarRequestOptions, this.Configuration); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("TestEnumParameters", localVarResponse); + if (_exception != null) throw _exception; + } + + return localVarResponse; + } + + /// + /// To test enum parameters To test enum parameters + /// + /// Thrown when fails to make API call + /// Header parameter enum test (string array) (optional) + /// Header parameter enum test (string) (optional, default to -efg) + /// Query parameter enum test (string array) (optional) + /// Query parameter enum test (string) (optional, default to -efg) + /// Query parameter enum test (double) (optional) + /// Query parameter enum test (double) (optional) + /// Form parameter enum test (string array) (optional, default to $) + /// Form parameter enum test (string) (optional, default to -efg) + /// Cancellation Token to cancel the request. + /// Task of void + public async System.Threading.Tasks.Task TestEnumParametersAsync(List enumHeaderStringArray = default(List), string enumHeaderString = default(string), List enumQueryStringArray = default(List), string enumQueryString = default(string), int? enumQueryInteger = default(int?), double? enumQueryDouble = default(double?), List enumFormStringArray = default(List), string enumFormString = default(string), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + await TestEnumParametersWithHttpInfoAsync(enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble, enumFormStringArray, enumFormString, cancellationToken).ConfigureAwait(false); + } + + /// + /// To test enum parameters To test enum parameters + /// + /// Thrown when fails to make API call + /// Header parameter enum test (string array) (optional) + /// Header parameter enum test (string) (optional, default to -efg) + /// Query parameter enum test (string array) (optional) + /// Query parameter enum test (string) (optional, default to -efg) + /// Query parameter enum test (double) (optional) + /// Query parameter enum test (double) (optional) + /// Form parameter enum test (string array) (optional, default to $) + /// Form parameter enum test (string) (optional, default to -efg) + /// Cancellation Token to cancel the request. + /// Task of ApiResponse + public async System.Threading.Tasks.Task> TestEnumParametersWithHttpInfoAsync(List enumHeaderStringArray = default(List), string enumHeaderString = default(string), List enumQueryStringArray = default(List), string enumQueryString = default(string), int? enumQueryInteger = default(int?), double? enumQueryDouble = default(double?), List enumFormStringArray = default(List), string enumFormString = default(string), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + + Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + "application/x-www-form-urlencoded" + }; + + // 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); + + if (enumQueryStringArray != null) + { + localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("multi", "enum_query_string_array", enumQueryStringArray)); + } + if (enumQueryString != null) + { + localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("", "enum_query_string", enumQueryString)); + } + if (enumQueryInteger != null) + { + localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("", "enum_query_integer", enumQueryInteger)); + } + if (enumQueryDouble != null) + { + localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("", "enum_query_double", enumQueryDouble)); + } + if (enumHeaderStringArray != null) + { + localVarRequestOptions.HeaderParameters.Add("enum_header_string_array", Org.OpenAPITools.Client.ClientUtils.ParameterToString(enumHeaderStringArray)); // header parameter + } + if (enumHeaderString != null) + { + localVarRequestOptions.HeaderParameters.Add("enum_header_string", Org.OpenAPITools.Client.ClientUtils.ParameterToString(enumHeaderString)); // header parameter + } + if (enumFormStringArray != null) + { + localVarRequestOptions.FormParameters.Add("enum_form_string_array", Org.OpenAPITools.Client.ClientUtils.ParameterToString(enumFormStringArray)); // form parameter + } + if (enumFormString != null) + { + localVarRequestOptions.FormParameters.Add("enum_form_string", Org.OpenAPITools.Client.ClientUtils.ParameterToString(enumFormString)); // form parameter + } + + + // make the HTTP request + + var localVarResponse = await this.AsynchronousClient.GetAsync("/fake", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("TestEnumParameters", localVarResponse); + if (_exception != null) throw _exception; + } + + return localVarResponse; + } + + /// + /// Fake endpoint to test group parameters (optional) Fake endpoint to test group parameters (optional) + /// + /// Thrown when fails to make API call + /// Required String in group parameters + /// Required Boolean in group parameters + /// Required Integer in group parameters + /// String in group parameters (optional) + /// Boolean in group parameters (optional) + /// Integer in group parameters (optional) + /// + public void TestGroupParameters(int requiredStringGroup, bool requiredBooleanGroup, long requiredInt64Group, int? stringGroup = default(int?), bool? booleanGroup = default(bool?), long? int64Group = default(long?)) + { + TestGroupParametersWithHttpInfo(requiredStringGroup, requiredBooleanGroup, requiredInt64Group, stringGroup, booleanGroup, int64Group); + } + + /// + /// Fake endpoint to test group parameters (optional) Fake endpoint to test group parameters (optional) + /// + /// Thrown when fails to make API call + /// Required String in group parameters + /// Required Boolean in group parameters + /// Required Integer in group parameters + /// String in group parameters (optional) + /// Boolean in group parameters (optional) + /// Integer in group parameters (optional) + /// ApiResponse of Object(void) + public Org.OpenAPITools.Client.ApiResponse TestGroupParametersWithHttpInfo(int requiredStringGroup, bool requiredBooleanGroup, long requiredInt64Group, int? stringGroup = default(int?), bool? booleanGroup = default(bool?), long? int64Group = default(long?)) + { + Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + }; + + // 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.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("", "required_string_group", requiredStringGroup)); + localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("", "required_int64_group", requiredInt64Group)); + if (stringGroup != null) + { + localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("", "string_group", stringGroup)); + } + if (int64Group != null) + { + localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("", "int64_group", int64Group)); + } + localVarRequestOptions.HeaderParameters.Add("required_boolean_group", Org.OpenAPITools.Client.ClientUtils.ParameterToString(requiredBooleanGroup)); // header parameter + if (booleanGroup != null) + { + localVarRequestOptions.HeaderParameters.Add("boolean_group", Org.OpenAPITools.Client.ClientUtils.ParameterToString(booleanGroup)); // header parameter + } + + // authentication (bearer_test) required + // bearer authentication required + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + + // make the HTTP request + var localVarResponse = this.Client.Delete("/fake", localVarRequestOptions, this.Configuration); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("TestGroupParameters", localVarResponse); + if (_exception != null) throw _exception; + } + + return localVarResponse; + } + + /// + /// Fake endpoint to test group parameters (optional) Fake endpoint to test group parameters (optional) + /// + /// Thrown when fails to make API call + /// Required String in group parameters + /// Required Boolean in group parameters + /// Required Integer in group parameters + /// String in group parameters (optional) + /// Boolean in group parameters (optional) + /// Integer in group parameters (optional) + /// Cancellation Token to cancel the request. + /// Task of void + public async System.Threading.Tasks.Task TestGroupParametersAsync(int requiredStringGroup, bool requiredBooleanGroup, long requiredInt64Group, int? stringGroup = default(int?), bool? booleanGroup = default(bool?), long? int64Group = default(long?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + await TestGroupParametersWithHttpInfoAsync(requiredStringGroup, requiredBooleanGroup, requiredInt64Group, stringGroup, booleanGroup, int64Group, cancellationToken).ConfigureAwait(false); + } + + /// + /// Fake endpoint to test group parameters (optional) Fake endpoint to test group parameters (optional) + /// + /// Thrown when fails to make API call + /// Required String in group parameters + /// Required Boolean in group parameters + /// Required Integer in group parameters + /// String in group parameters (optional) + /// Boolean in group parameters (optional) + /// Integer in group parameters (optional) + /// Cancellation Token to cancel the request. + /// Task of ApiResponse + public async System.Threading.Tasks.Task> TestGroupParametersWithHttpInfoAsync(int requiredStringGroup, bool requiredBooleanGroup, long requiredInt64Group, int? stringGroup = default(int?), bool? booleanGroup = default(bool?), long? int64Group = default(long?), 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[] { + }; + + + 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.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("", "required_string_group", requiredStringGroup)); + localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("", "required_int64_group", requiredInt64Group)); + if (stringGroup != null) + { + localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("", "string_group", stringGroup)); + } + if (int64Group != null) + { + localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("", "int64_group", int64Group)); + } + localVarRequestOptions.HeaderParameters.Add("required_boolean_group", Org.OpenAPITools.Client.ClientUtils.ParameterToString(requiredBooleanGroup)); // header parameter + if (booleanGroup != null) + { + localVarRequestOptions.HeaderParameters.Add("boolean_group", Org.OpenAPITools.Client.ClientUtils.ParameterToString(booleanGroup)); // header parameter + } + + // authentication (bearer_test) required + // bearer authentication required + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + + // make the HTTP request + + var localVarResponse = await this.AsynchronousClient.DeleteAsync("/fake", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("TestGroupParameters", localVarResponse); + if (_exception != null) throw _exception; + } + + return localVarResponse; + } + + /// + /// test inline additionalProperties + /// + /// Thrown when fails to make API call + /// request body + /// + public void TestInlineAdditionalProperties(Dictionary requestBody) + { + TestInlineAdditionalPropertiesWithHttpInfo(requestBody); + } + + /// + /// test inline additionalProperties + /// + /// Thrown when fails to make API call + /// request body + /// ApiResponse of Object(void) + public Org.OpenAPITools.Client.ApiResponse TestInlineAdditionalPropertiesWithHttpInfo(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->TestInlineAdditionalProperties"); + + 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/inline-additionalProperties", localVarRequestOptions, this.Configuration); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("TestInlineAdditionalProperties", localVarResponse); + if (_exception != null) throw _exception; + } + + return localVarResponse; + } + + /// + /// test inline 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 TestInlineAdditionalPropertiesAsync(Dictionary requestBody, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + await TestInlineAdditionalPropertiesWithHttpInfoAsync(requestBody, cancellationToken).ConfigureAwait(false); + } + + /// + /// test inline 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> TestInlineAdditionalPropertiesWithHttpInfoAsync(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->TestInlineAdditionalProperties"); + + + 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/inline-additionalProperties", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("TestInlineAdditionalProperties", localVarResponse); + if (_exception != null) throw _exception; + } + + return localVarResponse; + } + + /// + /// test json serialization of form data + /// + /// Thrown when fails to make API call + /// field1 + /// field2 + /// + public void TestJsonFormData(string param, string param2) + { + TestJsonFormDataWithHttpInfo(param, param2); + } + + /// + /// test json serialization of form data + /// + /// Thrown when fails to make API call + /// field1 + /// field2 + /// ApiResponse of Object(void) + public Org.OpenAPITools.Client.ApiResponse TestJsonFormDataWithHttpInfo(string param, string param2) + { + // verify the required parameter 'param' is set + if (param == null) + throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'param' when calling FakeApi->TestJsonFormData"); + + // verify the required parameter 'param2' is set + if (param2 == null) + throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'param2' when calling FakeApi->TestJsonFormData"); + + Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + "application/x-www-form-urlencoded" + }; + + // 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.FormParameters.Add("param", Org.OpenAPITools.Client.ClientUtils.ParameterToString(param)); // form parameter + localVarRequestOptions.FormParameters.Add("param2", Org.OpenAPITools.Client.ClientUtils.ParameterToString(param2)); // form parameter + + + // make the HTTP request + var localVarResponse = this.Client.Get("/fake/jsonFormData", localVarRequestOptions, this.Configuration); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("TestJsonFormData", localVarResponse); + if (_exception != null) throw _exception; + } + + return localVarResponse; + } + + /// + /// test json serialization of form data + /// + /// Thrown when fails to make API call + /// field1 + /// field2 + /// Cancellation Token to cancel the request. + /// Task of void + public async System.Threading.Tasks.Task TestJsonFormDataAsync(string param, string param2, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + await TestJsonFormDataWithHttpInfoAsync(param, param2, cancellationToken).ConfigureAwait(false); + } + + /// + /// test json serialization of form data + /// + /// Thrown when fails to make API call + /// field1 + /// field2 + /// Cancellation Token to cancel the request. + /// Task of ApiResponse + public async System.Threading.Tasks.Task> TestJsonFormDataWithHttpInfoAsync(string param, string param2, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + // verify the required parameter 'param' is set + if (param == null) + throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'param' when calling FakeApi->TestJsonFormData"); + + // verify the required parameter 'param2' is set + if (param2 == null) + throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'param2' when calling FakeApi->TestJsonFormData"); + + + Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + "application/x-www-form-urlencoded" + }; + + // 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.FormParameters.Add("param", Org.OpenAPITools.Client.ClientUtils.ParameterToString(param)); // form parameter + localVarRequestOptions.FormParameters.Add("param2", Org.OpenAPITools.Client.ClientUtils.ParameterToString(param2)); // form parameter + + + // make the HTTP request + + var localVarResponse = await this.AsynchronousClient.GetAsync("/fake/jsonFormData", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("TestJsonFormData", localVarResponse); + if (_exception != null) throw _exception; + } + + return localVarResponse; + } + + /// + /// To test the collection format in query parameters + /// + /// Thrown when fails to make API call + /// + /// + /// + /// + /// + /// + public void TestQueryParameterCollectionFormat(List pipe, List ioutil, List http, List url, List context) + { + TestQueryParameterCollectionFormatWithHttpInfo(pipe, ioutil, http, url, context); + } + + /// + /// To test the collection format in query parameters + /// + /// Thrown when fails to make API call + /// + /// + /// + /// + /// + /// ApiResponse of Object(void) + public Org.OpenAPITools.Client.ApiResponse TestQueryParameterCollectionFormatWithHttpInfo(List pipe, List ioutil, List http, List url, List context) + { + // verify the required parameter 'pipe' is set + if (pipe == null) + throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'pipe' when calling FakeApi->TestQueryParameterCollectionFormat"); + + // verify the required parameter 'ioutil' is set + if (ioutil == null) + throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'ioutil' when calling FakeApi->TestQueryParameterCollectionFormat"); + + // verify the required parameter 'http' is set + if (http == null) + throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'http' when calling FakeApi->TestQueryParameterCollectionFormat"); + + // verify the required parameter 'url' is set + if (url == null) + throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'url' when calling FakeApi->TestQueryParameterCollectionFormat"); + + // verify the required parameter 'context' is set + if (context == null) + throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'context' when calling FakeApi->TestQueryParameterCollectionFormat"); + + Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + }; + + // 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.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("multi", "pipe", pipe)); + localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("csv", "ioutil", ioutil)); + localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("ssv", "http", http)); + localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("csv", "url", url)); + localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("multi", "context", context)); + + + // make the HTTP request + var localVarResponse = this.Client.Put("/fake/test-query-paramters", localVarRequestOptions, this.Configuration); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("TestQueryParameterCollectionFormat", localVarResponse); + if (_exception != null) throw _exception; + } + + return localVarResponse; + } + + /// + /// To test the collection format in query parameters + /// + /// Thrown when fails to make API call + /// + /// + /// + /// + /// + /// Cancellation Token to cancel the request. + /// Task of void + public async System.Threading.Tasks.Task TestQueryParameterCollectionFormatAsync(List pipe, List ioutil, List http, List url, List context, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + await TestQueryParameterCollectionFormatWithHttpInfoAsync(pipe, ioutil, http, url, context, cancellationToken).ConfigureAwait(false); + } + + /// + /// To test the collection format in query parameters + /// + /// Thrown when fails to make API call + /// + /// + /// + /// + /// + /// Cancellation Token to cancel the request. + /// Task of ApiResponse + public async System.Threading.Tasks.Task> TestQueryParameterCollectionFormatWithHttpInfoAsync(List pipe, List ioutil, List http, List url, List context, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + // verify the required parameter 'pipe' is set + if (pipe == null) + throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'pipe' when calling FakeApi->TestQueryParameterCollectionFormat"); + + // verify the required parameter 'ioutil' is set + if (ioutil == null) + throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'ioutil' when calling FakeApi->TestQueryParameterCollectionFormat"); + + // verify the required parameter 'http' is set + if (http == null) + throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'http' when calling FakeApi->TestQueryParameterCollectionFormat"); + + // verify the required parameter 'url' is set + if (url == null) + throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'url' when calling FakeApi->TestQueryParameterCollectionFormat"); + + // verify the required parameter 'context' is set + if (context == null) + throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'context' when calling FakeApi->TestQueryParameterCollectionFormat"); + + + Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + }; + + // 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.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("multi", "pipe", pipe)); + localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("csv", "ioutil", ioutil)); + localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("ssv", "http", http)); + localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("csv", "url", url)); + localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("multi", "context", context)); + + + // make the HTTP request + + var localVarResponse = await this.AsynchronousClient.PutAsync("/fake/test-query-paramters", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("TestQueryParameterCollectionFormat", localVarResponse); + if (_exception != null) throw _exception; + } + + return localVarResponse; + } + + } +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Api/FakeClassnameTags123Api.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Api/FakeClassnameTags123Api.cs new file mode 100644 index 00000000000..d4fbb5868ad --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Api/FakeClassnameTags123Api.cs @@ -0,0 +1,330 @@ +/* + * 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.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 IFakeClassnameTags123ApiSync : IApiAccessor + { + #region Synchronous Operations + /// + /// To test class name in snake case + /// + /// + /// To test class name in snake case + /// + /// Thrown when fails to make API call + /// client model + /// ModelClient + ModelClient TestClassname(ModelClient modelClient); + + /// + /// To test class name in snake case + /// + /// + /// To test class name in snake case + /// + /// Thrown when fails to make API call + /// client model + /// ApiResponse of ModelClient + ApiResponse TestClassnameWithHttpInfo(ModelClient modelClient); + #endregion Synchronous Operations + } + + /// + /// Represents a collection of functions to interact with the API endpoints + /// + public interface IFakeClassnameTags123ApiAsync : IApiAccessor + { + #region Asynchronous Operations + /// + /// To test class name in snake case + /// + /// + /// To test class name in snake case + /// + /// Thrown when fails to make API call + /// client model + /// Cancellation Token to cancel the request. + /// Task of ModelClient + System.Threading.Tasks.Task TestClassnameAsync(ModelClient modelClient, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// To test class name in snake case + /// + /// + /// To test class name in snake case + /// + /// Thrown when fails to make API call + /// client model + /// Cancellation Token to cancel the request. + /// Task of ApiResponse (ModelClient) + System.Threading.Tasks.Task> TestClassnameWithHttpInfoAsync(ModelClient modelClient, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + #endregion Asynchronous Operations + } + + /// + /// Represents a collection of functions to interact with the API endpoints + /// + public interface IFakeClassnameTags123Api : IFakeClassnameTags123ApiSync, IFakeClassnameTags123ApiAsync + { + + } + + /// + /// Represents a collection of functions to interact with the API endpoints + /// + public partial class FakeClassnameTags123Api : IFakeClassnameTags123Api + { + private Org.OpenAPITools.Client.ExceptionFactory _exceptionFactory = (name, response) => null; + + /// + /// Initializes a new instance of the class. + /// + /// + public FakeClassnameTags123Api() : this((string)null) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// + public FakeClassnameTags123Api(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 FakeClassnameTags123Api(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 FakeClassnameTags123Api(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; } + } + + /// + /// To test class name in snake case To test class name in snake case + /// + /// Thrown when fails to make API call + /// client model + /// ModelClient + public ModelClient TestClassname(ModelClient modelClient) + { + Org.OpenAPITools.Client.ApiResponse localVarResponse = TestClassnameWithHttpInfo(modelClient); + return localVarResponse.Data; + } + + /// + /// To test class name in snake case To test class name in snake case + /// + /// Thrown when fails to make API call + /// client model + /// ApiResponse of ModelClient + public Org.OpenAPITools.Client.ApiResponse TestClassnameWithHttpInfo(ModelClient modelClient) + { + // verify the required parameter 'modelClient' is set + if (modelClient == null) + throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'modelClient' when calling FakeClassnameTags123Api->TestClassname"); + + 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 = modelClient; + + // 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.Patch("/fake_classname_test", localVarRequestOptions, this.Configuration); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("TestClassname", localVarResponse); + if (_exception != null) throw _exception; + } + + return localVarResponse; + } + + /// + /// To test class name in snake case To test class name in snake case + /// + /// Thrown when fails to make API call + /// client model + /// Cancellation Token to cancel the request. + /// Task of ModelClient + public async System.Threading.Tasks.Task TestClassnameAsync(ModelClient modelClient, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + Org.OpenAPITools.Client.ApiResponse localVarResponse = await TestClassnameWithHttpInfoAsync(modelClient, cancellationToken).ConfigureAwait(false); + return localVarResponse.Data; + } + + /// + /// To test class name in snake case To test class name in snake case + /// + /// Thrown when fails to make API call + /// client model + /// Cancellation Token to cancel the request. + /// Task of ApiResponse (ModelClient) + public async System.Threading.Tasks.Task> TestClassnameWithHttpInfoAsync(ModelClient modelClient, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + // verify the required parameter 'modelClient' is set + if (modelClient == null) + throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'modelClient' when calling FakeClassnameTags123Api->TestClassname"); + + + 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 = modelClient; + + // 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.PatchAsync("/fake_classname_test", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("TestClassname", localVarResponse); + if (_exception != null) throw _exception; + } + + return localVarResponse; + } + + } +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Api/PetApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Api/PetApi.cs new file mode 100644 index 00000000000..2bf19af1b1a --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Api/PetApi.cs @@ -0,0 +1,1884 @@ +/* + * 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.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 IPetApiSync : IApiAccessor + { + #region Synchronous Operations + /// + /// Add a new pet to the store + /// + /// Thrown when fails to make API call + /// Pet object that needs to be added to the store + /// + void AddPet(Pet pet); + + /// + /// Add a new pet to the store + /// + /// + /// + /// + /// Thrown when fails to make API call + /// Pet object that needs to be added to the store + /// ApiResponse of Object(void) + ApiResponse AddPetWithHttpInfo(Pet pet); + /// + /// Deletes a pet + /// + /// Thrown when fails to make API call + /// Pet id to delete + /// (optional) + /// + void DeletePet(long petId, string apiKey = default(string)); + + /// + /// Deletes a pet + /// + /// + /// + /// + /// Thrown when fails to make API call + /// Pet id to delete + /// (optional) + /// ApiResponse of Object(void) + ApiResponse DeletePetWithHttpInfo(long petId, string apiKey = default(string)); + /// + /// Finds Pets by status + /// + /// + /// 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 + /// List<Pet> + List FindPetsByStatus(List status); + + /// + /// Finds Pets by status + /// + /// + /// 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 + /// ApiResponse of List<Pet> + ApiResponse> FindPetsByStatusWithHttpInfo(List status); + /// + /// Finds Pets by tags + /// + /// + /// Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + /// + /// Thrown when fails to make API call + /// Tags to filter by + /// List<Pet> + List FindPetsByTags(List tags); + + /// + /// Finds Pets by tags + /// + /// + /// Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + /// + /// Thrown when fails to make API call + /// Tags to filter by + /// ApiResponse of List<Pet> + ApiResponse> FindPetsByTagsWithHttpInfo(List tags); + /// + /// Find pet by ID + /// + /// + /// Returns a single pet + /// + /// Thrown when fails to make API call + /// ID of pet to return + /// Pet + Pet GetPetById(long petId); + + /// + /// Find pet by ID + /// + /// + /// Returns a single pet + /// + /// Thrown when fails to make API call + /// ID of pet to return + /// ApiResponse of Pet + ApiResponse GetPetByIdWithHttpInfo(long petId); + /// + /// Update an existing pet + /// + /// Thrown when fails to make API call + /// Pet object that needs to be added to the store + /// + void UpdatePet(Pet pet); + + /// + /// Update an existing pet + /// + /// + /// + /// + /// Thrown when fails to make API call + /// Pet object that needs to be added to the store + /// ApiResponse of Object(void) + ApiResponse UpdatePetWithHttpInfo(Pet pet); + /// + /// Updates a pet in the store with form data + /// + /// Thrown when fails to make API call + /// ID of pet that needs to be updated + /// Updated name of the pet (optional) + /// Updated status of the pet (optional) + /// + void UpdatePetWithForm(long petId, string name = default(string), string status = default(string)); + + /// + /// Updates a pet in the store with form data + /// + /// + /// + /// + /// Thrown when fails to make API call + /// ID of pet that needs to be updated + /// Updated name of the pet (optional) + /// Updated status of the pet (optional) + /// ApiResponse of Object(void) + ApiResponse UpdatePetWithFormWithHttpInfo(long petId, string name = default(string), string status = default(string)); + /// + /// uploads an image + /// + /// Thrown when fails to make API call + /// ID of pet to update + /// Additional data to pass to server (optional) + /// file to upload (optional) + /// ApiResponse + ApiResponse UploadFile(long petId, string additionalMetadata = default(string), System.IO.Stream file = default(System.IO.Stream)); + + /// + /// uploads an image + /// + /// + /// + /// + /// Thrown when fails to make API call + /// ID of pet to update + /// Additional data to pass to server (optional) + /// file to upload (optional) + /// ApiResponse of ApiResponse + ApiResponse UploadFileWithHttpInfo(long petId, string additionalMetadata = default(string), System.IO.Stream file = default(System.IO.Stream)); + /// + /// uploads an image (required) + /// + /// Thrown when fails to make API call + /// ID of pet to update + /// file to upload + /// Additional data to pass to server (optional) + /// ApiResponse + ApiResponse UploadFileWithRequiredFile(long petId, System.IO.Stream requiredFile, string additionalMetadata = default(string)); + + /// + /// uploads an image (required) + /// + /// + /// + /// + /// Thrown when fails to make API call + /// ID of pet to update + /// file to upload + /// Additional data to pass to server (optional) + /// ApiResponse of ApiResponse + ApiResponse UploadFileWithRequiredFileWithHttpInfo(long petId, System.IO.Stream requiredFile, string additionalMetadata = default(string)); + #endregion Synchronous Operations + } + + /// + /// Represents a collection of functions to interact with the API endpoints + /// + public interface IPetApiAsync : IApiAccessor + { + #region Asynchronous Operations + /// + /// Add a new pet to the store + /// + /// + /// + /// + /// Thrown when fails to make API call + /// Pet object that needs to be added to the store + /// Cancellation Token to cancel the request. + /// Task of void + System.Threading.Tasks.Task AddPetAsync(Pet pet, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// Add a new pet to the store + /// + /// + /// + /// + /// Thrown when fails to make API call + /// Pet object that needs to be added to the store + /// Cancellation Token to cancel the request. + /// Task of ApiResponse + System.Threading.Tasks.Task> AddPetWithHttpInfoAsync(Pet pet, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + /// + /// Deletes a pet + /// + /// + /// + /// + /// Thrown when fails to make API call + /// Pet id to delete + /// (optional) + /// Cancellation Token to cancel the request. + /// Task of void + System.Threading.Tasks.Task DeletePetAsync(long petId, string apiKey = default(string), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// Deletes a pet + /// + /// + /// + /// + /// Thrown when fails to make API call + /// Pet id to delete + /// (optional) + /// Cancellation Token to cancel the request. + /// Task of ApiResponse + System.Threading.Tasks.Task> DeletePetWithHttpInfoAsync(long petId, string apiKey = default(string), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + /// + /// Finds Pets by status + /// + /// + /// 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 + /// Cancellation Token to cancel the request. + /// Task of List<Pet> + System.Threading.Tasks.Task> FindPetsByStatusAsync(List status, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// Finds Pets by status + /// + /// + /// 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 + /// Cancellation Token to cancel the request. + /// Task of ApiResponse (List<Pet>) + System.Threading.Tasks.Task>> FindPetsByStatusWithHttpInfoAsync(List status, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + /// + /// Finds Pets by tags + /// + /// + /// Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + /// + /// Thrown when fails to make API call + /// Tags to filter by + /// Cancellation Token to cancel the request. + /// Task of List<Pet> + System.Threading.Tasks.Task> FindPetsByTagsAsync(List tags, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// Finds Pets by tags + /// + /// + /// Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + /// + /// Thrown when fails to make API call + /// Tags to filter by + /// Cancellation Token to cancel the request. + /// Task of ApiResponse (List<Pet>) + System.Threading.Tasks.Task>> FindPetsByTagsWithHttpInfoAsync(List tags, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + /// + /// Find pet by ID + /// + /// + /// Returns a single pet + /// + /// Thrown when fails to make API call + /// ID of pet to return + /// Cancellation Token to cancel the request. + /// Task of Pet + System.Threading.Tasks.Task GetPetByIdAsync(long petId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// Find pet by ID + /// + /// + /// Returns a single pet + /// + /// Thrown when fails to make API call + /// ID of pet to return + /// Cancellation Token to cancel the request. + /// Task of ApiResponse (Pet) + System.Threading.Tasks.Task> GetPetByIdWithHttpInfoAsync(long petId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + /// + /// Update an existing pet + /// + /// + /// + /// + /// Thrown when fails to make API call + /// Pet object that needs to be added to the store + /// Cancellation Token to cancel the request. + /// Task of void + System.Threading.Tasks.Task UpdatePetAsync(Pet pet, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// Update an existing pet + /// + /// + /// + /// + /// Thrown when fails to make API call + /// Pet object that needs to be added to the store + /// Cancellation Token to cancel the request. + /// Task of ApiResponse + System.Threading.Tasks.Task> UpdatePetWithHttpInfoAsync(Pet pet, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + /// + /// Updates a pet in the store with form data + /// + /// + /// + /// + /// Thrown when fails to make API call + /// ID of pet that needs to be updated + /// Updated name of the pet (optional) + /// Updated status of the pet (optional) + /// Cancellation Token to cancel the request. + /// Task of void + System.Threading.Tasks.Task UpdatePetWithFormAsync(long petId, string name = default(string), string status = default(string), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// Updates a pet in the store with form data + /// + /// + /// + /// + /// Thrown when fails to make API call + /// ID of pet that needs to be updated + /// Updated name of the pet (optional) + /// Updated status of the pet (optional) + /// Cancellation Token to cancel the request. + /// Task of ApiResponse + System.Threading.Tasks.Task> UpdatePetWithFormWithHttpInfoAsync(long petId, string name = default(string), string status = default(string), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + /// + /// uploads an image + /// + /// + /// + /// + /// Thrown when fails to make API call + /// ID of pet to update + /// Additional data to pass to server (optional) + /// file to upload (optional) + /// Cancellation Token to cancel the request. + /// Task of ApiResponse + System.Threading.Tasks.Task UploadFileAsync(long petId, string additionalMetadata = default(string), System.IO.Stream file = default(System.IO.Stream), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// uploads an image + /// + /// + /// + /// + /// Thrown when fails to make API call + /// ID of pet to update + /// Additional data to pass to server (optional) + /// file to upload (optional) + /// Cancellation Token to cancel the request. + /// Task of ApiResponse (ApiResponse) + System.Threading.Tasks.Task> UploadFileWithHttpInfoAsync(long petId, string additionalMetadata = default(string), System.IO.Stream file = default(System.IO.Stream), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + /// + /// uploads an image (required) + /// + /// + /// + /// + /// Thrown when fails to make API call + /// ID of pet to update + /// file to upload + /// Additional data to pass to server (optional) + /// Cancellation Token to cancel the request. + /// Task of ApiResponse + System.Threading.Tasks.Task UploadFileWithRequiredFileAsync(long petId, System.IO.Stream requiredFile, string additionalMetadata = default(string), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// uploads an image (required) + /// + /// + /// + /// + /// Thrown when fails to make API call + /// ID of pet to update + /// file to upload + /// Additional data to pass to server (optional) + /// Cancellation Token to cancel the request. + /// Task of ApiResponse (ApiResponse) + System.Threading.Tasks.Task> UploadFileWithRequiredFileWithHttpInfoAsync(long petId, System.IO.Stream requiredFile, string additionalMetadata = default(string), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + #endregion Asynchronous Operations + } + + /// + /// Represents a collection of functions to interact with the API endpoints + /// + public interface IPetApi : IPetApiSync, IPetApiAsync + { + + } + + /// + /// Represents a collection of functions to interact with the API endpoints + /// + public partial class PetApi : IPetApi + { + private Org.OpenAPITools.Client.ExceptionFactory _exceptionFactory = (name, response) => null; + + /// + /// Initializes a new instance of the class. + /// + /// + public PetApi() : this((string)null) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// + public PetApi(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 PetApi(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 PetApi(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; } + } + + /// + /// Add a new pet to the store + /// + /// Thrown when fails to make API call + /// Pet object that needs to be added to the store + /// + public void AddPet(Pet pet) + { + AddPetWithHttpInfo(pet); + } + + /// + /// Add a new pet to the store + /// + /// Thrown when fails to make API call + /// Pet object that needs to be added to the store + /// ApiResponse of Object(void) + public Org.OpenAPITools.Client.ApiResponse AddPetWithHttpInfo(Pet pet) + { + // verify the required parameter 'pet' is set + if (pet == null) + throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'pet' when calling PetApi->AddPet"); + + Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + "application/json", + "application/xml" + }; + + // 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 = pet; + + // authentication (http_signature_test) required + if (this.Configuration.HttpSigningConfiguration != null) + { + var HttpSigningHeaders = this.Configuration.HttpSigningConfiguration.GetHttpSignedHeader(this.Configuration.BasePath, "POST", "/pet", localVarRequestOptions); + foreach (var headerItem in HttpSigningHeaders) + { + if (localVarRequestOptions.HeaderParameters.ContainsKey(headerItem.Key)) + { + localVarRequestOptions.HeaderParameters[headerItem.Key] = new List() { headerItem.Value }; + } + else + { + localVarRequestOptions.HeaderParameters.Add(headerItem.Key, headerItem.Value); + } + } + } + // authentication (petstore_auth) required + // oauth required + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + + // make the HTTP request + var localVarResponse = this.Client.Post("/pet", localVarRequestOptions, this.Configuration); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("AddPet", localVarResponse); + if (_exception != null) throw _exception; + } + + return localVarResponse; + } + + /// + /// Add a new pet to the store + /// + /// Thrown when fails to make API call + /// Pet object that needs to be added to the store + /// Cancellation Token to cancel the request. + /// Task of void + public async System.Threading.Tasks.Task AddPetAsync(Pet pet, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + await AddPetWithHttpInfoAsync(pet, cancellationToken).ConfigureAwait(false); + } + + /// + /// Add a new pet to the store + /// + /// Thrown when fails to make API call + /// Pet object that needs to be added to the store + /// Cancellation Token to cancel the request. + /// Task of ApiResponse + public async System.Threading.Tasks.Task> AddPetWithHttpInfoAsync(Pet pet, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + // verify the required parameter 'pet' is set + if (pet == null) + throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'pet' when calling PetApi->AddPet"); + + + Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + "application/json", + "application/xml" + }; + + // 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 = pet; + + // authentication (http_signature_test) required + if (this.Configuration.HttpSigningConfiguration != null) + { + var HttpSigningHeaders = this.Configuration.HttpSigningConfiguration.GetHttpSignedHeader(this.Configuration.BasePath, "POST", "/pet", localVarRequestOptions); + foreach (var headerItem in HttpSigningHeaders) + { + if (localVarRequestOptions.HeaderParameters.ContainsKey(headerItem.Key)) + { + localVarRequestOptions.HeaderParameters[headerItem.Key] = new List() { headerItem.Value }; + } + else + { + localVarRequestOptions.HeaderParameters.Add(headerItem.Key, headerItem.Value); + } + } + } + // authentication (petstore_auth) required + // oauth required + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + + // make the HTTP request + + var localVarResponse = await this.AsynchronousClient.PostAsync("/pet", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("AddPet", localVarResponse); + if (_exception != null) throw _exception; + } + + return localVarResponse; + } + + /// + /// Deletes a pet + /// + /// Thrown when fails to make API call + /// Pet id to delete + /// (optional) + /// + public void DeletePet(long petId, string apiKey = default(string)) + { + DeletePetWithHttpInfo(petId, apiKey); + } + + /// + /// Deletes a pet + /// + /// Thrown when fails to make API call + /// Pet id to delete + /// (optional) + /// ApiResponse of Object(void) + public Org.OpenAPITools.Client.ApiResponse DeletePetWithHttpInfo(long petId, string apiKey = default(string)) + { + Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + }; + + // 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.PathParameters.Add("petId", Org.OpenAPITools.Client.ClientUtils.ParameterToString(petId)); // path parameter + if (apiKey != null) + { + localVarRequestOptions.HeaderParameters.Add("api_key", Org.OpenAPITools.Client.ClientUtils.ParameterToString(apiKey)); // header parameter + } + + // authentication (petstore_auth) required + // oauth required + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + + // make the HTTP request + var localVarResponse = this.Client.Delete("/pet/{petId}", localVarRequestOptions, this.Configuration); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("DeletePet", localVarResponse); + if (_exception != null) throw _exception; + } + + return localVarResponse; + } + + /// + /// Deletes a pet + /// + /// Thrown when fails to make API call + /// Pet id to delete + /// (optional) + /// Cancellation Token to cancel the request. + /// Task of void + public async System.Threading.Tasks.Task DeletePetAsync(long petId, string apiKey = default(string), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + await DeletePetWithHttpInfoAsync(petId, apiKey, cancellationToken).ConfigureAwait(false); + } + + /// + /// Deletes a pet + /// + /// Thrown when fails to make API call + /// Pet id to delete + /// (optional) + /// Cancellation Token to cancel the request. + /// Task of ApiResponse + public async System.Threading.Tasks.Task> DeletePetWithHttpInfoAsync(long petId, string apiKey = default(string), 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[] { + }; + + + 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.PathParameters.Add("petId", Org.OpenAPITools.Client.ClientUtils.ParameterToString(petId)); // path parameter + if (apiKey != null) + { + localVarRequestOptions.HeaderParameters.Add("api_key", Org.OpenAPITools.Client.ClientUtils.ParameterToString(apiKey)); // header parameter + } + + // authentication (petstore_auth) required + // oauth required + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + + // make the HTTP request + + var localVarResponse = await this.AsynchronousClient.DeleteAsync("/pet/{petId}", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("DeletePet", localVarResponse); + if (_exception != null) throw _exception; + } + + return localVarResponse; + } + + /// + /// Finds Pets by status 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 + /// List<Pet> + public List FindPetsByStatus(List status) + { + Org.OpenAPITools.Client.ApiResponse> localVarResponse = FindPetsByStatusWithHttpInfo(status); + return localVarResponse.Data; + } + + /// + /// Finds Pets by status 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 + /// ApiResponse of List<Pet> + public Org.OpenAPITools.Client.ApiResponse> FindPetsByStatusWithHttpInfo(List status) + { + // verify the required parameter 'status' is set + if (status == null) + throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'status' when calling PetApi->FindPetsByStatus"); + + Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + }; + + // to determine the Accept header + string[] _accepts = new string[] { + "application/xml", + "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.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("csv", "status", status)); + + // authentication (http_signature_test) required + if (this.Configuration.HttpSigningConfiguration != null) + { + var HttpSigningHeaders = this.Configuration.HttpSigningConfiguration.GetHttpSignedHeader(this.Configuration.BasePath, "GET", "/pet/findByStatus", localVarRequestOptions); + foreach (var headerItem in HttpSigningHeaders) + { + if (localVarRequestOptions.HeaderParameters.ContainsKey(headerItem.Key)) + { + localVarRequestOptions.HeaderParameters[headerItem.Key] = new List() { headerItem.Value }; + } + else + { + localVarRequestOptions.HeaderParameters.Add(headerItem.Key, headerItem.Value); + } + } + } + // authentication (petstore_auth) required + // oauth required + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + + // make the HTTP request + var localVarResponse = this.Client.Get>("/pet/findByStatus", localVarRequestOptions, this.Configuration); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("FindPetsByStatus", localVarResponse); + if (_exception != null) throw _exception; + } + + return localVarResponse; + } + + /// + /// Finds Pets by status 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 + /// Cancellation Token to cancel the request. + /// Task of List<Pet> + public async System.Threading.Tasks.Task> FindPetsByStatusAsync(List status, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + Org.OpenAPITools.Client.ApiResponse> localVarResponse = await FindPetsByStatusWithHttpInfoAsync(status, cancellationToken).ConfigureAwait(false); + return localVarResponse.Data; + } + + /// + /// Finds Pets by status 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 + /// Cancellation Token to cancel the request. + /// Task of ApiResponse (List<Pet>) + public async System.Threading.Tasks.Task>> FindPetsByStatusWithHttpInfoAsync(List status, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + // verify the required parameter 'status' is set + if (status == null) + throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'status' when calling PetApi->FindPetsByStatus"); + + + Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + }; + + // to determine the Accept header + string[] _accepts = new string[] { + "application/xml", + "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.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("csv", "status", status)); + + // authentication (http_signature_test) required + if (this.Configuration.HttpSigningConfiguration != null) + { + var HttpSigningHeaders = this.Configuration.HttpSigningConfiguration.GetHttpSignedHeader(this.Configuration.BasePath, "GET", "/pet/findByStatus", localVarRequestOptions); + foreach (var headerItem in HttpSigningHeaders) + { + if (localVarRequestOptions.HeaderParameters.ContainsKey(headerItem.Key)) + { + localVarRequestOptions.HeaderParameters[headerItem.Key] = new List() { headerItem.Value }; + } + else + { + localVarRequestOptions.HeaderParameters.Add(headerItem.Key, headerItem.Value); + } + } + } + // authentication (petstore_auth) required + // oauth required + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + + // make the HTTP request + + var localVarResponse = await this.AsynchronousClient.GetAsync>("/pet/findByStatus", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("FindPetsByStatus", localVarResponse); + if (_exception != null) throw _exception; + } + + return localVarResponse; + } + + /// + /// Finds Pets by tags Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + /// + /// Thrown when fails to make API call + /// Tags to filter by + /// List<Pet> + public List FindPetsByTags(List tags) + { + Org.OpenAPITools.Client.ApiResponse> localVarResponse = FindPetsByTagsWithHttpInfo(tags); + return localVarResponse.Data; + } + + /// + /// Finds Pets by tags Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + /// + /// Thrown when fails to make API call + /// Tags to filter by + /// ApiResponse of List<Pet> + public Org.OpenAPITools.Client.ApiResponse> FindPetsByTagsWithHttpInfo(List tags) + { + // verify the required parameter 'tags' is set + if (tags == null) + throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'tags' when calling PetApi->FindPetsByTags"); + + Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + }; + + // to determine the Accept header + string[] _accepts = new string[] { + "application/xml", + "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.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("csv", "tags", tags)); + + // authentication (http_signature_test) required + if (this.Configuration.HttpSigningConfiguration != null) + { + var HttpSigningHeaders = this.Configuration.HttpSigningConfiguration.GetHttpSignedHeader(this.Configuration.BasePath, "GET", "/pet/findByTags", localVarRequestOptions); + foreach (var headerItem in HttpSigningHeaders) + { + if (localVarRequestOptions.HeaderParameters.ContainsKey(headerItem.Key)) + { + localVarRequestOptions.HeaderParameters[headerItem.Key] = new List() { headerItem.Value }; + } + else + { + localVarRequestOptions.HeaderParameters.Add(headerItem.Key, headerItem.Value); + } + } + } + // authentication (petstore_auth) required + // oauth required + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + + // make the HTTP request + var localVarResponse = this.Client.Get>("/pet/findByTags", localVarRequestOptions, this.Configuration); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("FindPetsByTags", localVarResponse); + if (_exception != null) throw _exception; + } + + return localVarResponse; + } + + /// + /// Finds Pets by tags Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + /// + /// Thrown when fails to make API call + /// Tags to filter by + /// Cancellation Token to cancel the request. + /// Task of List<Pet> + public async System.Threading.Tasks.Task> FindPetsByTagsAsync(List tags, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + Org.OpenAPITools.Client.ApiResponse> localVarResponse = await FindPetsByTagsWithHttpInfoAsync(tags, cancellationToken).ConfigureAwait(false); + return localVarResponse.Data; + } + + /// + /// Finds Pets by tags Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + /// + /// Thrown when fails to make API call + /// Tags to filter by + /// Cancellation Token to cancel the request. + /// Task of ApiResponse (List<Pet>) + public async System.Threading.Tasks.Task>> FindPetsByTagsWithHttpInfoAsync(List tags, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + // verify the required parameter 'tags' is set + if (tags == null) + throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'tags' when calling PetApi->FindPetsByTags"); + + + Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + }; + + // to determine the Accept header + string[] _accepts = new string[] { + "application/xml", + "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.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("csv", "tags", tags)); + + // authentication (http_signature_test) required + if (this.Configuration.HttpSigningConfiguration != null) + { + var HttpSigningHeaders = this.Configuration.HttpSigningConfiguration.GetHttpSignedHeader(this.Configuration.BasePath, "GET", "/pet/findByTags", localVarRequestOptions); + foreach (var headerItem in HttpSigningHeaders) + { + if (localVarRequestOptions.HeaderParameters.ContainsKey(headerItem.Key)) + { + localVarRequestOptions.HeaderParameters[headerItem.Key] = new List() { headerItem.Value }; + } + else + { + localVarRequestOptions.HeaderParameters.Add(headerItem.Key, headerItem.Value); + } + } + } + // authentication (petstore_auth) required + // oauth required + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + + // make the HTTP request + + var localVarResponse = await this.AsynchronousClient.GetAsync>("/pet/findByTags", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("FindPetsByTags", localVarResponse); + if (_exception != null) throw _exception; + } + + return localVarResponse; + } + + /// + /// Find pet by ID Returns a single pet + /// + /// Thrown when fails to make API call + /// ID of pet to return + /// Pet + public Pet GetPetById(long petId) + { + Org.OpenAPITools.Client.ApiResponse localVarResponse = GetPetByIdWithHttpInfo(petId); + return localVarResponse.Data; + } + + /// + /// Find pet by ID Returns a single pet + /// + /// Thrown when fails to make API call + /// ID of pet to return + /// ApiResponse of Pet + public Org.OpenAPITools.Client.ApiResponse GetPetByIdWithHttpInfo(long petId) + { + Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + }; + + // to determine the Accept header + string[] _accepts = new string[] { + "application/xml", + "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.PathParameters.Add("petId", Org.OpenAPITools.Client.ClientUtils.ParameterToString(petId)); // path parameter + + // authentication (api_key) required + if (!string.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("api_key"))) + { + localVarRequestOptions.HeaderParameters.Add("api_key", this.Configuration.GetApiKeyWithPrefix("api_key")); + } + + // make the HTTP request + var localVarResponse = this.Client.Get("/pet/{petId}", localVarRequestOptions, this.Configuration); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("GetPetById", localVarResponse); + if (_exception != null) throw _exception; + } + + return localVarResponse; + } + + /// + /// Find pet by ID Returns a single pet + /// + /// Thrown when fails to make API call + /// ID of pet to return + /// Cancellation Token to cancel the request. + /// Task of Pet + public async System.Threading.Tasks.Task GetPetByIdAsync(long petId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + Org.OpenAPITools.Client.ApiResponse localVarResponse = await GetPetByIdWithHttpInfoAsync(petId, cancellationToken).ConfigureAwait(false); + return localVarResponse.Data; + } + + /// + /// Find pet by ID Returns a single pet + /// + /// Thrown when fails to make API call + /// ID of pet to return + /// Cancellation Token to cancel the request. + /// Task of ApiResponse (Pet) + public async System.Threading.Tasks.Task> GetPetByIdWithHttpInfoAsync(long petId, 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/xml", + "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.PathParameters.Add("petId", Org.OpenAPITools.Client.ClientUtils.ParameterToString(petId)); // path parameter + + // authentication (api_key) required + if (!string.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("api_key"))) + { + localVarRequestOptions.HeaderParameters.Add("api_key", this.Configuration.GetApiKeyWithPrefix("api_key")); + } + + // make the HTTP request + + var localVarResponse = await this.AsynchronousClient.GetAsync("/pet/{petId}", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("GetPetById", localVarResponse); + if (_exception != null) throw _exception; + } + + return localVarResponse; + } + + /// + /// Update an existing pet + /// + /// Thrown when fails to make API call + /// Pet object that needs to be added to the store + /// + public void UpdatePet(Pet pet) + { + UpdatePetWithHttpInfo(pet); + } + + /// + /// Update an existing pet + /// + /// Thrown when fails to make API call + /// Pet object that needs to be added to the store + /// ApiResponse of Object(void) + public Org.OpenAPITools.Client.ApiResponse UpdatePetWithHttpInfo(Pet pet) + { + // verify the required parameter 'pet' is set + if (pet == null) + throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'pet' when calling PetApi->UpdatePet"); + + Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + "application/json", + "application/xml" + }; + + // 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 = pet; + + // authentication (http_signature_test) required + if (this.Configuration.HttpSigningConfiguration != null) + { + var HttpSigningHeaders = this.Configuration.HttpSigningConfiguration.GetHttpSignedHeader(this.Configuration.BasePath, "PUT", "/pet", localVarRequestOptions); + foreach (var headerItem in HttpSigningHeaders) + { + if (localVarRequestOptions.HeaderParameters.ContainsKey(headerItem.Key)) + { + localVarRequestOptions.HeaderParameters[headerItem.Key] = new List() { headerItem.Value }; + } + else + { + localVarRequestOptions.HeaderParameters.Add(headerItem.Key, headerItem.Value); + } + } + } + // authentication (petstore_auth) required + // oauth required + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + + // make the HTTP request + var localVarResponse = this.Client.Put("/pet", localVarRequestOptions, this.Configuration); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("UpdatePet", localVarResponse); + if (_exception != null) throw _exception; + } + + return localVarResponse; + } + + /// + /// Update an existing pet + /// + /// Thrown when fails to make API call + /// Pet object that needs to be added to the store + /// Cancellation Token to cancel the request. + /// Task of void + public async System.Threading.Tasks.Task UpdatePetAsync(Pet pet, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + await UpdatePetWithHttpInfoAsync(pet, cancellationToken).ConfigureAwait(false); + } + + /// + /// Update an existing pet + /// + /// Thrown when fails to make API call + /// Pet object that needs to be added to the store + /// Cancellation Token to cancel the request. + /// Task of ApiResponse + public async System.Threading.Tasks.Task> UpdatePetWithHttpInfoAsync(Pet pet, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + // verify the required parameter 'pet' is set + if (pet == null) + throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'pet' when calling PetApi->UpdatePet"); + + + Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + "application/json", + "application/xml" + }; + + // 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 = pet; + + // authentication (http_signature_test) required + if (this.Configuration.HttpSigningConfiguration != null) + { + var HttpSigningHeaders = this.Configuration.HttpSigningConfiguration.GetHttpSignedHeader(this.Configuration.BasePath, "PUT", "/pet", localVarRequestOptions); + foreach (var headerItem in HttpSigningHeaders) + { + if (localVarRequestOptions.HeaderParameters.ContainsKey(headerItem.Key)) + { + localVarRequestOptions.HeaderParameters[headerItem.Key] = new List() { headerItem.Value }; + } + else + { + localVarRequestOptions.HeaderParameters.Add(headerItem.Key, headerItem.Value); + } + } + } + // authentication (petstore_auth) required + // oauth required + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + + // make the HTTP request + + var localVarResponse = await this.AsynchronousClient.PutAsync("/pet", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("UpdatePet", localVarResponse); + if (_exception != null) throw _exception; + } + + return localVarResponse; + } + + /// + /// Updates a pet in the store with form data + /// + /// Thrown when fails to make API call + /// ID of pet that needs to be updated + /// Updated name of the pet (optional) + /// Updated status of the pet (optional) + /// + public void UpdatePetWithForm(long petId, string name = default(string), string status = default(string)) + { + UpdatePetWithFormWithHttpInfo(petId, name, status); + } + + /// + /// Updates a pet in the store with form data + /// + /// Thrown when fails to make API call + /// ID of pet that needs to be updated + /// Updated name of the pet (optional) + /// Updated status of the pet (optional) + /// ApiResponse of Object(void) + public Org.OpenAPITools.Client.ApiResponse UpdatePetWithFormWithHttpInfo(long petId, string name = default(string), string status = default(string)) + { + Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + "application/x-www-form-urlencoded" + }; + + // 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.PathParameters.Add("petId", Org.OpenAPITools.Client.ClientUtils.ParameterToString(petId)); // path parameter + if (name != null) + { + localVarRequestOptions.FormParameters.Add("name", Org.OpenAPITools.Client.ClientUtils.ParameterToString(name)); // form parameter + } + if (status != null) + { + localVarRequestOptions.FormParameters.Add("status", Org.OpenAPITools.Client.ClientUtils.ParameterToString(status)); // form parameter + } + + // authentication (petstore_auth) required + // oauth required + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + + // make the HTTP request + var localVarResponse = this.Client.Post("/pet/{petId}", localVarRequestOptions, this.Configuration); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("UpdatePetWithForm", localVarResponse); + if (_exception != null) throw _exception; + } + + return localVarResponse; + } + + /// + /// Updates a pet in the store with form data + /// + /// Thrown when fails to make API call + /// ID of pet that needs to be updated + /// Updated name of the pet (optional) + /// Updated status of the pet (optional) + /// Cancellation Token to cancel the request. + /// Task of void + public async System.Threading.Tasks.Task UpdatePetWithFormAsync(long petId, string name = default(string), string status = default(string), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + await UpdatePetWithFormWithHttpInfoAsync(petId, name, status, cancellationToken).ConfigureAwait(false); + } + + /// + /// Updates a pet in the store with form data + /// + /// Thrown when fails to make API call + /// ID of pet that needs to be updated + /// Updated name of the pet (optional) + /// Updated status of the pet (optional) + /// Cancellation Token to cancel the request. + /// Task of ApiResponse + public async System.Threading.Tasks.Task> UpdatePetWithFormWithHttpInfoAsync(long petId, string name = default(string), string status = default(string), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + + Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + "application/x-www-form-urlencoded" + }; + + // 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.PathParameters.Add("petId", Org.OpenAPITools.Client.ClientUtils.ParameterToString(petId)); // path parameter + if (name != null) + { + localVarRequestOptions.FormParameters.Add("name", Org.OpenAPITools.Client.ClientUtils.ParameterToString(name)); // form parameter + } + if (status != null) + { + localVarRequestOptions.FormParameters.Add("status", Org.OpenAPITools.Client.ClientUtils.ParameterToString(status)); // form parameter + } + + // authentication (petstore_auth) required + // oauth required + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + + // make the HTTP request + + var localVarResponse = await this.AsynchronousClient.PostAsync("/pet/{petId}", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("UpdatePetWithForm", localVarResponse); + if (_exception != null) throw _exception; + } + + return localVarResponse; + } + + /// + /// uploads an image + /// + /// Thrown when fails to make API call + /// ID of pet to update + /// Additional data to pass to server (optional) + /// file to upload (optional) + /// ApiResponse + public ApiResponse UploadFile(long petId, string additionalMetadata = default(string), System.IO.Stream file = default(System.IO.Stream)) + { + Org.OpenAPITools.Client.ApiResponse localVarResponse = UploadFileWithHttpInfo(petId, additionalMetadata, file); + return localVarResponse.Data; + } + + /// + /// uploads an image + /// + /// Thrown when fails to make API call + /// ID of pet to update + /// Additional data to pass to server (optional) + /// file to upload (optional) + /// ApiResponse of ApiResponse + public Org.OpenAPITools.Client.ApiResponse UploadFileWithHttpInfo(long petId, string additionalMetadata = default(string), System.IO.Stream file = default(System.IO.Stream)) + { + 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[] { + "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.PathParameters.Add("petId", Org.OpenAPITools.Client.ClientUtils.ParameterToString(petId)); // path parameter + if (additionalMetadata != null) + { + localVarRequestOptions.FormParameters.Add("additionalMetadata", Org.OpenAPITools.Client.ClientUtils.ParameterToString(additionalMetadata)); // form parameter + } + if (file != null) + { + localVarRequestOptions.FileParameters.Add("file", file); + } + + // authentication (petstore_auth) required + // oauth required + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + + // make the HTTP request + var localVarResponse = this.Client.Post("/pet/{petId}/uploadImage", localVarRequestOptions, this.Configuration); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("UploadFile", localVarResponse); + if (_exception != null) throw _exception; + } + + return localVarResponse; + } + + /// + /// uploads an image + /// + /// Thrown when fails to make API call + /// ID of pet to update + /// Additional data to pass to server (optional) + /// file to upload (optional) + /// Cancellation Token to cancel the request. + /// Task of ApiResponse + public async System.Threading.Tasks.Task UploadFileAsync(long petId, string additionalMetadata = default(string), System.IO.Stream file = default(System.IO.Stream), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + Org.OpenAPITools.Client.ApiResponse localVarResponse = await UploadFileWithHttpInfoAsync(petId, additionalMetadata, file, cancellationToken).ConfigureAwait(false); + return localVarResponse.Data; + } + + /// + /// uploads an image + /// + /// Thrown when fails to make API call + /// ID of pet to update + /// Additional data to pass to server (optional) + /// file to upload (optional) + /// Cancellation Token to cancel the request. + /// Task of ApiResponse (ApiResponse) + public async System.Threading.Tasks.Task> UploadFileWithHttpInfoAsync(long petId, string additionalMetadata = default(string), System.IO.Stream file = default(System.IO.Stream), 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[] { + "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.PathParameters.Add("petId", Org.OpenAPITools.Client.ClientUtils.ParameterToString(petId)); // path parameter + if (additionalMetadata != null) + { + localVarRequestOptions.FormParameters.Add("additionalMetadata", Org.OpenAPITools.Client.ClientUtils.ParameterToString(additionalMetadata)); // form parameter + } + if (file != null) + { + localVarRequestOptions.FileParameters.Add("file", file); + } + + // authentication (petstore_auth) required + // oauth required + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + + // make the HTTP request + + var localVarResponse = await this.AsynchronousClient.PostAsync("/pet/{petId}/uploadImage", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("UploadFile", localVarResponse); + if (_exception != null) throw _exception; + } + + return localVarResponse; + } + + /// + /// uploads an image (required) + /// + /// Thrown when fails to make API call + /// ID of pet to update + /// file to upload + /// Additional data to pass to server (optional) + /// ApiResponse + public ApiResponse UploadFileWithRequiredFile(long petId, System.IO.Stream requiredFile, string additionalMetadata = default(string)) + { + Org.OpenAPITools.Client.ApiResponse localVarResponse = UploadFileWithRequiredFileWithHttpInfo(petId, requiredFile, additionalMetadata); + return localVarResponse.Data; + } + + /// + /// uploads an image (required) + /// + /// Thrown when fails to make API call + /// ID of pet to update + /// file to upload + /// Additional data to pass to server (optional) + /// ApiResponse of ApiResponse + public Org.OpenAPITools.Client.ApiResponse UploadFileWithRequiredFileWithHttpInfo(long petId, System.IO.Stream requiredFile, string additionalMetadata = default(string)) + { + // verify the required parameter 'requiredFile' is set + if (requiredFile == null) + throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'requiredFile' when calling PetApi->UploadFileWithRequiredFile"); + + 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[] { + "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.PathParameters.Add("petId", Org.OpenAPITools.Client.ClientUtils.ParameterToString(petId)); // path parameter + if (additionalMetadata != null) + { + localVarRequestOptions.FormParameters.Add("additionalMetadata", Org.OpenAPITools.Client.ClientUtils.ParameterToString(additionalMetadata)); // form parameter + } + localVarRequestOptions.FileParameters.Add("requiredFile", requiredFile); + + // authentication (petstore_auth) required + // oauth required + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + + // make the HTTP request + var localVarResponse = this.Client.Post("/fake/{petId}/uploadImageWithRequiredFile", localVarRequestOptions, this.Configuration); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("UploadFileWithRequiredFile", localVarResponse); + if (_exception != null) throw _exception; + } + + return localVarResponse; + } + + /// + /// uploads an image (required) + /// + /// Thrown when fails to make API call + /// ID of pet to update + /// file to upload + /// Additional data to pass to server (optional) + /// Cancellation Token to cancel the request. + /// Task of ApiResponse + public async System.Threading.Tasks.Task UploadFileWithRequiredFileAsync(long petId, System.IO.Stream requiredFile, string additionalMetadata = default(string), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + Org.OpenAPITools.Client.ApiResponse localVarResponse = await UploadFileWithRequiredFileWithHttpInfoAsync(petId, requiredFile, additionalMetadata, cancellationToken).ConfigureAwait(false); + return localVarResponse.Data; + } + + /// + /// uploads an image (required) + /// + /// Thrown when fails to make API call + /// ID of pet to update + /// file to upload + /// Additional data to pass to server (optional) + /// Cancellation Token to cancel the request. + /// Task of ApiResponse (ApiResponse) + public async System.Threading.Tasks.Task> UploadFileWithRequiredFileWithHttpInfoAsync(long petId, System.IO.Stream requiredFile, string additionalMetadata = default(string), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + // verify the required parameter 'requiredFile' is set + if (requiredFile == null) + throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'requiredFile' when calling PetApi->UploadFileWithRequiredFile"); + + + 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[] { + "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.PathParameters.Add("petId", Org.OpenAPITools.Client.ClientUtils.ParameterToString(petId)); // path parameter + if (additionalMetadata != null) + { + localVarRequestOptions.FormParameters.Add("additionalMetadata", Org.OpenAPITools.Client.ClientUtils.ParameterToString(additionalMetadata)); // form parameter + } + localVarRequestOptions.FileParameters.Add("requiredFile", requiredFile); + + // authentication (petstore_auth) required + // oauth required + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + + // make the HTTP request + + var localVarResponse = await this.AsynchronousClient.PostAsync("/fake/{petId}/uploadImageWithRequiredFile", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("UploadFileWithRequiredFile", localVarResponse); + if (_exception != null) throw _exception; + } + + return localVarResponse; + } + + } +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Api/StoreApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Api/StoreApi.cs new file mode 100644 index 00000000000..ad7387db705 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Api/StoreApi.cs @@ -0,0 +1,778 @@ +/* + * 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.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 IStoreApiSync : IApiAccessor + { + #region Synchronous Operations + /// + /// Delete purchase order by ID + /// + /// + /// For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + /// + /// Thrown when fails to make API call + /// ID of the order that needs to be deleted + /// + void DeleteOrder(string orderId); + + /// + /// Delete purchase order by ID + /// + /// + /// For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + /// + /// Thrown when fails to make API call + /// ID of the order that needs to be deleted + /// ApiResponse of Object(void) + ApiResponse DeleteOrderWithHttpInfo(string orderId); + /// + /// Returns pet inventories by status + /// + /// + /// Returns a map of status codes to quantities + /// + /// Thrown when fails to make API call + /// Dictionary<string, int> + Dictionary GetInventory(); + + /// + /// Returns pet inventories by status + /// + /// + /// Returns a map of status codes to quantities + /// + /// Thrown when fails to make API call + /// ApiResponse of Dictionary<string, int> + ApiResponse> GetInventoryWithHttpInfo(); + /// + /// Find purchase order by ID + /// + /// + /// For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + /// + /// Thrown when fails to make API call + /// ID of pet that needs to be fetched + /// Order + Order GetOrderById(long orderId); + + /// + /// Find purchase order by ID + /// + /// + /// For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + /// + /// Thrown when fails to make API call + /// ID of pet that needs to be fetched + /// ApiResponse of Order + ApiResponse GetOrderByIdWithHttpInfo(long orderId); + /// + /// Place an order for a pet + /// + /// Thrown when fails to make API call + /// order placed for purchasing the pet + /// Order + Order PlaceOrder(Order order); + + /// + /// Place an order for a pet + /// + /// + /// + /// + /// Thrown when fails to make API call + /// order placed for purchasing the pet + /// ApiResponse of Order + ApiResponse PlaceOrderWithHttpInfo(Order order); + #endregion Synchronous Operations + } + + /// + /// Represents a collection of functions to interact with the API endpoints + /// + public interface IStoreApiAsync : IApiAccessor + { + #region Asynchronous Operations + /// + /// Delete purchase order by ID + /// + /// + /// For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + /// + /// Thrown when fails to make API call + /// ID of the order that needs to be deleted + /// Cancellation Token to cancel the request. + /// Task of void + System.Threading.Tasks.Task DeleteOrderAsync(string orderId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// Delete purchase order by ID + /// + /// + /// For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + /// + /// Thrown when fails to make API call + /// ID of the order that needs to be deleted + /// Cancellation Token to cancel the request. + /// Task of ApiResponse + System.Threading.Tasks.Task> DeleteOrderWithHttpInfoAsync(string orderId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + /// + /// Returns pet inventories by status + /// + /// + /// Returns a map of status codes to quantities + /// + /// Thrown when fails to make API call + /// Cancellation Token to cancel the request. + /// Task of Dictionary<string, int> + System.Threading.Tasks.Task> GetInventoryAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// Returns pet inventories by status + /// + /// + /// Returns a map of status codes to quantities + /// + /// Thrown when fails to make API call + /// Cancellation Token to cancel the request. + /// Task of ApiResponse (Dictionary<string, int>) + System.Threading.Tasks.Task>> GetInventoryWithHttpInfoAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + /// + /// Find purchase order by ID + /// + /// + /// For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + /// + /// Thrown when fails to make API call + /// ID of pet that needs to be fetched + /// Cancellation Token to cancel the request. + /// Task of Order + System.Threading.Tasks.Task GetOrderByIdAsync(long orderId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// Find purchase order by ID + /// + /// + /// For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + /// + /// Thrown when fails to make API call + /// ID of pet that needs to be fetched + /// Cancellation Token to cancel the request. + /// Task of ApiResponse (Order) + System.Threading.Tasks.Task> GetOrderByIdWithHttpInfoAsync(long orderId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + /// + /// Place an order for a pet + /// + /// + /// + /// + /// Thrown when fails to make API call + /// order placed for purchasing the pet + /// Cancellation Token to cancel the request. + /// Task of Order + System.Threading.Tasks.Task PlaceOrderAsync(Order order, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// Place an order for a pet + /// + /// + /// + /// + /// Thrown when fails to make API call + /// order placed for purchasing the pet + /// Cancellation Token to cancel the request. + /// Task of ApiResponse (Order) + System.Threading.Tasks.Task> PlaceOrderWithHttpInfoAsync(Order order, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + #endregion Asynchronous Operations + } + + /// + /// Represents a collection of functions to interact with the API endpoints + /// + public interface IStoreApi : IStoreApiSync, IStoreApiAsync + { + + } + + /// + /// Represents a collection of functions to interact with the API endpoints + /// + public partial class StoreApi : IStoreApi + { + private Org.OpenAPITools.Client.ExceptionFactory _exceptionFactory = (name, response) => null; + + /// + /// Initializes a new instance of the class. + /// + /// + public StoreApi() : this((string)null) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// + public StoreApi(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 StoreApi(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 StoreApi(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; } + } + + /// + /// Delete purchase order by ID For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + /// + /// Thrown when fails to make API call + /// ID of the order that needs to be deleted + /// + public void DeleteOrder(string orderId) + { + DeleteOrderWithHttpInfo(orderId); + } + + /// + /// Delete purchase order by ID For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + /// + /// Thrown when fails to make API call + /// ID of the order that needs to be deleted + /// ApiResponse of Object(void) + public Org.OpenAPITools.Client.ApiResponse DeleteOrderWithHttpInfo(string orderId) + { + // verify the required parameter 'orderId' is set + if (orderId == null) + throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'orderId' when calling StoreApi->DeleteOrder"); + + Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + }; + + // 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.PathParameters.Add("order_id", Org.OpenAPITools.Client.ClientUtils.ParameterToString(orderId)); // path parameter + + + // make the HTTP request + var localVarResponse = this.Client.Delete("/store/order/{order_id}", localVarRequestOptions, this.Configuration); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("DeleteOrder", localVarResponse); + if (_exception != null) throw _exception; + } + + return localVarResponse; + } + + /// + /// Delete purchase order by ID For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + /// + /// Thrown when fails to make API call + /// ID of the order that needs to be deleted + /// Cancellation Token to cancel the request. + /// Task of void + public async System.Threading.Tasks.Task DeleteOrderAsync(string orderId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + await DeleteOrderWithHttpInfoAsync(orderId, cancellationToken).ConfigureAwait(false); + } + + /// + /// Delete purchase order by ID For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + /// + /// Thrown when fails to make API call + /// ID of the order that needs to be deleted + /// Cancellation Token to cancel the request. + /// Task of ApiResponse + public async System.Threading.Tasks.Task> DeleteOrderWithHttpInfoAsync(string orderId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + // verify the required parameter 'orderId' is set + if (orderId == null) + throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'orderId' when calling StoreApi->DeleteOrder"); + + + Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + }; + + // 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.PathParameters.Add("order_id", Org.OpenAPITools.Client.ClientUtils.ParameterToString(orderId)); // path parameter + + + // make the HTTP request + + var localVarResponse = await this.AsynchronousClient.DeleteAsync("/store/order/{order_id}", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("DeleteOrder", localVarResponse); + if (_exception != null) throw _exception; + } + + return localVarResponse; + } + + /// + /// Returns pet inventories by status Returns a map of status codes to quantities + /// + /// Thrown when fails to make API call + /// Dictionary<string, int> + public Dictionary GetInventory() + { + Org.OpenAPITools.Client.ApiResponse> localVarResponse = GetInventoryWithHttpInfo(); + return localVarResponse.Data; + } + + /// + /// Returns pet inventories by status Returns a map of status codes to quantities + /// + /// Thrown when fails to make API call + /// ApiResponse of Dictionary<string, int> + public Org.OpenAPITools.Client.ApiResponse> GetInventoryWithHttpInfo() + { + 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); + + + // authentication (api_key) required + if (!string.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("api_key"))) + { + localVarRequestOptions.HeaderParameters.Add("api_key", this.Configuration.GetApiKeyWithPrefix("api_key")); + } + + // make the HTTP request + var localVarResponse = this.Client.Get>("/store/inventory", localVarRequestOptions, this.Configuration); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("GetInventory", localVarResponse); + if (_exception != null) throw _exception; + } + + return localVarResponse; + } + + /// + /// Returns pet inventories by status Returns a map of status codes to quantities + /// + /// Thrown when fails to make API call + /// Cancellation Token to cancel the request. + /// Task of Dictionary<string, int> + public async System.Threading.Tasks.Task> GetInventoryAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + Org.OpenAPITools.Client.ApiResponse> localVarResponse = await GetInventoryWithHttpInfoAsync(cancellationToken).ConfigureAwait(false); + return localVarResponse.Data; + } + + /// + /// Returns pet inventories by status Returns a map of status codes to quantities + /// + /// Thrown when fails to make API call + /// Cancellation Token to cancel the request. + /// Task of ApiResponse (Dictionary<string, int>) + public async System.Threading.Tasks.Task>> GetInventoryWithHttpInfoAsync(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); + + + // authentication (api_key) required + if (!string.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("api_key"))) + { + localVarRequestOptions.HeaderParameters.Add("api_key", this.Configuration.GetApiKeyWithPrefix("api_key")); + } + + // make the HTTP request + + var localVarResponse = await this.AsynchronousClient.GetAsync>("/store/inventory", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("GetInventory", localVarResponse); + if (_exception != null) throw _exception; + } + + return localVarResponse; + } + + /// + /// Find purchase order by ID For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + /// + /// Thrown when fails to make API call + /// ID of pet that needs to be fetched + /// Order + public Order GetOrderById(long orderId) + { + Org.OpenAPITools.Client.ApiResponse localVarResponse = GetOrderByIdWithHttpInfo(orderId); + return localVarResponse.Data; + } + + /// + /// Find purchase order by ID For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + /// + /// Thrown when fails to make API call + /// ID of pet that needs to be fetched + /// ApiResponse of Order + public Org.OpenAPITools.Client.ApiResponse GetOrderByIdWithHttpInfo(long orderId) + { + Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + }; + + // to determine the Accept header + string[] _accepts = new string[] { + "application/xml", + "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.PathParameters.Add("order_id", Org.OpenAPITools.Client.ClientUtils.ParameterToString(orderId)); // path parameter + + + // make the HTTP request + var localVarResponse = this.Client.Get("/store/order/{order_id}", localVarRequestOptions, this.Configuration); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("GetOrderById", localVarResponse); + if (_exception != null) throw _exception; + } + + return localVarResponse; + } + + /// + /// Find purchase order by ID For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + /// + /// Thrown when fails to make API call + /// ID of pet that needs to be fetched + /// Cancellation Token to cancel the request. + /// Task of Order + public async System.Threading.Tasks.Task GetOrderByIdAsync(long orderId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + Org.OpenAPITools.Client.ApiResponse localVarResponse = await GetOrderByIdWithHttpInfoAsync(orderId, cancellationToken).ConfigureAwait(false); + return localVarResponse.Data; + } + + /// + /// Find purchase order by ID For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + /// + /// Thrown when fails to make API call + /// ID of pet that needs to be fetched + /// Cancellation Token to cancel the request. + /// Task of ApiResponse (Order) + public async System.Threading.Tasks.Task> GetOrderByIdWithHttpInfoAsync(long orderId, 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/xml", + "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.PathParameters.Add("order_id", Org.OpenAPITools.Client.ClientUtils.ParameterToString(orderId)); // path parameter + + + // make the HTTP request + + var localVarResponse = await this.AsynchronousClient.GetAsync("/store/order/{order_id}", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("GetOrderById", localVarResponse); + if (_exception != null) throw _exception; + } + + return localVarResponse; + } + + /// + /// Place an order for a pet + /// + /// Thrown when fails to make API call + /// order placed for purchasing the pet + /// Order + public Order PlaceOrder(Order order) + { + Org.OpenAPITools.Client.ApiResponse localVarResponse = PlaceOrderWithHttpInfo(order); + return localVarResponse.Data; + } + + /// + /// Place an order for a pet + /// + /// Thrown when fails to make API call + /// order placed for purchasing the pet + /// ApiResponse of Order + public Org.OpenAPITools.Client.ApiResponse PlaceOrderWithHttpInfo(Order order) + { + // verify the required parameter 'order' is set + if (order == null) + throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'order' when calling StoreApi->PlaceOrder"); + + 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/xml", + "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 = order; + + + // make the HTTP request + var localVarResponse = this.Client.Post("/store/order", localVarRequestOptions, this.Configuration); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("PlaceOrder", localVarResponse); + if (_exception != null) throw _exception; + } + + return localVarResponse; + } + + /// + /// Place an order for a pet + /// + /// Thrown when fails to make API call + /// order placed for purchasing the pet + /// Cancellation Token to cancel the request. + /// Task of Order + public async System.Threading.Tasks.Task PlaceOrderAsync(Order order, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + Org.OpenAPITools.Client.ApiResponse localVarResponse = await PlaceOrderWithHttpInfoAsync(order, cancellationToken).ConfigureAwait(false); + return localVarResponse.Data; + } + + /// + /// Place an order for a pet + /// + /// Thrown when fails to make API call + /// order placed for purchasing the pet + /// Cancellation Token to cancel the request. + /// Task of ApiResponse (Order) + public async System.Threading.Tasks.Task> PlaceOrderWithHttpInfoAsync(Order order, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + // verify the required parameter 'order' is set + if (order == null) + throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'order' when calling StoreApi->PlaceOrder"); + + + 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/xml", + "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 = order; + + + // make the HTTP request + + var localVarResponse = await this.AsynchronousClient.PostAsync("/store/order", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("PlaceOrder", localVarResponse); + if (_exception != null) throw _exception; + } + + return localVarResponse; + } + + } +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Api/UserApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Api/UserApi.cs new file mode 100644 index 00000000000..a2f2598c8ac --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Api/UserApi.cs @@ -0,0 +1,1422 @@ +/* + * 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.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 IUserApiSync : IApiAccessor + { + #region Synchronous Operations + /// + /// Create user + /// + /// + /// This can only be done by the logged in user. + /// + /// Thrown when fails to make API call + /// Created user object + /// + void CreateUser(User user); + + /// + /// Create user + /// + /// + /// This can only be done by the logged in user. + /// + /// Thrown when fails to make API call + /// Created user object + /// ApiResponse of Object(void) + ApiResponse CreateUserWithHttpInfo(User user); + /// + /// Creates list of users with given input array + /// + /// Thrown when fails to make API call + /// List of user object + /// + void CreateUsersWithArrayInput(List user); + + /// + /// Creates list of users with given input array + /// + /// + /// + /// + /// Thrown when fails to make API call + /// List of user object + /// ApiResponse of Object(void) + ApiResponse CreateUsersWithArrayInputWithHttpInfo(List user); + /// + /// Creates list of users with given input array + /// + /// Thrown when fails to make API call + /// List of user object + /// + void CreateUsersWithListInput(List user); + + /// + /// Creates list of users with given input array + /// + /// + /// + /// + /// Thrown when fails to make API call + /// List of user object + /// ApiResponse of Object(void) + ApiResponse CreateUsersWithListInputWithHttpInfo(List user); + /// + /// Delete user + /// + /// + /// This can only be done by the logged in user. + /// + /// Thrown when fails to make API call + /// The name that needs to be deleted + /// + void DeleteUser(string username); + + /// + /// Delete user + /// + /// + /// This can only be done by the logged in user. + /// + /// Thrown when fails to make API call + /// The name that needs to be deleted + /// ApiResponse of Object(void) + ApiResponse DeleteUserWithHttpInfo(string username); + /// + /// Get user by user name + /// + /// Thrown when fails to make API call + /// The name that needs to be fetched. Use user1 for testing. + /// User + User GetUserByName(string username); + + /// + /// Get user by user name + /// + /// + /// + /// + /// Thrown when fails to make API call + /// The name that needs to be fetched. Use user1 for testing. + /// ApiResponse of User + ApiResponse GetUserByNameWithHttpInfo(string username); + /// + /// Logs user into the system + /// + /// Thrown when fails to make API call + /// The user name for login + /// The password for login in clear text + /// string + string LoginUser(string username, string password); + + /// + /// Logs user into the system + /// + /// + /// + /// + /// Thrown when fails to make API call + /// The user name for login + /// The password for login in clear text + /// ApiResponse of string + ApiResponse LoginUserWithHttpInfo(string username, string password); + /// + /// Logs out current logged in user session + /// + /// Thrown when fails to make API call + /// + void LogoutUser(); + + /// + /// Logs out current logged in user session + /// + /// + /// + /// + /// Thrown when fails to make API call + /// ApiResponse of Object(void) + ApiResponse LogoutUserWithHttpInfo(); + /// + /// Updated user + /// + /// + /// This can only be done by the logged in user. + /// + /// Thrown when fails to make API call + /// name that need to be deleted + /// Updated user object + /// + void UpdateUser(string username, User user); + + /// + /// Updated user + /// + /// + /// This can only be done by the logged in user. + /// + /// Thrown when fails to make API call + /// name that need to be deleted + /// Updated user object + /// ApiResponse of Object(void) + ApiResponse UpdateUserWithHttpInfo(string username, User user); + #endregion Synchronous Operations + } + + /// + /// Represents a collection of functions to interact with the API endpoints + /// + public interface IUserApiAsync : IApiAccessor + { + #region Asynchronous Operations + /// + /// Create user + /// + /// + /// This can only be done by the logged in user. + /// + /// Thrown when fails to make API call + /// Created user object + /// Cancellation Token to cancel the request. + /// Task of void + System.Threading.Tasks.Task CreateUserAsync(User user, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// Create user + /// + /// + /// This can only be done by the logged in user. + /// + /// Thrown when fails to make API call + /// Created user object + /// Cancellation Token to cancel the request. + /// Task of ApiResponse + System.Threading.Tasks.Task> CreateUserWithHttpInfoAsync(User user, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + /// + /// Creates list of users with given input array + /// + /// + /// + /// + /// Thrown when fails to make API call + /// List of user object + /// Cancellation Token to cancel the request. + /// Task of void + System.Threading.Tasks.Task CreateUsersWithArrayInputAsync(List user, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// Creates list of users with given input array + /// + /// + /// + /// + /// Thrown when fails to make API call + /// List of user object + /// Cancellation Token to cancel the request. + /// Task of ApiResponse + System.Threading.Tasks.Task> CreateUsersWithArrayInputWithHttpInfoAsync(List user, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + /// + /// Creates list of users with given input array + /// + /// + /// + /// + /// Thrown when fails to make API call + /// List of user object + /// Cancellation Token to cancel the request. + /// Task of void + System.Threading.Tasks.Task CreateUsersWithListInputAsync(List user, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// Creates list of users with given input array + /// + /// + /// + /// + /// Thrown when fails to make API call + /// List of user object + /// Cancellation Token to cancel the request. + /// Task of ApiResponse + System.Threading.Tasks.Task> CreateUsersWithListInputWithHttpInfoAsync(List user, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + /// + /// Delete user + /// + /// + /// This can only be done by the logged in user. + /// + /// Thrown when fails to make API call + /// The name that needs to be deleted + /// Cancellation Token to cancel the request. + /// Task of void + System.Threading.Tasks.Task DeleteUserAsync(string username, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// Delete user + /// + /// + /// This can only be done by the logged in user. + /// + /// Thrown when fails to make API call + /// The name that needs to be deleted + /// Cancellation Token to cancel the request. + /// Task of ApiResponse + System.Threading.Tasks.Task> DeleteUserWithHttpInfoAsync(string username, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + /// + /// Get user by user name + /// + /// + /// + /// + /// Thrown when fails to make API call + /// The name that needs to be fetched. Use user1 for testing. + /// Cancellation Token to cancel the request. + /// Task of User + System.Threading.Tasks.Task GetUserByNameAsync(string username, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// Get user by user name + /// + /// + /// + /// + /// Thrown when fails to make API call + /// The name that needs to be fetched. Use user1 for testing. + /// Cancellation Token to cancel the request. + /// Task of ApiResponse (User) + System.Threading.Tasks.Task> GetUserByNameWithHttpInfoAsync(string username, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + /// + /// Logs user into the system + /// + /// + /// + /// + /// Thrown when fails to make API call + /// The user name for login + /// The password for login in clear text + /// Cancellation Token to cancel the request. + /// Task of string + System.Threading.Tasks.Task LoginUserAsync(string username, string password, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// Logs user into the system + /// + /// + /// + /// + /// Thrown when fails to make API call + /// The user name for login + /// The password for login in clear text + /// Cancellation Token to cancel the request. + /// Task of ApiResponse (string) + System.Threading.Tasks.Task> LoginUserWithHttpInfoAsync(string username, string password, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + /// + /// Logs out current logged in user session + /// + /// + /// + /// + /// Thrown when fails to make API call + /// Cancellation Token to cancel the request. + /// Task of void + System.Threading.Tasks.Task LogoutUserAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// Logs out current logged in user session + /// + /// + /// + /// + /// Thrown when fails to make API call + /// Cancellation Token to cancel the request. + /// Task of ApiResponse + System.Threading.Tasks.Task> LogoutUserWithHttpInfoAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + /// + /// Updated user + /// + /// + /// This can only be done by the logged in user. + /// + /// Thrown when fails to make API call + /// name that need to be deleted + /// Updated user object + /// Cancellation Token to cancel the request. + /// Task of void + System.Threading.Tasks.Task UpdateUserAsync(string username, User user, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// Updated user + /// + /// + /// This can only be done by the logged in user. + /// + /// Thrown when fails to make API call + /// name that need to be deleted + /// Updated user object + /// Cancellation Token to cancel the request. + /// Task of ApiResponse + System.Threading.Tasks.Task> UpdateUserWithHttpInfoAsync(string username, User user, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + #endregion Asynchronous Operations + } + + /// + /// Represents a collection of functions to interact with the API endpoints + /// + public interface IUserApi : IUserApiSync, IUserApiAsync + { + + } + + /// + /// Represents a collection of functions to interact with the API endpoints + /// + public partial class UserApi : IUserApi + { + private Org.OpenAPITools.Client.ExceptionFactory _exceptionFactory = (name, response) => null; + + /// + /// Initializes a new instance of the class. + /// + /// + public UserApi() : this((string)null) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// + public UserApi(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 UserApi(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 UserApi(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; } + } + + /// + /// Create user This can only be done by the logged in user. + /// + /// Thrown when fails to make API call + /// Created user object + /// + public void CreateUser(User user) + { + CreateUserWithHttpInfo(user); + } + + /// + /// Create user This can only be done by the logged in user. + /// + /// Thrown when fails to make API call + /// Created user object + /// ApiResponse of Object(void) + public Org.OpenAPITools.Client.ApiResponse CreateUserWithHttpInfo(User user) + { + // verify the required parameter 'user' is set + if (user == null) + throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'user' when calling UserApi->CreateUser"); + + 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 = user; + + + // make the HTTP request + var localVarResponse = this.Client.Post("/user", localVarRequestOptions, this.Configuration); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("CreateUser", localVarResponse); + if (_exception != null) throw _exception; + } + + return localVarResponse; + } + + /// + /// Create user This can only be done by the logged in user. + /// + /// Thrown when fails to make API call + /// Created user object + /// Cancellation Token to cancel the request. + /// Task of void + public async System.Threading.Tasks.Task CreateUserAsync(User user, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + await CreateUserWithHttpInfoAsync(user, cancellationToken).ConfigureAwait(false); + } + + /// + /// Create user This can only be done by the logged in user. + /// + /// Thrown when fails to make API call + /// Created user object + /// Cancellation Token to cancel the request. + /// Task of ApiResponse + public async System.Threading.Tasks.Task> CreateUserWithHttpInfoAsync(User user, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + // verify the required parameter 'user' is set + if (user == null) + throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'user' when calling UserApi->CreateUser"); + + + 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 = user; + + + // make the HTTP request + + var localVarResponse = await this.AsynchronousClient.PostAsync("/user", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("CreateUser", localVarResponse); + if (_exception != null) throw _exception; + } + + return localVarResponse; + } + + /// + /// Creates list of users with given input array + /// + /// Thrown when fails to make API call + /// List of user object + /// + public void CreateUsersWithArrayInput(List user) + { + CreateUsersWithArrayInputWithHttpInfo(user); + } + + /// + /// Creates list of users with given input array + /// + /// Thrown when fails to make API call + /// List of user object + /// ApiResponse of Object(void) + public Org.OpenAPITools.Client.ApiResponse CreateUsersWithArrayInputWithHttpInfo(List user) + { + // verify the required parameter 'user' is set + if (user == null) + throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'user' when calling UserApi->CreateUsersWithArrayInput"); + + 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 = user; + + + // make the HTTP request + var localVarResponse = this.Client.Post("/user/createWithArray", localVarRequestOptions, this.Configuration); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("CreateUsersWithArrayInput", localVarResponse); + if (_exception != null) throw _exception; + } + + return localVarResponse; + } + + /// + /// Creates list of users with given input array + /// + /// Thrown when fails to make API call + /// List of user object + /// Cancellation Token to cancel the request. + /// Task of void + public async System.Threading.Tasks.Task CreateUsersWithArrayInputAsync(List user, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + await CreateUsersWithArrayInputWithHttpInfoAsync(user, cancellationToken).ConfigureAwait(false); + } + + /// + /// Creates list of users with given input array + /// + /// Thrown when fails to make API call + /// List of user object + /// Cancellation Token to cancel the request. + /// Task of ApiResponse + public async System.Threading.Tasks.Task> CreateUsersWithArrayInputWithHttpInfoAsync(List user, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + // verify the required parameter 'user' is set + if (user == null) + throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'user' when calling UserApi->CreateUsersWithArrayInput"); + + + 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 = user; + + + // make the HTTP request + + var localVarResponse = await this.AsynchronousClient.PostAsync("/user/createWithArray", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("CreateUsersWithArrayInput", localVarResponse); + if (_exception != null) throw _exception; + } + + return localVarResponse; + } + + /// + /// Creates list of users with given input array + /// + /// Thrown when fails to make API call + /// List of user object + /// + public void CreateUsersWithListInput(List user) + { + CreateUsersWithListInputWithHttpInfo(user); + } + + /// + /// Creates list of users with given input array + /// + /// Thrown when fails to make API call + /// List of user object + /// ApiResponse of Object(void) + public Org.OpenAPITools.Client.ApiResponse CreateUsersWithListInputWithHttpInfo(List user) + { + // verify the required parameter 'user' is set + if (user == null) + throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'user' when calling UserApi->CreateUsersWithListInput"); + + 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 = user; + + + // make the HTTP request + var localVarResponse = this.Client.Post("/user/createWithList", localVarRequestOptions, this.Configuration); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("CreateUsersWithListInput", localVarResponse); + if (_exception != null) throw _exception; + } + + return localVarResponse; + } + + /// + /// Creates list of users with given input array + /// + /// Thrown when fails to make API call + /// List of user object + /// Cancellation Token to cancel the request. + /// Task of void + public async System.Threading.Tasks.Task CreateUsersWithListInputAsync(List user, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + await CreateUsersWithListInputWithHttpInfoAsync(user, cancellationToken).ConfigureAwait(false); + } + + /// + /// Creates list of users with given input array + /// + /// Thrown when fails to make API call + /// List of user object + /// Cancellation Token to cancel the request. + /// Task of ApiResponse + public async System.Threading.Tasks.Task> CreateUsersWithListInputWithHttpInfoAsync(List user, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + // verify the required parameter 'user' is set + if (user == null) + throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'user' when calling UserApi->CreateUsersWithListInput"); + + + 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 = user; + + + // make the HTTP request + + var localVarResponse = await this.AsynchronousClient.PostAsync("/user/createWithList", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("CreateUsersWithListInput", localVarResponse); + if (_exception != null) throw _exception; + } + + return localVarResponse; + } + + /// + /// Delete user This can only be done by the logged in user. + /// + /// Thrown when fails to make API call + /// The name that needs to be deleted + /// + public void DeleteUser(string username) + { + DeleteUserWithHttpInfo(username); + } + + /// + /// Delete user This can only be done by the logged in user. + /// + /// Thrown when fails to make API call + /// The name that needs to be deleted + /// ApiResponse of Object(void) + public Org.OpenAPITools.Client.ApiResponse DeleteUserWithHttpInfo(string username) + { + // verify the required parameter 'username' is set + if (username == null) + throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'username' when calling UserApi->DeleteUser"); + + Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + }; + + // 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.PathParameters.Add("username", Org.OpenAPITools.Client.ClientUtils.ParameterToString(username)); // path parameter + + + // make the HTTP request + var localVarResponse = this.Client.Delete("/user/{username}", localVarRequestOptions, this.Configuration); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("DeleteUser", localVarResponse); + if (_exception != null) throw _exception; + } + + return localVarResponse; + } + + /// + /// Delete user This can only be done by the logged in user. + /// + /// Thrown when fails to make API call + /// The name that needs to be deleted + /// Cancellation Token to cancel the request. + /// Task of void + public async System.Threading.Tasks.Task DeleteUserAsync(string username, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + await DeleteUserWithHttpInfoAsync(username, cancellationToken).ConfigureAwait(false); + } + + /// + /// Delete user This can only be done by the logged in user. + /// + /// Thrown when fails to make API call + /// The name that needs to be deleted + /// Cancellation Token to cancel the request. + /// Task of ApiResponse + public async System.Threading.Tasks.Task> DeleteUserWithHttpInfoAsync(string username, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + // verify the required parameter 'username' is set + if (username == null) + throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'username' when calling UserApi->DeleteUser"); + + + Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + }; + + // 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.PathParameters.Add("username", Org.OpenAPITools.Client.ClientUtils.ParameterToString(username)); // path parameter + + + // make the HTTP request + + var localVarResponse = await this.AsynchronousClient.DeleteAsync("/user/{username}", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("DeleteUser", localVarResponse); + if (_exception != null) throw _exception; + } + + return localVarResponse; + } + + /// + /// Get user by user name + /// + /// Thrown when fails to make API call + /// The name that needs to be fetched. Use user1 for testing. + /// User + public User GetUserByName(string username) + { + Org.OpenAPITools.Client.ApiResponse localVarResponse = GetUserByNameWithHttpInfo(username); + return localVarResponse.Data; + } + + /// + /// Get user by user name + /// + /// Thrown when fails to make API call + /// The name that needs to be fetched. Use user1 for testing. + /// ApiResponse of User + public Org.OpenAPITools.Client.ApiResponse GetUserByNameWithHttpInfo(string username) + { + // verify the required parameter 'username' is set + if (username == null) + throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'username' when calling UserApi->GetUserByName"); + + Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + }; + + // to determine the Accept header + string[] _accepts = new string[] { + "application/xml", + "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.PathParameters.Add("username", Org.OpenAPITools.Client.ClientUtils.ParameterToString(username)); // path parameter + + + // make the HTTP request + var localVarResponse = this.Client.Get("/user/{username}", localVarRequestOptions, this.Configuration); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("GetUserByName", localVarResponse); + if (_exception != null) throw _exception; + } + + return localVarResponse; + } + + /// + /// Get user by user name + /// + /// Thrown when fails to make API call + /// The name that needs to be fetched. Use user1 for testing. + /// Cancellation Token to cancel the request. + /// Task of User + public async System.Threading.Tasks.Task GetUserByNameAsync(string username, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + Org.OpenAPITools.Client.ApiResponse localVarResponse = await GetUserByNameWithHttpInfoAsync(username, cancellationToken).ConfigureAwait(false); + return localVarResponse.Data; + } + + /// + /// Get user by user name + /// + /// Thrown when fails to make API call + /// The name that needs to be fetched. Use user1 for testing. + /// Cancellation Token to cancel the request. + /// Task of ApiResponse (User) + public async System.Threading.Tasks.Task> GetUserByNameWithHttpInfoAsync(string username, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + // verify the required parameter 'username' is set + if (username == null) + throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'username' when calling UserApi->GetUserByName"); + + + Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + }; + + // to determine the Accept header + string[] _accepts = new string[] { + "application/xml", + "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.PathParameters.Add("username", Org.OpenAPITools.Client.ClientUtils.ParameterToString(username)); // path parameter + + + // make the HTTP request + + var localVarResponse = await this.AsynchronousClient.GetAsync("/user/{username}", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("GetUserByName", localVarResponse); + if (_exception != null) throw _exception; + } + + return localVarResponse; + } + + /// + /// Logs user into the system + /// + /// Thrown when fails to make API call + /// The user name for login + /// The password for login in clear text + /// string + public string LoginUser(string username, string password) + { + Org.OpenAPITools.Client.ApiResponse localVarResponse = LoginUserWithHttpInfo(username, password); + return localVarResponse.Data; + } + + /// + /// Logs user into the system + /// + /// Thrown when fails to make API call + /// The user name for login + /// The password for login in clear text + /// ApiResponse of string + public Org.OpenAPITools.Client.ApiResponse LoginUserWithHttpInfo(string username, string password) + { + // verify the required parameter 'username' is set + if (username == null) + throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'username' when calling UserApi->LoginUser"); + + // verify the required parameter 'password' is set + if (password == null) + throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'password' when calling UserApi->LoginUser"); + + Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + }; + + // to determine the Accept header + string[] _accepts = new string[] { + "application/xml", + "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.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("", "username", username)); + localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("", "password", password)); + + + // make the HTTP request + var localVarResponse = this.Client.Get("/user/login", localVarRequestOptions, this.Configuration); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("LoginUser", localVarResponse); + if (_exception != null) throw _exception; + } + + return localVarResponse; + } + + /// + /// Logs user into the system + /// + /// Thrown when fails to make API call + /// The user name for login + /// The password for login in clear text + /// Cancellation Token to cancel the request. + /// Task of string + public async System.Threading.Tasks.Task LoginUserAsync(string username, string password, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + Org.OpenAPITools.Client.ApiResponse localVarResponse = await LoginUserWithHttpInfoAsync(username, password, cancellationToken).ConfigureAwait(false); + return localVarResponse.Data; + } + + /// + /// Logs user into the system + /// + /// Thrown when fails to make API call + /// The user name for login + /// The password for login in clear text + /// Cancellation Token to cancel the request. + /// Task of ApiResponse (string) + public async System.Threading.Tasks.Task> LoginUserWithHttpInfoAsync(string username, string password, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + // verify the required parameter 'username' is set + if (username == null) + throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'username' when calling UserApi->LoginUser"); + + // verify the required parameter 'password' is set + if (password == null) + throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'password' when calling UserApi->LoginUser"); + + + Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + }; + + // to determine the Accept header + string[] _accepts = new string[] { + "application/xml", + "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.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("", "username", username)); + localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("", "password", password)); + + + // make the HTTP request + + var localVarResponse = await this.AsynchronousClient.GetAsync("/user/login", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("LoginUser", localVarResponse); + if (_exception != null) throw _exception; + } + + return localVarResponse; + } + + /// + /// Logs out current logged in user session + /// + /// Thrown when fails to make API call + /// + public void LogoutUser() + { + LogoutUserWithHttpInfo(); + } + + /// + /// Logs out current logged in user session + /// + /// Thrown when fails to make API call + /// ApiResponse of Object(void) + public Org.OpenAPITools.Client.ApiResponse LogoutUserWithHttpInfo() + { + Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + }; + + // 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); + + + + // make the HTTP request + var localVarResponse = this.Client.Get("/user/logout", localVarRequestOptions, this.Configuration); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("LogoutUser", localVarResponse); + if (_exception != null) throw _exception; + } + + return localVarResponse; + } + + /// + /// Logs out current logged in user session + /// + /// Thrown when fails to make API call + /// Cancellation Token to cancel the request. + /// Task of void + public async System.Threading.Tasks.Task LogoutUserAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + await LogoutUserWithHttpInfoAsync(cancellationToken).ConfigureAwait(false); + } + + /// + /// Logs out current logged in user session + /// + /// Thrown when fails to make API call + /// Cancellation Token to cancel the request. + /// Task of ApiResponse + public async System.Threading.Tasks.Task> LogoutUserWithHttpInfoAsync(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[] { + }; + + + 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); + + + + // make the HTTP request + + var localVarResponse = await this.AsynchronousClient.GetAsync("/user/logout", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("LogoutUser", localVarResponse); + if (_exception != null) throw _exception; + } + + return localVarResponse; + } + + /// + /// Updated user This can only be done by the logged in user. + /// + /// Thrown when fails to make API call + /// name that need to be deleted + /// Updated user object + /// + public void UpdateUser(string username, User user) + { + UpdateUserWithHttpInfo(username, user); + } + + /// + /// Updated user This can only be done by the logged in user. + /// + /// Thrown when fails to make API call + /// name that need to be deleted + /// Updated user object + /// ApiResponse of Object(void) + public Org.OpenAPITools.Client.ApiResponse UpdateUserWithHttpInfo(string username, User user) + { + // verify the required parameter 'username' is set + if (username == null) + throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'username' when calling UserApi->UpdateUser"); + + // verify the required parameter 'user' is set + if (user == null) + throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'user' when calling UserApi->UpdateUser"); + + 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.PathParameters.Add("username", Org.OpenAPITools.Client.ClientUtils.ParameterToString(username)); // path parameter + localVarRequestOptions.Data = user; + + + // make the HTTP request + var localVarResponse = this.Client.Put("/user/{username}", localVarRequestOptions, this.Configuration); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("UpdateUser", localVarResponse); + if (_exception != null) throw _exception; + } + + return localVarResponse; + } + + /// + /// Updated user This can only be done by the logged in user. + /// + /// Thrown when fails to make API call + /// name that need to be deleted + /// Updated user object + /// Cancellation Token to cancel the request. + /// Task of void + public async System.Threading.Tasks.Task UpdateUserAsync(string username, User user, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + await UpdateUserWithHttpInfoAsync(username, user, cancellationToken).ConfigureAwait(false); + } + + /// + /// Updated user This can only be done by the logged in user. + /// + /// Thrown when fails to make API call + /// name that need to be deleted + /// Updated user object + /// Cancellation Token to cancel the request. + /// Task of ApiResponse + public async System.Threading.Tasks.Task> UpdateUserWithHttpInfoAsync(string username, User user, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + // verify the required parameter 'username' is set + if (username == null) + throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'username' when calling UserApi->UpdateUser"); + + // verify the required parameter 'user' is set + if (user == null) + throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'user' when calling UserApi->UpdateUser"); + + + 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.PathParameters.Add("username", Org.OpenAPITools.Client.ClientUtils.ParameterToString(username)); // path parameter + localVarRequestOptions.Data = user; + + + // make the HTTP request + + var localVarResponse = await this.AsynchronousClient.PutAsync("/user/{username}", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("UpdateUser", localVarResponse); + if (_exception != null) throw _exception; + } + + return localVarResponse; + } + + } +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Client/ApiClient.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Client/ApiClient.cs new file mode 100644 index 00000000000..e3647002317 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Client/ApiClient.cs @@ -0,0 +1,860 @@ +/* + * 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.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 Newtonsoft.Json; +using Newtonsoft.Json.Serialization; +using ErrorEventArgs = Newtonsoft.Json.Serialization.ErrorEventArgs; +using RestSharp; +using RestSharp.Deserializers; +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 : RestSharp.Serializers.ISerializer, RestSharp.Deserializers.IDeserializer + { + private readonly IReadableConfiguration _configuration; + private static readonly string _contentType = "application/json"; + 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 T Deserialize(IRestResponse 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(IRestResponse 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 string RootElement { get; set; } + public string Namespace { get; set; } + public string DateFormat { get; set; } + + public string ContentType + { + get { return _contentType; } + set { throw new InvalidOperationException("Not allowed to set content type."); } + } + } + /// + /// Provides a default implementation of an Api client (both synchronous and asynchronous implementatios), + /// 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 accomodate 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(IRestRequest request); + + /// + /// Allows for extending response processing for generated code. + /// + /// The RestSharp request object + /// The RestSharp response object + partial void InterceptResponse(IRestRequest request, IRestResponse 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(Method(method)) + { + Resource = path, + JsonSerializer = new CustomJsonCodec(SerializerSettings, configuration) + }; + + 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) + { + var bytes = ClientUtils.ReadAsBytes(fileParam.Value); + var fileStream = fileParam.Value as FileStream; + if (fileStream != null) + request.Files.Add(FileParameter.Create(fileParam.Key, bytes, System.IO.Path.GetFileName(fileStream.Name))); + else + request.Files.Add(FileParameter.Create(fileParam.Key, bytes, "no_file_name_provided")); + } + } + + if (options.Cookies != null && options.Cookies.Count > 0) + { + foreach (var cookie in options.Cookies) + { + request.AddCookie(cookie.Name, cookie.Value); + } + } + + return request; + } + + private ApiResponse ToApiResponse(IRestResponse 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.Cookies != null) + { + foreach (var responseCookies in response.Cookies) + { + transformed.Cookies.Add( + new Cookie( + responseCookies.Name, + responseCookies.Value, + responseCookies.Path, + responseCookies.Domain) + ); + } + } + + return transformed; + } + + private ApiResponse Exec(RestRequest req, IReadableConfiguration configuration) + { + RestClient client = new RestClient(_baseUrl); + + client.ClearHandlers(); + var existingDeserializer = req.JsonSerializer as IDeserializer; + if (existingDeserializer != null) + { + client.AddHandler("application/json", () => existingDeserializer); + client.AddHandler("text/json", () => existingDeserializer); + client.AddHandler("text/x-json", () => existingDeserializer); + client.AddHandler("text/javascript", () => existingDeserializer); + client.AddHandler("*+json", () => existingDeserializer); + } + else + { + var customDeserializer = new CustomJsonCodec(SerializerSettings, configuration); + client.AddHandler("application/json", () => customDeserializer); + client.AddHandler("text/json", () => customDeserializer); + client.AddHandler("text/x-json", () => customDeserializer); + client.AddHandler("text/javascript", () => customDeserializer); + client.AddHandler("*+json", () => customDeserializer); + } + + var xmlDeserializer = new XmlDeserializer(); + client.AddHandler("application/xml", () => xmlDeserializer); + client.AddHandler("text/xml", () => xmlDeserializer); + client.AddHandler("*+xml", () => xmlDeserializer); + client.AddHandler("*", () => xmlDeserializer); + + client.Timeout = configuration.Timeout; + + if (configuration.Proxy != null) + { + client.Proxy = configuration.Proxy; + } + + if (configuration.UserAgent != null) + { + client.UserAgent = configuration.UserAgent; + } + + if (configuration.ClientCertificates != null) + { + client.ClientCertificates = configuration.ClientCertificates; + } + + InterceptRequest(req); + + IRestResponse response; + if (RetryConfiguration.RetryPolicy != null) + { + var policy = RetryConfiguration.RetryPolicy; + var policyResult = policy.ExecuteAndCapture(() => client.Execute(req)); + response = (policyResult.Outcome == OutcomeType.Successful) ? client.Deserialize(policyResult.Result) : new RestResponse + { + Request = req, + ErrorException = policyResult.FinalException + }; + } + else + { + response = client.Execute(req); + } + + // 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); + } + + InterceptResponse(req, 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) + { + 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 req, IReadableConfiguration configuration, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + RestClient client = new RestClient(_baseUrl); + + client.ClearHandlers(); + var existingDeserializer = req.JsonSerializer as IDeserializer; + if (existingDeserializer != null) + { + client.AddHandler("application/json", () => existingDeserializer); + client.AddHandler("text/json", () => existingDeserializer); + client.AddHandler("text/x-json", () => existingDeserializer); + client.AddHandler("text/javascript", () => existingDeserializer); + client.AddHandler("*+json", () => existingDeserializer); + } + else + { + var customDeserializer = new CustomJsonCodec(SerializerSettings, configuration); + client.AddHandler("application/json", () => customDeserializer); + client.AddHandler("text/json", () => customDeserializer); + client.AddHandler("text/x-json", () => customDeserializer); + client.AddHandler("text/javascript", () => customDeserializer); + client.AddHandler("*+json", () => customDeserializer); + } + + var xmlDeserializer = new XmlDeserializer(); + client.AddHandler("application/xml", () => xmlDeserializer); + client.AddHandler("text/xml", () => xmlDeserializer); + client.AddHandler("*+xml", () => xmlDeserializer); + client.AddHandler("*", () => xmlDeserializer); + + client.Timeout = configuration.Timeout; + + if (configuration.Proxy != null) + { + client.Proxy = configuration.Proxy; + } + + if (configuration.UserAgent != null) + { + client.UserAgent = configuration.UserAgent; + } + + if (configuration.ClientCertificates != null) + { + client.ClientCertificates = configuration.ClientCertificates; + } + + InterceptRequest(req); + + IRestResponse response; + if (RetryConfiguration.AsyncRetryPolicy != null) + { + var policy = RetryConfiguration.AsyncRetryPolicy; + var policyResult = await policy.ExecuteAndCaptureAsync((ct) => client.ExecuteAsync(req, ct), cancellationToken).ConfigureAwait(false); + response = (policyResult.Outcome == OutcomeType.Successful) ? client.Deserialize(policyResult.Result) : new RestResponse + { + Request = req, + ErrorException = policyResult.FinalException + }; + } + else + { + response = await client.ExecuteAsync(req, 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); + } + + InterceptResponse(req, 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) + { + 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), 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), 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), 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), 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), 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), 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), 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), 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), 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), 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), 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), 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), 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), config); + } + #endregion ISynchronousClient + } +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Client/ApiException.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Client/ApiException.cs new file mode 100644 index 00000000000..67d9888d6a3 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Client/ApiException.cs @@ -0,0 +1,68 @@ +/* + * 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; + +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-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Client/ApiResponse.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Client/ApiResponse.cs new file mode 100644 index 00000000000..ca2de833a5a --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Client/ApiResponse.cs @@ -0,0 +1,166 @@ +/* + * 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.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-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Client/ClientUtils.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Client/ClientUtils.cs new file mode 100644 index 00000000000..3d038d5ce69 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Client/ClientUtils.cs @@ -0,0 +1,243 @@ +/* + * 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.Globalization; +using System.IO; +using System.Linq; +using System.Text; +using System.Text.RegularExpressions; +using KellermanSoftware.CompareNetObjects; + +namespace Org.OpenAPITools.Client +{ + /// + /// Utility functions providing some benefit to API client consumers. + /// + public static class ClientUtils + { + /// + /// An instance of CompareLogic. + /// + public static CompareLogic compareLogic; + + /// + /// Static contstructor to initialise compareLogic. + /// + static ClientUtils() + { + compareLogic = new CompareLogic(); + } + + /// + /// 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) + return string.Join(",", collection.Cast()); + + return Convert.ToString(obj, 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"); + } + } +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Client/Configuration.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Client/Configuration.cs new file mode 100644 index 00000000000..06154ad382c --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Client/Configuration.cs @@ -0,0 +1,587 @@ +/* + * 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.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; + +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); + } + 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; + + /// + /// Gets or sets the API key based on the authentication name. + /// This is the key and value comprising the "secret" for acessing 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; + + /// + /// HttpSigning configuration + /// + private HttpSigningConfiguration _HttpSigningConfiguration = null; + #endregion Private Members + + #region Constructors + + /// + /// Initializes a new instance of the class + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage("ReSharper", "VirtualMemberCallInConstructor")] + public Configuration() + { + Proxy = null; + UserAgent = "OpenAPI-Generator/1.0.0/csharp"; + BasePath = "http://petstore.swagger.io:80/v2"; + DefaultHeaders = new ConcurrentDictionary(); + ApiKey = new ConcurrentDictionary(); + ApiKeyPrefix = new ConcurrentDictionary(); + Servers = new List>() + { + { + new Dictionary { + {"url", "http://{server}.swagger.io:{port}/v2"}, + {"description", "petstore server"}, + { + "variables", new Dictionary { + { + "server", new Dictionary { + {"description", "No description provided"}, + {"default_value", "petstore"}, + { + "enum_values", new List() { + "petstore", + "qa-petstore", + "dev-petstore" + } + } + } + }, + { + "port", new Dictionary { + {"description", "No description provided"}, + {"default_value", "80"}, + { + "enum_values", new List() { + "80", + "8080" + } + } + } + } + } + } + } + }, + { + new Dictionary { + {"url", "https://localhost:8080/{version}"}, + {"description", "The local server"}, + { + "variables", new Dictionary { + { + "version", new Dictionary { + {"description", "No description provided"}, + {"default_value", "v2"}, + { + "enum_values", new List() { + "v1", + "v2" + } + } + } + } + } + } + } + }, + { + new Dictionary { + {"url", "https://127.0.0.1/no_variable"}, + {"description", "The local server without variables"}, + } + } + }; + + // 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://petstore.swagger.io:80/v2") : 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; } + } + + /// + /// 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; + } + } + + /// + /// 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(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) + { + 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"]; + + // go through 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 defualt value + url = url.Replace("{" + variable.Key + "}", (string)serverVariables["default_value"]); + } + } + + return url; + } + + /// + /// Gets and Sets the HttpSigningConfiuration + /// + public HttpSigningConfiguration HttpSigningConfiguration + { + get { return _HttpSigningConfiguration; } + set { _HttpSigningConfiguration = value; } + } + + #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, + HttpSigningConfiguration = second.HttpSigningConfiguration ?? first.HttpSigningConfiguration, + TempFolderPath = second.TempFolderPath ?? first.TempFolderPath, + DateTimeFormat = second.DateTimeFormat ?? first.DateTimeFormat + }; + return config; + } + #endregion Static Members + } +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Client/ExceptionFactory.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Client/ExceptionFactory.cs new file mode 100644 index 00000000000..43624dd7c86 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Client/ExceptionFactory.cs @@ -0,0 +1,22 @@ +/* + * 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; + +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-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Client/GlobalConfiguration.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Client/GlobalConfiguration.cs new file mode 100644 index 00000000000..4bc467ffa40 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Client/GlobalConfiguration.cs @@ -0,0 +1,67 @@ +/* + * 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.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; + } + } + } + } +} \ No newline at end of file diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Client/HttpMethod.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Client/HttpMethod.cs new file mode 100644 index 00000000000..39cde64b2a5 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Client/HttpMethod.cs @@ -0,0 +1,33 @@ +/* + * 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 + */ + + +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-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Client/HttpSigningConfiguration.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Client/HttpSigningConfiguration.cs new file mode 100644 index 00000000000..1d2d0019cae --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Client/HttpSigningConfiguration.cs @@ -0,0 +1,757 @@ +using Newtonsoft.Json; +using Newtonsoft.Json.Serialization; +using System; +using System.Collections.Generic; +using System.IO; +using System.Runtime.InteropServices; +using System.Security; +using System.Security.Cryptography; +using System.Text; +using System.Web; + +namespace Org.OpenAPITools.Client +{ + /// + /// Class for HttpSigning auth related parameter and methods + /// + public class HttpSigningConfiguration + { + #region + /// + /// Initailize the HashAlgorithm and SigningAlgorithm to default value + /// + public HttpSigningConfiguration() + { + HashAlgorithm = HashAlgorithmName.SHA256; + SigningAlgorithm = "PKCS1-v15"; + } + #endregion + + #region Properties + /// + ///Gets the Api keyId + /// + public string KeyId { get; set; } + + /// + /// Gets the Key file path + /// + public string KeyFilePath { get; set; } + + /// + /// Gets the key pass phrase for password protected key + /// + public SecureString KeyPassPhrase { get; set; } + + /// + /// Gets the HTTP signing header + /// + public List HttpSigningHeader { get; set; } + + /// + /// Gets the hash algorithm sha256 or sha512 + /// + public HashAlgorithmName HashAlgorithm { get; set; } + + /// + /// Gets the signing algorithm + /// + public string SigningAlgorithm { get; set; } + + /// + /// Gets the Signature validaty period in seconds + /// + public int SignatureValidityPeriod { get; set; } + + #endregion + + #region enum + private enum PrivateKeyType + { + None = 0, + RSA = 1, + ECDSA = 2, + } + #endregion + + #region Methods + /// + /// Gets the Headers for HttpSigning + /// + /// Base path + /// HTTP method + /// Path + /// Request options + /// + internal Dictionary GetHttpSignedHeader(string basePath,string method, string path, RequestOptions requestOptions) + { + const string HEADER_REQUEST_TARGET = "(request-target)"; + //The time when the HTTP signature expires. The API server should reject HTTP requests + //that have expired. + const string HEADER_EXPIRES = "(expires)"; + //The 'Date' header. + const string HEADER_DATE = "Date"; + //The 'Host' header. + const string HEADER_HOST = "Host"; + //The time when the HTTP signature was generated. + const string HEADER_CREATED = "(created)"; + //When the 'Digest' header is included in the HTTP signature, the client automatically + //computes the digest of the HTTP request body, per RFC 3230. + const string HEADER_DIGEST = "Digest"; + //The 'Authorization' header is automatically generated by the client. It includes + //the list of signed headers and a base64-encoded signature. + const string HEADER_AUTHORIZATION = "Authorization"; + + //Hash table to store singed headers + var HttpSignedRequestHeader = new Dictionary(); + var HttpSignatureHeader = new Dictionary(); + + if (HttpSigningHeader.Count == 0) + { + HttpSigningHeader.Add("(created)"); + } + + if (requestOptions.PathParameters != null) + { + foreach (var pathParam in requestOptions.PathParameters) + { + var tempPath = path.Replace(pathParam.Key, "0"); + path = string.Format(tempPath, pathParam.Value); + } + } + + var httpValues = HttpUtility.ParseQueryString(string.Empty); + foreach (var parameter in requestOptions.QueryParameters) + { +#if (NETCOREAPP) + if (parameter.Value.Count > 1) + { // array + foreach (var value in parameter.Value) + { + httpValues.Add(HttpUtility.UrlEncode(parameter.Key) + "[]", value); + } + } + else + { + httpValues.Add(HttpUtility.UrlEncode(parameter.Key), parameter.Value[0]); + } +#else + if (parameter.Value.Count > 1) + { // array + foreach (var value in parameter.Value) + { + httpValues.Add(parameter.Key + "[]", value); + } + } + else + { + httpValues.Add(parameter.Key, parameter.Value[0]); + } +#endif + } + var uriBuilder = new UriBuilder(string.Concat(basePath, path)); + uriBuilder.Query = httpValues.ToString().Replace("+", "%20"); + + var dateTime = DateTime.Now; + string Digest = string.Empty; + + //get the body + string requestBody = string.Empty; + if (requestOptions.Data != null) + { + var serializerSettings = new JsonSerializerSettings(); + requestBody = JsonConvert.SerializeObject(requestOptions.Data, serializerSettings); + } + + if (HashAlgorithm == HashAlgorithmName.SHA256) + { + var bodyDigest = GetStringHash(HashAlgorithm.ToString(), requestBody); + Digest = string.Format("SHA-256={0}", Convert.ToBase64String(bodyDigest)); + } + else if (HashAlgorithm == HashAlgorithmName.SHA512) + { + var bodyDigest = GetStringHash(HashAlgorithm.ToString(), requestBody); + Digest = string.Format("SHA-512={0}", Convert.ToBase64String(bodyDigest)); + } + else + { + throw new Exception(string.Format("{0} not supported", HashAlgorithm)); + } + + + foreach (var header in HttpSigningHeader) + { + if (header.Equals(HEADER_REQUEST_TARGET)) + { + var targetUrl = string.Format("{0} {1}{2}", method.ToLower(), uriBuilder.Path, uriBuilder.Query); + HttpSignatureHeader.Add(header.ToLower(), targetUrl); + } + else if (header.Equals(HEADER_EXPIRES)) + { + var expireDateTime = dateTime.AddSeconds(SignatureValidityPeriod); + HttpSignatureHeader.Add(header.ToLower(), GetUnixTime(expireDateTime).ToString()); + } + else if (header.Equals(HEADER_DATE)) + { + var utcDateTime = dateTime.ToString("r").ToString(); + HttpSignatureHeader.Add(header.ToLower(), utcDateTime); + HttpSignedRequestHeader.Add(HEADER_DATE, utcDateTime); + } + else if (header.Equals(HEADER_HOST)) + { + HttpSignatureHeader.Add(header.ToLower(), uriBuilder.Host); + HttpSignedRequestHeader.Add(HEADER_HOST, uriBuilder.Host); + } + else if (header.Equals(HEADER_CREATED)) + { + HttpSignatureHeader.Add(header.ToLower(), GetUnixTime(dateTime).ToString()); + } + else if (header.Equals(HEADER_DIGEST)) + { + HttpSignedRequestHeader.Add(HEADER_DIGEST, Digest); + HttpSignatureHeader.Add(header.ToLower(), Digest); + } + else + { + bool isHeaderFound = false; + foreach (var item in requestOptions.HeaderParameters) + { + if (string.Equals(item.Key, header, StringComparison.OrdinalIgnoreCase)) + { + HttpSignatureHeader.Add(header.ToLower(), item.Value.ToString()); + isHeaderFound = true; + break; + } + } + if (!isHeaderFound) + { + throw new Exception(string.Format("Cannot sign HTTP request.Request does not contain the {0} header.",header)); + } + } + + } + var headersKeysString = string.Join(" ", HttpSignatureHeader.Keys); + var headerValuesList = new List(); + + foreach (var keyVal in HttpSignatureHeader) + { + headerValuesList.Add(string.Format("{0}: {1}", keyVal.Key, keyVal.Value)); + + } + //Concatinate headers value separated by new line + var headerValuesString = string.Join("\n", headerValuesList); + var signatureStringHash = GetStringHash(HashAlgorithm.ToString(), headerValuesString); + string headerSignatureStr = null; + var keyType = GetKeyType(KeyFilePath); + + if (keyType == PrivateKeyType.RSA) + { + headerSignatureStr = GetRSASignature(signatureStringHash); + } + else if (keyType == PrivateKeyType.ECDSA) + { + headerSignatureStr = GetECDSASignature(signatureStringHash); + } + var cryptographicScheme = "hs2019"; + var authorizationHeaderValue = string.Format("Signature keyId=\"{0}\",algorithm=\"{1}\"", + 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.Add(HEADER_AUTHORIZATION, authorizationHeaderValue); + + return HttpSignedRequestHeader; + } + + private byte[] GetStringHash(string hashName, string stringToBeHashed) + { + var hashAlgorithm = System.Security.Cryptography.HashAlgorithm.Create(hashName); + var bytes = Encoding.UTF8.GetBytes(stringToBeHashed); + var stringHash = hashAlgorithm.ComputeHash(bytes); + return stringHash; + } + + private int GetUnixTime(DateTime date2) + { + DateTime date1 = new DateTime(1970, 01, 01); + TimeSpan timeSpan = date2 - date1; + return (int)timeSpan.TotalSeconds; + } + + private string GetRSASignature(byte[] stringToSign) + { + RSA rsa = GetRSAProviderFromPemFile(KeyFilePath, KeyPassPhrase); + if (SigningAlgorithm == "RSASSA-PSS") + { + var signedbytes = rsa.SignHash(stringToSign, HashAlgorithm, RSASignaturePadding.Pss); + return Convert.ToBase64String(signedbytes); + } + else if (SigningAlgorithm == "PKCS1-v15") + { + var signedbytes = rsa.SignHash(stringToSign, HashAlgorithm, RSASignaturePadding.Pkcs1); + return Convert.ToBase64String(signedbytes); + } + return string.Empty; + } + + /// + /// Gets the ECDSA signature + /// + /// + /// + private string GetECDSASignature(byte[] dataToSign) + { + if (!File.Exists(KeyFilePath)) + { + throw new Exception("key file path does not exist."); + } + + var ecKeyHeader = "-----BEGIN EC PRIVATE KEY-----"; + var ecKeyFooter = "-----END EC PRIVATE KEY-----"; + var keyStr = File.ReadAllText(KeyFilePath); + var ecKeyBase64String = keyStr.Replace(ecKeyHeader, "").Replace(ecKeyFooter, "").Trim(); + var keyBytes = System.Convert.FromBase64String(ecKeyBase64String); + var ecdsa = ECDsa.Create(); + +#if (NETCOREAPP3_0 || NETCOREAPP3_1 || NET5_0) + var byteCount = 0; + if (KeyPassPhrase != null) + { + IntPtr unmanagedString = IntPtr.Zero; + try + { + // convert secure string to byte array + unmanagedString = Marshal.SecureStringToGlobalAllocUnicode(KeyPassPhrase); + ecdsa.ImportEncryptedPkcs8PrivateKey(Encoding.UTF8.GetBytes(Marshal.PtrToStringUni(unmanagedString)), keyBytes, out byteCount); + } + finally + { + if (unmanagedString != IntPtr.Zero) + { + Marshal.ZeroFreeBSTR(unmanagedString); + } + } + } + else + { + ecdsa.ImportPkcs8PrivateKey(keyBytes, out byteCount); + } + var signedBytes = ecdsa.SignHash(dataToSign); + var derBytes = ConvertToECDSAANS1Format(signedBytes); + var signedString = System.Convert.ToBase64String(derBytes); + + return signedString; +#else + throw new Exception("ECDSA signing is supported only on NETCOREAPP3_0 and above"); +#endif + + } + + private byte[] ConvertToECDSAANS1Format(byte[] signedBytes) + { + var derBytes = new List(); + byte derLength = 68; //default lenght for ECDSA code signinged bit 0x44 + byte rbytesLength = 32; //R length 0x20 + byte sbytesLength = 32; //S length 0x20 + var rBytes = new List(); + var sBytes = new List(); + for (int i = 0; i < 32; i++) + { + rBytes.Add(signedBytes[i]); + } + for (int i = 32; i < 64; i++) + { + sBytes.Add(signedBytes[i]); + } + + if (rBytes[0] > 0x7F) + { + derLength++; + rbytesLength++; + var tempBytes = new List(); + tempBytes.AddRange(rBytes); + rBytes.Clear(); + rBytes.Add(0x00); + rBytes.AddRange(tempBytes); + } + + if (sBytes[0] > 0x7F) + { + derLength++; + sbytesLength++; + var tempBytes = new List(); + tempBytes.AddRange(sBytes); + sBytes.Clear(); + sBytes.Add(0x00); + sBytes.AddRange(tempBytes); + + } + + derBytes.Add(48); //start of the sequence 0x30 + derBytes.Add(derLength); //total length r lenth, type and r bytes + + derBytes.Add(2); //tag for integer + derBytes.Add(rbytesLength); //length of r + derBytes.AddRange(rBytes); + + derBytes.Add(2); //tag for integer + derBytes.Add(sbytesLength); //length of s + derBytes.AddRange(sBytes); + return derBytes.ToArray(); + } + + private RSACryptoServiceProvider GetRSAProviderFromPemFile(string pemfile, SecureString keyPassPharse = 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, keyPassPharse); + if (pemkey == null) + { + return null; + } + return DecodeRSAPrivateKey(pemkey); + } + return null; + } + + private byte[] ConvertPrivateKeyToBytes(string instr, SecureString keyPassPharse = 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 fromat + return null; + } + + byte[] deskey = GetEncryptedKey(salt, keyPassPharse, 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; + } + } + + private RSACryptoServiceProvider DecodeRSAPrivateKey(byte[] privkey) + { + byte[] MODULUS, E, D, P, Q, DP, DQ, IQ; + + // --------- 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); + MODULUS = binr.ReadBytes(elems); + + elems = GetIntegerSize(binr); + E = binr.ReadBytes(elems); + + elems = GetIntegerSize(binr); + D = binr.ReadBytes(elems); + + elems = GetIntegerSize(binr); + P = binr.ReadBytes(elems); + + elems = GetIntegerSize(binr); + Q = binr.ReadBytes(elems); + + elems = GetIntegerSize(binr); + DP = binr.ReadBytes(elems); + + elems = GetIntegerSize(binr); + DQ = binr.ReadBytes(elems); + + elems = GetIntegerSize(binr); + IQ = binr.ReadBytes(elems); + + // ------- create RSACryptoServiceProvider instance and initialize with public key ----- + RSACryptoServiceProvider RSA = new RSACryptoServiceProvider(); + RSAParameters RSAparams = new RSAParameters(); + RSAparams.Modulus = MODULUS; + RSAparams.Exponent = E; + RSAparams.D = D; + RSAparams.P = P; + RSAparams.Q = Q; + RSAparams.DP = DP; + RSAparams.DQ = DQ; + RSAparams.InverseQ = IQ; + RSA.ImportParameters(RSAparams); + return RSA; + } + catch (Exception) + { + return null; + } + finally + { + binr.Close(); + } + } + + private 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; + } + + private byte[] GetEncryptedKey(byte[] salt, SecureString secpswd, int count, int miter) + { + IntPtr unmanagedPswd = IntPtr.Zero; + int HASHLENGTH = 16; //MD5 bytes + byte[] keymaterial = new byte[HASHLENGTH * miter]; //to store contatenated Mi hashed results + + byte[] psbytes = new byte[secpswd.Length]; + unmanagedPswd = Marshal.SecureStringToGlobalAllocAnsi(secpswd); + Marshal.Copy(unmanagedPswd, psbytes, 0, psbytes.Length); + Marshal.ZeroFreeGlobalAllocAnsi(unmanagedPswd); + + // --- contatenate 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 contatenate 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); //contatenate 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; + } + + private 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; + } + + /// + /// Detect the key type from the pem file. + /// + /// key file path in pem format + /// + private PrivateKeyType GetKeyType(string keyFilePath) + { + if (!File.Exists(keyFilePath)) + { + throw new Exception("Key file path does not exist."); + } + + var ecPrivateKeyHeader = "BEGIN EC PRIVATE KEY"; + var ecPrivateKeyFooter = "END EC PRIVATE KEY"; + var rsaPrivateKeyHeader = "BEGIN RSA PRIVATE KEY"; + var rsaPrivateFooter = "END RSA PRIVATE KEY"; + //var pkcs8Header = "BEGIN PRIVATE KEY"; + //var pkcs8Footer = "END PRIVATE KEY"; + var keyType = PrivateKeyType.None; + var key = File.ReadAllLines(keyFilePath); + + if (key[0].ToString().Contains(rsaPrivateKeyHeader) && + key[key.Length - 1].ToString().Contains(rsaPrivateFooter)) + { + keyType = PrivateKeyType.RSA; + } + else if (key[0].ToString().Contains(ecPrivateKeyHeader) && + key[key.Length - 1].ToString().Contains(ecPrivateKeyFooter)) + { + keyType = PrivateKeyType.ECDSA; + } + else if (key[0].ToString().Contains(ecPrivateKeyHeader) && + key[key.Length - 1].ToString().Contains(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 = PrivateKeyType.ECDSA; + } + else + { + throw new Exception("Either the key is invalid or key is not supported"); + + } + return keyType; + } + #endregion + } +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Client/IApiAccessor.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Client/IApiAccessor.cs new file mode 100644 index 00000000000..2bd76416004 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Client/IApiAccessor.cs @@ -0,0 +1,37 @@ +/* + * 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; + +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-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Client/IAsynchronousClient.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Client/IAsynchronousClient.cs new file mode 100644 index 00000000000..601e86d561c --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Client/IAsynchronousClient.cs @@ -0,0 +1,100 @@ +/* + * 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.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-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Client/IReadableConfiguration.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Client/IReadableConfiguration.cs new file mode 100644 index 00000000000..141e65a5b72 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Client/IReadableConfiguration.cs @@ -0,0 +1,120 @@ +/* + * 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.Generic; +using System.Net; +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 foramt. + 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; } + + /// + /// Gets the API key with prefix. + /// + /// API key identifier (authentication scheme). + /// API key with prefix. + string GetApiKeyWithPrefix(string apiKeyIdentifier); + + /// + /// Gets certificate collection to be sent with requests. + /// + /// X509 Certificate collection. + X509CertificateCollection ClientCertificates { get; } + + /// + /// Gets the HttpSigning configuration + /// + HttpSigningConfiguration HttpSigningConfiguration { get; } + } +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Client/ISynchronousClient.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Client/ISynchronousClient.cs new file mode 100644 index 00000000000..0e0a7fedacf --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Client/ISynchronousClient.cs @@ -0,0 +1,93 @@ +/* + * 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.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-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Client/Multimap.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Client/Multimap.cs new file mode 100644 index 00000000000..738a64c570b --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Client/Multimap.cs @@ -0,0 +1,295 @@ +/* + * 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; + +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-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Client/OpenAPIDateConverter.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Client/OpenAPIDateConverter.cs new file mode 100644 index 00000000000..a5253e58201 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Client/OpenAPIDateConverter.cs @@ -0,0 +1,29 @@ +/* + * 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 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-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Client/RequestOptions.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Client/RequestOptions.cs new file mode 100644 index 00000000000..7a1d5b97a88 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Client/RequestOptions.cs @@ -0,0 +1,74 @@ +/* + * 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.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 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 Dictionary FileParameters { get; set; } + + /// + /// Cookies to be sent along with the request. + /// + public List Cookies { 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 Dictionary(); + Cookies = new List(); + } + } +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Client/RetryConfiguration.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Client/RetryConfiguration.cs new file mode 100644 index 00000000000..c93633a36d9 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Client/RetryConfiguration.cs @@ -0,0 +1,21 @@ +using Polly; +using RestSharp; + +namespace Org.OpenAPITools.Client +{ + /// + /// Configuration class to set the polly retry policies to be applied to the requests. + /// + public 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-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/AbstractOpenAPISchema.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/AbstractOpenAPISchema.cs new file mode 100644 index 00000000000..b3fc4c3c7a3 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/AbstractOpenAPISchema.cs @@ -0,0 +1,76 @@ +/* + * 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 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-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/AdditionalPropertiesClass.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/AdditionalPropertiesClass.cs new file mode 100644 index 00000000000..8a3ae3533a0 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/AdditionalPropertiesClass.cs @@ -0,0 +1,350 @@ +/* + * 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 +{ + /// + /// AdditionalPropertiesClass + /// + [DataContract(Name = "AdditionalPropertiesClass")] + public partial class AdditionalPropertiesClass : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// mapProperty. + /// mapOfMapProperty. + /// anytype1. + /// mapWithUndeclaredPropertiesAnytype1. + /// mapWithUndeclaredPropertiesAnytype2. + /// mapWithUndeclaredPropertiesAnytype3. + /// an object with no declared properties and no undeclared properties, hence it's an empty map.. + /// mapWithUndeclaredPropertiesString. + public AdditionalPropertiesClass(Dictionary mapProperty = default(Dictionary), Dictionary> mapOfMapProperty = default(Dictionary>), Object anytype1 = default(Object), Object mapWithUndeclaredPropertiesAnytype1 = default(Object), Object mapWithUndeclaredPropertiesAnytype2 = default(Object), Dictionary mapWithUndeclaredPropertiesAnytype3 = default(Dictionary), Object emptyMap = default(Object), Dictionary mapWithUndeclaredPropertiesString = default(Dictionary)) + { + this._MapProperty = mapProperty; + this._MapOfMapProperty = mapOfMapProperty; + this._Anytype1 = anytype1; + this._MapWithUndeclaredPropertiesAnytype1 = mapWithUndeclaredPropertiesAnytype1; + this._MapWithUndeclaredPropertiesAnytype2 = mapWithUndeclaredPropertiesAnytype2; + this._MapWithUndeclaredPropertiesAnytype3 = mapWithUndeclaredPropertiesAnytype3; + this._EmptyMap = emptyMap; + this._MapWithUndeclaredPropertiesString = mapWithUndeclaredPropertiesString; + this.AdditionalProperties = new Dictionary(); + } + + /// + /// Gets or Sets MapProperty + /// + [DataMember(Name = "map_property", EmitDefaultValue = false)] + public Dictionary MapProperty + { + get{ return _MapProperty;} + set + { + _MapProperty = value; + _flagMapProperty = true; + } + } + private Dictionary _MapProperty; + private bool _flagMapProperty; + + /// + /// Returns false as MapProperty should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeMapProperty() + { + return _flagMapProperty; + } + /// + /// Gets or Sets MapOfMapProperty + /// + [DataMember(Name = "map_of_map_property", EmitDefaultValue = false)] + public Dictionary> MapOfMapProperty + { + get{ return _MapOfMapProperty;} + set + { + _MapOfMapProperty = value; + _flagMapOfMapProperty = true; + } + } + private Dictionary> _MapOfMapProperty; + private bool _flagMapOfMapProperty; + + /// + /// Returns false as MapOfMapProperty should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeMapOfMapProperty() + { + return _flagMapOfMapProperty; + } + /// + /// Gets or Sets Anytype1 + /// + [DataMember(Name = "anytype_1", EmitDefaultValue = true)] + public Object Anytype1 + { + get{ return _Anytype1;} + set + { + _Anytype1 = value; + _flagAnytype1 = true; + } + } + private Object _Anytype1; + private bool _flagAnytype1; + + /// + /// Returns false as Anytype1 should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeAnytype1() + { + return _flagAnytype1; + } + /// + /// Gets or Sets MapWithUndeclaredPropertiesAnytype1 + /// + [DataMember(Name = "map_with_undeclared_properties_anytype_1", EmitDefaultValue = false)] + public Object MapWithUndeclaredPropertiesAnytype1 + { + get{ return _MapWithUndeclaredPropertiesAnytype1;} + set + { + _MapWithUndeclaredPropertiesAnytype1 = value; + _flagMapWithUndeclaredPropertiesAnytype1 = true; + } + } + private Object _MapWithUndeclaredPropertiesAnytype1; + private bool _flagMapWithUndeclaredPropertiesAnytype1; + + /// + /// Returns false as MapWithUndeclaredPropertiesAnytype1 should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeMapWithUndeclaredPropertiesAnytype1() + { + return _flagMapWithUndeclaredPropertiesAnytype1; + } + /// + /// Gets or Sets MapWithUndeclaredPropertiesAnytype2 + /// + [DataMember(Name = "map_with_undeclared_properties_anytype_2", EmitDefaultValue = false)] + public Object MapWithUndeclaredPropertiesAnytype2 + { + get{ return _MapWithUndeclaredPropertiesAnytype2;} + set + { + _MapWithUndeclaredPropertiesAnytype2 = value; + _flagMapWithUndeclaredPropertiesAnytype2 = true; + } + } + private Object _MapWithUndeclaredPropertiesAnytype2; + private bool _flagMapWithUndeclaredPropertiesAnytype2; + + /// + /// Returns false as MapWithUndeclaredPropertiesAnytype2 should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeMapWithUndeclaredPropertiesAnytype2() + { + return _flagMapWithUndeclaredPropertiesAnytype2; + } + /// + /// Gets or Sets MapWithUndeclaredPropertiesAnytype3 + /// + [DataMember(Name = "map_with_undeclared_properties_anytype_3", EmitDefaultValue = false)] + public Dictionary MapWithUndeclaredPropertiesAnytype3 + { + get{ return _MapWithUndeclaredPropertiesAnytype3;} + set + { + _MapWithUndeclaredPropertiesAnytype3 = value; + _flagMapWithUndeclaredPropertiesAnytype3 = true; + } + } + private Dictionary _MapWithUndeclaredPropertiesAnytype3; + private bool _flagMapWithUndeclaredPropertiesAnytype3; + + /// + /// Returns false as MapWithUndeclaredPropertiesAnytype3 should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeMapWithUndeclaredPropertiesAnytype3() + { + return _flagMapWithUndeclaredPropertiesAnytype3; + } + /// + /// 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. + [DataMember(Name = "empty_map", EmitDefaultValue = false)] + public Object EmptyMap + { + get{ return _EmptyMap;} + set + { + _EmptyMap = value; + _flagEmptyMap = true; + } + } + private Object _EmptyMap; + private bool _flagEmptyMap; + + /// + /// Returns false as EmptyMap should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeEmptyMap() + { + return _flagEmptyMap; + } + /// + /// Gets or Sets MapWithUndeclaredPropertiesString + /// + [DataMember(Name = "map_with_undeclared_properties_string", EmitDefaultValue = false)] + public Dictionary MapWithUndeclaredPropertiesString + { + get{ return _MapWithUndeclaredPropertiesString;} + set + { + _MapWithUndeclaredPropertiesString = value; + _flagMapWithUndeclaredPropertiesString = true; + } + } + private Dictionary _MapWithUndeclaredPropertiesString; + private bool _flagMapWithUndeclaredPropertiesString; + + /// + /// Returns false as MapWithUndeclaredPropertiesString should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeMapWithUndeclaredPropertiesString() + { + return _flagMapWithUndeclaredPropertiesString; + } + /// + /// 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() + { + var sb = new StringBuilder(); + sb.Append("class AdditionalPropertiesClass {\n"); + sb.Append(" MapProperty: ").Append(MapProperty).Append("\n"); + sb.Append(" MapOfMapProperty: ").Append(MapOfMapProperty).Append("\n"); + sb.Append(" Anytype1: ").Append(Anytype1).Append("\n"); + sb.Append(" MapWithUndeclaredPropertiesAnytype1: ").Append(MapWithUndeclaredPropertiesAnytype1).Append("\n"); + sb.Append(" MapWithUndeclaredPropertiesAnytype2: ").Append(MapWithUndeclaredPropertiesAnytype2).Append("\n"); + sb.Append(" MapWithUndeclaredPropertiesAnytype3: ").Append(MapWithUndeclaredPropertiesAnytype3).Append("\n"); + sb.Append(" EmptyMap: ").Append(EmptyMap).Append("\n"); + sb.Append(" MapWithUndeclaredPropertiesString: ").Append(MapWithUndeclaredPropertiesString).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 AdditionalPropertiesClass).AreEqual; + } + + /// + /// Returns true if AdditionalPropertiesClass instances are equal + /// + /// Instance of AdditionalPropertiesClass to be compared + /// Boolean + public bool Equals(AdditionalPropertiesClass 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.MapProperty != null) + hashCode = hashCode * 59 + this.MapProperty.GetHashCode(); + if (this.MapOfMapProperty != null) + hashCode = hashCode * 59 + this.MapOfMapProperty.GetHashCode(); + if (this.Anytype1 != null) + hashCode = hashCode * 59 + this.Anytype1.GetHashCode(); + if (this.MapWithUndeclaredPropertiesAnytype1 != null) + hashCode = hashCode * 59 + this.MapWithUndeclaredPropertiesAnytype1.GetHashCode(); + if (this.MapWithUndeclaredPropertiesAnytype2 != null) + hashCode = hashCode * 59 + this.MapWithUndeclaredPropertiesAnytype2.GetHashCode(); + if (this.MapWithUndeclaredPropertiesAnytype3 != null) + hashCode = hashCode * 59 + this.MapWithUndeclaredPropertiesAnytype3.GetHashCode(); + if (this.EmptyMap != null) + hashCode = hashCode * 59 + this.EmptyMap.GetHashCode(); + if (this.MapWithUndeclaredPropertiesString != null) + hashCode = hashCode * 59 + this.MapWithUndeclaredPropertiesString.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-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Animal.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Animal.cs new file mode 100644 index 00000000000..9e554565830 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Animal.cs @@ -0,0 +1,199 @@ +/* + * 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 JsonSubTypes; +using System.ComponentModel.DataAnnotations; +using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; +using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; + +namespace Org.OpenAPITools.Model +{ + /// + /// Animal + /// + [DataContract(Name = "Animal")] + [JsonConverter(typeof(JsonSubtypes), "ClassName")] + [JsonSubtypes.KnownSubType(typeof(Cat), "Cat")] + [JsonSubtypes.KnownSubType(typeof(Dog), "Dog")] + public partial class Animal : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + [JsonConstructorAttribute] + protected Animal() + { + this.AdditionalProperties = new Dictionary(); + } + /// + /// Initializes a new instance of the class. + /// + /// className (required). + /// color (default to "red"). + public Animal(string className = default(string), string color = "red") + { + // to ensure "className" is required (not null) + this._ClassName = className ?? throw new ArgumentNullException("className is a required property for Animal and cannot be null"); + // use default value if no "color" provided + this.Color = color ?? "red"; + this.AdditionalProperties = new Dictionary(); + } + + /// + /// Gets or Sets ClassName + /// + [DataMember(Name = "className", IsRequired = true, EmitDefaultValue = false)] + public string ClassName + { + get{ return _ClassName;} + set + { + _ClassName = value; + _flagClassName = true; + } + } + private string _ClassName; + private bool _flagClassName; + + /// + /// Returns false as ClassName should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeClassName() + { + return _flagClassName; + } + /// + /// Gets or Sets Color + /// + [DataMember(Name = "color", EmitDefaultValue = false)] + public string Color + { + get{ return _Color;} + set + { + _Color = value; + _flagColor = true; + } + } + private string _Color; + private bool _flagColor; + + /// + /// Returns false as Color should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeColor() + { + return _flagColor; + } + /// + /// 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() + { + var sb = new StringBuilder(); + sb.Append("class Animal {\n"); + sb.Append(" ClassName: ").Append(ClassName).Append("\n"); + sb.Append(" Color: ").Append(Color).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 Animal).AreEqual; + } + + /// + /// Returns true if Animal instances are equal + /// + /// Instance of Animal to be compared + /// Boolean + public bool Equals(Animal 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.ClassName != null) + hashCode = hashCode * 59 + this.ClassName.GetHashCode(); + if (this.Color != null) + hashCode = hashCode * 59 + this.Color.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) + { + 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-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/ApiResponse.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/ApiResponse.cs new file mode 100644 index 00000000000..7e4ec34e624 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/ApiResponse.cs @@ -0,0 +1,203 @@ +/* + * 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 +{ + /// + /// ApiResponse + /// + [DataContract(Name = "ApiResponse")] + public partial class ApiResponse : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// code. + /// type. + /// message. + public ApiResponse(int code = default(int), string type = default(string), string message = default(string)) + { + this._Code = code; + this._Type = type; + this._Message = message; + this.AdditionalProperties = new Dictionary(); + } + + /// + /// Gets or Sets Code + /// + [DataMember(Name = "code", EmitDefaultValue = false)] + public int Code + { + get{ return _Code;} + set + { + _Code = value; + _flagCode = true; + } + } + private int _Code; + private bool _flagCode; + + /// + /// Returns false as Code should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeCode() + { + return _flagCode; + } + /// + /// Gets or Sets Type + /// + [DataMember(Name = "type", EmitDefaultValue = false)] + public string Type + { + get{ return _Type;} + set + { + _Type = value; + _flagType = true; + } + } + private string _Type; + private bool _flagType; + + /// + /// Returns false as Type should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeType() + { + return _flagType; + } + /// + /// Gets or Sets Message + /// + [DataMember(Name = "message", EmitDefaultValue = false)] + public string Message + { + get{ return _Message;} + set + { + _Message = value; + _flagMessage = true; + } + } + private string _Message; + private bool _flagMessage; + + /// + /// Returns false as Message should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeMessage() + { + return _flagMessage; + } + /// + /// 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() + { + var sb = new StringBuilder(); + sb.Append("class ApiResponse {\n"); + sb.Append(" Code: ").Append(Code).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append(" Message: ").Append(Message).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 ApiResponse).AreEqual; + } + + /// + /// Returns true if ApiResponse instances are equal + /// + /// Instance of ApiResponse to be compared + /// Boolean + public bool Equals(ApiResponse 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; + hashCode = hashCode * 59 + this.Code.GetHashCode(); + if (this.Type != null) + hashCode = hashCode * 59 + this.Type.GetHashCode(); + if (this.Message != null) + hashCode = hashCode * 59 + this.Message.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-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Apple.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Apple.cs new file mode 100644 index 00000000000..1ffbb0c0951 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Apple.cs @@ -0,0 +1,189 @@ +/* + * 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 +{ + /// + /// Apple + /// + [DataContract(Name = "apple")] + public partial class Apple : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// cultivar. + /// origin. + public Apple(string cultivar = default(string), string origin = default(string)) + { + this._Cultivar = cultivar; + this._Origin = origin; + this.AdditionalProperties = new Dictionary(); + } + + /// + /// Gets or Sets Cultivar + /// + [DataMember(Name = "cultivar", EmitDefaultValue = false)] + public string Cultivar + { + get{ return _Cultivar;} + set + { + _Cultivar = value; + _flagCultivar = true; + } + } + private string _Cultivar; + private bool _flagCultivar; + + /// + /// Returns false as Cultivar should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeCultivar() + { + return _flagCultivar; + } + /// + /// Gets or Sets Origin + /// + [DataMember(Name = "origin", EmitDefaultValue = false)] + public string Origin + { + get{ return _Origin;} + set + { + _Origin = value; + _flagOrigin = true; + } + } + private string _Origin; + private bool _flagOrigin; + + /// + /// Returns false as Origin should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeOrigin() + { + return _flagOrigin; + } + /// + /// 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() + { + var sb = new StringBuilder(); + sb.Append("class Apple {\n"); + sb.Append(" Cultivar: ").Append(Cultivar).Append("\n"); + sb.Append(" Origin: ").Append(Origin).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 Apple).AreEqual; + } + + /// + /// Returns true if Apple instances are equal + /// + /// Instance of Apple to be compared + /// Boolean + public bool Equals(Apple 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.Cultivar != null) + hashCode = hashCode * 59 + this.Cultivar.GetHashCode(); + if (this.Origin != null) + hashCode = hashCode * 59 + this.Origin.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) + { + // Cultivar (string) pattern + Regex regexCultivar = new Regex(@"^[a-zA-Z\\s]*$", RegexOptions.CultureInvariant); + if (false == regexCultivar.Match(this.Cultivar).Success) + { + yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Cultivar, must match a pattern of " + regexCultivar, new [] { "Cultivar" }); + } + + // Origin (string) pattern + Regex regexOrigin = new Regex(@"^[A-Z\\s]*$", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase); + if (false == regexOrigin.Match(this.Origin).Success) + { + yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Origin, must match a pattern of " + regexOrigin, new [] { "Origin" }); + } + + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/AppleReq.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/AppleReq.cs new file mode 100644 index 00000000000..f0fc8d536b0 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/AppleReq.cs @@ -0,0 +1,170 @@ +/* + * 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 +{ + /// + /// AppleReq + /// + [DataContract(Name = "appleReq")] + public partial class AppleReq : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + [JsonConstructorAttribute] + protected AppleReq() { } + /// + /// Initializes a new instance of the class. + /// + /// cultivar (required). + /// mealy. + public AppleReq(string cultivar = default(string), bool mealy = default(bool)) + { + // to ensure "cultivar" is required (not null) + this._Cultivar = cultivar ?? throw new ArgumentNullException("cultivar is a required property for AppleReq and cannot be null"); + this._Mealy = mealy; + } + + /// + /// Gets or Sets Cultivar + /// + [DataMember(Name = "cultivar", IsRequired = true, EmitDefaultValue = false)] + public string Cultivar + { + get{ return _Cultivar;} + set + { + _Cultivar = value; + _flagCultivar = true; + } + } + private string _Cultivar; + private bool _flagCultivar; + + /// + /// Returns false as Cultivar should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeCultivar() + { + return _flagCultivar; + } + /// + /// Gets or Sets Mealy + /// + [DataMember(Name = "mealy", EmitDefaultValue = true)] + public bool Mealy + { + get{ return _Mealy;} + set + { + _Mealy = value; + _flagMealy = true; + } + } + private bool _Mealy; + private bool _flagMealy; + + /// + /// Returns false as Mealy should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeMealy() + { + return _flagMealy; + } + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + var sb = new StringBuilder(); + sb.Append("class AppleReq {\n"); + sb.Append(" Cultivar: ").Append(Cultivar).Append("\n"); + sb.Append(" Mealy: ").Append(Mealy).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 AppleReq).AreEqual; + } + + /// + /// Returns true if AppleReq instances are equal + /// + /// Instance of AppleReq to be compared + /// Boolean + public bool Equals(AppleReq 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.Cultivar != null) + hashCode = hashCode * 59 + this.Cultivar.GetHashCode(); + hashCode = hashCode * 59 + this.Mealy.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-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/ArrayOfArrayOfNumberOnly.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/ArrayOfArrayOfNumberOnly.cs new file mode 100644 index 00000000000..99d5a446460 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/ArrayOfArrayOfNumberOnly.cs @@ -0,0 +1,146 @@ +/* + * 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 +{ + /// + /// ArrayOfArrayOfNumberOnly + /// + [DataContract(Name = "ArrayOfArrayOfNumberOnly")] + public partial class ArrayOfArrayOfNumberOnly : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// arrayArrayNumber. + public ArrayOfArrayOfNumberOnly(List> arrayArrayNumber = default(List>)) + { + this._ArrayArrayNumber = arrayArrayNumber; + this.AdditionalProperties = new Dictionary(); + } + + /// + /// Gets or Sets ArrayArrayNumber + /// + [DataMember(Name = "ArrayArrayNumber", EmitDefaultValue = false)] + public List> ArrayArrayNumber + { + get{ return _ArrayArrayNumber;} + set + { + _ArrayArrayNumber = value; + _flagArrayArrayNumber = true; + } + } + private List> _ArrayArrayNumber; + private bool _flagArrayArrayNumber; + + /// + /// Returns false as ArrayArrayNumber should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeArrayArrayNumber() + { + return _flagArrayArrayNumber; + } + /// + /// 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() + { + var sb = new StringBuilder(); + sb.Append("class ArrayOfArrayOfNumberOnly {\n"); + sb.Append(" ArrayArrayNumber: ").Append(ArrayArrayNumber).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 ArrayOfArrayOfNumberOnly).AreEqual; + } + + /// + /// Returns true if ArrayOfArrayOfNumberOnly instances are equal + /// + /// Instance of ArrayOfArrayOfNumberOnly to be compared + /// Boolean + public bool Equals(ArrayOfArrayOfNumberOnly 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.ArrayArrayNumber != null) + hashCode = hashCode * 59 + this.ArrayArrayNumber.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-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/ArrayOfNumberOnly.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/ArrayOfNumberOnly.cs new file mode 100644 index 00000000000..7aa2e525878 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/ArrayOfNumberOnly.cs @@ -0,0 +1,146 @@ +/* + * 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 +{ + /// + /// ArrayOfNumberOnly + /// + [DataContract(Name = "ArrayOfNumberOnly")] + public partial class ArrayOfNumberOnly : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// arrayNumber. + public ArrayOfNumberOnly(List arrayNumber = default(List)) + { + this._ArrayNumber = arrayNumber; + this.AdditionalProperties = new Dictionary(); + } + + /// + /// Gets or Sets ArrayNumber + /// + [DataMember(Name = "ArrayNumber", EmitDefaultValue = false)] + public List ArrayNumber + { + get{ return _ArrayNumber;} + set + { + _ArrayNumber = value; + _flagArrayNumber = true; + } + } + private List _ArrayNumber; + private bool _flagArrayNumber; + + /// + /// Returns false as ArrayNumber should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeArrayNumber() + { + return _flagArrayNumber; + } + /// + /// 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() + { + var sb = new StringBuilder(); + sb.Append("class ArrayOfNumberOnly {\n"); + sb.Append(" ArrayNumber: ").Append(ArrayNumber).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 ArrayOfNumberOnly).AreEqual; + } + + /// + /// Returns true if ArrayOfNumberOnly instances are equal + /// + /// Instance of ArrayOfNumberOnly to be compared + /// Boolean + public bool Equals(ArrayOfNumberOnly 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.ArrayNumber != null) + hashCode = hashCode * 59 + this.ArrayNumber.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-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/ArrayTest.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/ArrayTest.cs new file mode 100644 index 00000000000..a35053405f3 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/ArrayTest.cs @@ -0,0 +1,204 @@ +/* + * 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 +{ + /// + /// ArrayTest + /// + [DataContract(Name = "ArrayTest")] + public partial class ArrayTest : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// arrayOfString. + /// arrayArrayOfInteger. + /// arrayArrayOfModel. + public ArrayTest(List arrayOfString = default(List), List> arrayArrayOfInteger = default(List>), List> arrayArrayOfModel = default(List>)) + { + this._ArrayOfString = arrayOfString; + this._ArrayArrayOfInteger = arrayArrayOfInteger; + this._ArrayArrayOfModel = arrayArrayOfModel; + this.AdditionalProperties = new Dictionary(); + } + + /// + /// Gets or Sets ArrayOfString + /// + [DataMember(Name = "array_of_string", EmitDefaultValue = false)] + public List ArrayOfString + { + get{ return _ArrayOfString;} + set + { + _ArrayOfString = value; + _flagArrayOfString = true; + } + } + private List _ArrayOfString; + private bool _flagArrayOfString; + + /// + /// Returns false as ArrayOfString should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeArrayOfString() + { + return _flagArrayOfString; + } + /// + /// Gets or Sets ArrayArrayOfInteger + /// + [DataMember(Name = "array_array_of_integer", EmitDefaultValue = false)] + public List> ArrayArrayOfInteger + { + get{ return _ArrayArrayOfInteger;} + set + { + _ArrayArrayOfInteger = value; + _flagArrayArrayOfInteger = true; + } + } + private List> _ArrayArrayOfInteger; + private bool _flagArrayArrayOfInteger; + + /// + /// Returns false as ArrayArrayOfInteger should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeArrayArrayOfInteger() + { + return _flagArrayArrayOfInteger; + } + /// + /// Gets or Sets ArrayArrayOfModel + /// + [DataMember(Name = "array_array_of_model", EmitDefaultValue = false)] + public List> ArrayArrayOfModel + { + get{ return _ArrayArrayOfModel;} + set + { + _ArrayArrayOfModel = value; + _flagArrayArrayOfModel = true; + } + } + private List> _ArrayArrayOfModel; + private bool _flagArrayArrayOfModel; + + /// + /// Returns false as ArrayArrayOfModel should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeArrayArrayOfModel() + { + return _flagArrayArrayOfModel; + } + /// + /// 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() + { + var sb = new StringBuilder(); + sb.Append("class ArrayTest {\n"); + sb.Append(" ArrayOfString: ").Append(ArrayOfString).Append("\n"); + sb.Append(" ArrayArrayOfInteger: ").Append(ArrayArrayOfInteger).Append("\n"); + sb.Append(" ArrayArrayOfModel: ").Append(ArrayArrayOfModel).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 ArrayTest).AreEqual; + } + + /// + /// Returns true if ArrayTest instances are equal + /// + /// Instance of ArrayTest to be compared + /// Boolean + public bool Equals(ArrayTest 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.ArrayOfString != null) + hashCode = hashCode * 59 + this.ArrayOfString.GetHashCode(); + if (this.ArrayArrayOfInteger != null) + hashCode = hashCode * 59 + this.ArrayArrayOfInteger.GetHashCode(); + if (this.ArrayArrayOfModel != null) + hashCode = hashCode * 59 + this.ArrayArrayOfModel.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-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Banana.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Banana.cs new file mode 100644 index 00000000000..74fce16d819 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Banana.cs @@ -0,0 +1,145 @@ +/* + * 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 +{ + /// + /// Banana + /// + [DataContract(Name = "banana")] + public partial class Banana : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// lengthCm. + public Banana(decimal lengthCm = default(decimal)) + { + this._LengthCm = lengthCm; + this.AdditionalProperties = new Dictionary(); + } + + /// + /// Gets or Sets LengthCm + /// + [DataMember(Name = "lengthCm", EmitDefaultValue = false)] + public decimal LengthCm + { + get{ return _LengthCm;} + set + { + _LengthCm = value; + _flagLengthCm = true; + } + } + private decimal _LengthCm; + private bool _flagLengthCm; + + /// + /// Returns false as LengthCm should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeLengthCm() + { + return _flagLengthCm; + } + /// + /// 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() + { + var sb = new StringBuilder(); + sb.Append("class Banana {\n"); + sb.Append(" LengthCm: ").Append(LengthCm).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 Banana).AreEqual; + } + + /// + /// Returns true if Banana instances are equal + /// + /// Instance of Banana to be compared + /// Boolean + public bool Equals(Banana 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; + hashCode = hashCode * 59 + this.LengthCm.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-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/BananaReq.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/BananaReq.cs new file mode 100644 index 00000000000..82e049f2eab --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/BananaReq.cs @@ -0,0 +1,168 @@ +/* + * 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 +{ + /// + /// BananaReq + /// + [DataContract(Name = "bananaReq")] + public partial class BananaReq : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + [JsonConstructorAttribute] + protected BananaReq() { } + /// + /// Initializes a new instance of the class. + /// + /// lengthCm (required). + /// sweet. + public BananaReq(decimal lengthCm = default(decimal), bool sweet = default(bool)) + { + this._LengthCm = lengthCm; + this._Sweet = sweet; + } + + /// + /// Gets or Sets LengthCm + /// + [DataMember(Name = "lengthCm", IsRequired = true, EmitDefaultValue = false)] + public decimal LengthCm + { + get{ return _LengthCm;} + set + { + _LengthCm = value; + _flagLengthCm = true; + } + } + private decimal _LengthCm; + private bool _flagLengthCm; + + /// + /// Returns false as LengthCm should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeLengthCm() + { + return _flagLengthCm; + } + /// + /// Gets or Sets Sweet + /// + [DataMember(Name = "sweet", EmitDefaultValue = true)] + public bool Sweet + { + get{ return _Sweet;} + set + { + _Sweet = value; + _flagSweet = true; + } + } + private bool _Sweet; + private bool _flagSweet; + + /// + /// Returns false as Sweet should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeSweet() + { + return _flagSweet; + } + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + var sb = new StringBuilder(); + sb.Append("class BananaReq {\n"); + sb.Append(" LengthCm: ").Append(LengthCm).Append("\n"); + sb.Append(" Sweet: ").Append(Sweet).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 BananaReq).AreEqual; + } + + /// + /// Returns true if BananaReq instances are equal + /// + /// Instance of BananaReq to be compared + /// Boolean + public bool Equals(BananaReq 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; + hashCode = hashCode * 59 + this.LengthCm.GetHashCode(); + hashCode = hashCode * 59 + this.Sweet.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-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/BasquePig.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/BasquePig.cs new file mode 100644 index 00000000000..1dca71f0558 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/BasquePig.cs @@ -0,0 +1,155 @@ +/* + * 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 +{ + /// + /// BasquePig + /// + [DataContract(Name = "BasquePig")] + public partial class BasquePig : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + [JsonConstructorAttribute] + protected BasquePig() + { + this.AdditionalProperties = new Dictionary(); + } + /// + /// Initializes a new instance of the class. + /// + /// className (required). + public BasquePig(string className = default(string)) + { + // to ensure "className" is required (not null) + this._ClassName = className ?? throw new ArgumentNullException("className is a required property for BasquePig and cannot be null"); + this.AdditionalProperties = new Dictionary(); + } + + /// + /// Gets or Sets ClassName + /// + [DataMember(Name = "className", IsRequired = true, EmitDefaultValue = false)] + public string ClassName + { + get{ return _ClassName;} + set + { + _ClassName = value; + _flagClassName = true; + } + } + private string _ClassName; + private bool _flagClassName; + + /// + /// Returns false as ClassName should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeClassName() + { + return _flagClassName; + } + /// + /// 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() + { + var sb = new StringBuilder(); + sb.Append("class BasquePig {\n"); + sb.Append(" ClassName: ").Append(ClassName).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 BasquePig).AreEqual; + } + + /// + /// Returns true if BasquePig instances are equal + /// + /// Instance of BasquePig to be compared + /// Boolean + public bool Equals(BasquePig 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.ClassName != null) + hashCode = hashCode * 59 + this.ClassName.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-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Capitalization.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Capitalization.cs new file mode 100644 index 00000000000..0e7d2fc0fb8 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Capitalization.cs @@ -0,0 +1,292 @@ +/* + * 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 +{ + /// + /// Capitalization + /// + [DataContract(Name = "Capitalization")] + public partial class Capitalization : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// smallCamel. + /// capitalCamel. + /// smallSnake. + /// capitalSnake. + /// sCAETHFlowPoints. + /// Name of the pet . + public Capitalization(string smallCamel = default(string), string capitalCamel = default(string), string smallSnake = default(string), string capitalSnake = default(string), string sCAETHFlowPoints = default(string), string aTTNAME = default(string)) + { + this._SmallCamel = smallCamel; + this._CapitalCamel = capitalCamel; + this._SmallSnake = smallSnake; + this._CapitalSnake = capitalSnake; + this._SCAETHFlowPoints = sCAETHFlowPoints; + this._ATT_NAME = aTTNAME; + this.AdditionalProperties = new Dictionary(); + } + + /// + /// Gets or Sets SmallCamel + /// + [DataMember(Name = "smallCamel", EmitDefaultValue = false)] + public string SmallCamel + { + get{ return _SmallCamel;} + set + { + _SmallCamel = value; + _flagSmallCamel = true; + } + } + private string _SmallCamel; + private bool _flagSmallCamel; + + /// + /// Returns false as SmallCamel should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeSmallCamel() + { + return _flagSmallCamel; + } + /// + /// Gets or Sets CapitalCamel + /// + [DataMember(Name = "CapitalCamel", EmitDefaultValue = false)] + public string CapitalCamel + { + get{ return _CapitalCamel;} + set + { + _CapitalCamel = value; + _flagCapitalCamel = true; + } + } + private string _CapitalCamel; + private bool _flagCapitalCamel; + + /// + /// Returns false as CapitalCamel should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeCapitalCamel() + { + return _flagCapitalCamel; + } + /// + /// Gets or Sets SmallSnake + /// + [DataMember(Name = "small_Snake", EmitDefaultValue = false)] + public string SmallSnake + { + get{ return _SmallSnake;} + set + { + _SmallSnake = value; + _flagSmallSnake = true; + } + } + private string _SmallSnake; + private bool _flagSmallSnake; + + /// + /// Returns false as SmallSnake should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeSmallSnake() + { + return _flagSmallSnake; + } + /// + /// Gets or Sets CapitalSnake + /// + [DataMember(Name = "Capital_Snake", EmitDefaultValue = false)] + public string CapitalSnake + { + get{ return _CapitalSnake;} + set + { + _CapitalSnake = value; + _flagCapitalSnake = true; + } + } + private string _CapitalSnake; + private bool _flagCapitalSnake; + + /// + /// Returns false as CapitalSnake should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeCapitalSnake() + { + return _flagCapitalSnake; + } + /// + /// Gets or Sets SCAETHFlowPoints + /// + [DataMember(Name = "SCA_ETH_Flow_Points", EmitDefaultValue = false)] + public string SCAETHFlowPoints + { + get{ return _SCAETHFlowPoints;} + set + { + _SCAETHFlowPoints = value; + _flagSCAETHFlowPoints = true; + } + } + private string _SCAETHFlowPoints; + private bool _flagSCAETHFlowPoints; + + /// + /// Returns false as SCAETHFlowPoints should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeSCAETHFlowPoints() + { + return _flagSCAETHFlowPoints; + } + /// + /// Name of the pet + /// + /// Name of the pet + [DataMember(Name = "ATT_NAME", EmitDefaultValue = false)] + public string ATT_NAME + { + get{ return _ATT_NAME;} + set + { + _ATT_NAME = value; + _flagATT_NAME = true; + } + } + private string _ATT_NAME; + private bool _flagATT_NAME; + + /// + /// Returns false as ATT_NAME should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeATT_NAME() + { + return _flagATT_NAME; + } + /// + /// 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() + { + var sb = new StringBuilder(); + sb.Append("class Capitalization {\n"); + sb.Append(" SmallCamel: ").Append(SmallCamel).Append("\n"); + sb.Append(" CapitalCamel: ").Append(CapitalCamel).Append("\n"); + sb.Append(" SmallSnake: ").Append(SmallSnake).Append("\n"); + sb.Append(" CapitalSnake: ").Append(CapitalSnake).Append("\n"); + sb.Append(" SCAETHFlowPoints: ").Append(SCAETHFlowPoints).Append("\n"); + sb.Append(" ATT_NAME: ").Append(ATT_NAME).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 Capitalization).AreEqual; + } + + /// + /// Returns true if Capitalization instances are equal + /// + /// Instance of Capitalization to be compared + /// Boolean + public bool Equals(Capitalization 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.SmallCamel != null) + hashCode = hashCode * 59 + this.SmallCamel.GetHashCode(); + if (this.CapitalCamel != null) + hashCode = hashCode * 59 + this.CapitalCamel.GetHashCode(); + if (this.SmallSnake != null) + hashCode = hashCode * 59 + this.SmallSnake.GetHashCode(); + if (this.CapitalSnake != null) + hashCode = hashCode * 59 + this.CapitalSnake.GetHashCode(); + if (this.SCAETHFlowPoints != null) + hashCode = hashCode * 59 + this.SCAETHFlowPoints.GetHashCode(); + if (this.ATT_NAME != null) + hashCode = hashCode * 59 + this.ATT_NAME.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-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Cat.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Cat.cs new file mode 100644 index 00000000000..b2fec9a105f --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Cat.cs @@ -0,0 +1,169 @@ +/* + * 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 JsonSubTypes; +using System.ComponentModel.DataAnnotations; +using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; +using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; + +namespace Org.OpenAPITools.Model +{ + /// + /// Cat + /// + [DataContract(Name = "Cat")] + [JsonConverter(typeof(JsonSubtypes), "ClassName")] + public partial class Cat : Animal, IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + [JsonConstructorAttribute] + protected Cat() + { + this.AdditionalProperties = new Dictionary(); + } + /// + /// Initializes a new instance of the class. + /// + /// declawed. + /// className (required) (default to "Cat"). + /// color (default to "red"). + public Cat(bool declawed = default(bool), string className = "Cat", string color = "red") : base(className, color) + { + this._Declawed = declawed; + this.AdditionalProperties = new Dictionary(); + } + + /// + /// Gets or Sets Declawed + /// + [DataMember(Name = "declawed", EmitDefaultValue = true)] + public bool Declawed + { + get{ return _Declawed;} + set + { + _Declawed = value; + _flagDeclawed = true; + } + } + private bool _Declawed; + private bool _flagDeclawed; + + /// + /// Returns false as Declawed should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeDeclawed() + { + return _flagDeclawed; + } + /// + /// 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() + { + var sb = new StringBuilder(); + sb.Append("class Cat {\n"); + sb.Append(" ").Append(base.ToString().Replace("\n", "\n ")).Append("\n"); + sb.Append(" Declawed: ").Append(Declawed).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 override 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 Cat).AreEqual; + } + + /// + /// Returns true if Cat instances are equal + /// + /// Instance of Cat to be compared + /// Boolean + public bool Equals(Cat 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 = base.GetHashCode(); + hashCode = hashCode * 59 + this.Declawed.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) + { + return this.BaseValidate(validationContext); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + protected IEnumerable BaseValidate(ValidationContext validationContext) + { + foreach(var x in BaseValidate(validationContext)) yield return x; + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/CatAllOf.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/CatAllOf.cs new file mode 100644 index 00000000000..d8032316af5 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/CatAllOf.cs @@ -0,0 +1,145 @@ +/* + * 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 +{ + /// + /// CatAllOf + /// + [DataContract(Name = "Cat_allOf")] + public partial class CatAllOf : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// declawed. + public CatAllOf(bool declawed = default(bool)) + { + this._Declawed = declawed; + this.AdditionalProperties = new Dictionary(); + } + + /// + /// Gets or Sets Declawed + /// + [DataMember(Name = "declawed", EmitDefaultValue = true)] + public bool Declawed + { + get{ return _Declawed;} + set + { + _Declawed = value; + _flagDeclawed = true; + } + } + private bool _Declawed; + private bool _flagDeclawed; + + /// + /// Returns false as Declawed should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeDeclawed() + { + return _flagDeclawed; + } + /// + /// 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() + { + var sb = new StringBuilder(); + sb.Append("class CatAllOf {\n"); + sb.Append(" Declawed: ").Append(Declawed).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 CatAllOf).AreEqual; + } + + /// + /// Returns true if CatAllOf instances are equal + /// + /// Instance of CatAllOf to be compared + /// Boolean + public bool Equals(CatAllOf 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; + hashCode = hashCode * 59 + this.Declawed.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-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Category.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Category.cs new file mode 100644 index 00000000000..a99b2e4df1f --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Category.cs @@ -0,0 +1,183 @@ +/* + * 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 +{ + /// + /// Category + /// + [DataContract(Name = "Category")] + public partial class Category : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + [JsonConstructorAttribute] + protected Category() + { + this.AdditionalProperties = new Dictionary(); + } + /// + /// Initializes a new instance of the class. + /// + /// id. + /// name (required) (default to "default-name"). + public Category(long id = default(long), string name = "default-name") + { + // to ensure "name" is required (not null) + this._Name = name ?? throw new ArgumentNullException("name is a required property for Category and cannot be null"); + this._Id = id; + this.AdditionalProperties = new Dictionary(); + } + + /// + /// Gets or Sets Id + /// + [DataMember(Name = "id", EmitDefaultValue = false)] + public long Id + { + get{ return _Id;} + set + { + _Id = value; + _flagId = true; + } + } + private long _Id; + private bool _flagId; + + /// + /// Returns false as Id should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeId() + { + return _flagId; + } + /// + /// Gets or Sets Name + /// + [DataMember(Name = "name", IsRequired = true, EmitDefaultValue = false)] + public string Name + { + get{ return _Name;} + set + { + _Name = value; + _flagName = true; + } + } + private string _Name; + private bool _flagName; + + /// + /// Returns false as Name should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeName() + { + return _flagName; + } + /// + /// 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() + { + var sb = new StringBuilder(); + sb.Append("class Category {\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" Name: ").Append(Name).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 Category).AreEqual; + } + + /// + /// Returns true if Category instances are equal + /// + /// Instance of Category to be compared + /// Boolean + public bool Equals(Category 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; + hashCode = hashCode * 59 + this.Id.GetHashCode(); + if (this.Name != null) + hashCode = hashCode * 59 + this.Name.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-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/ChildCat.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/ChildCat.cs new file mode 100644 index 00000000000..e07206d390c --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/ChildCat.cs @@ -0,0 +1,212 @@ +/* + * 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 JsonSubTypes; +using System.ComponentModel.DataAnnotations; +using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; +using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; + +namespace Org.OpenAPITools.Model +{ + /// + /// ChildCat + /// + [DataContract(Name = "ChildCat")] + [JsonConverter(typeof(JsonSubtypes), "PetType")] + public partial class ChildCat : ParentPet, IEquatable, IValidatableObject + { + /// + /// Defines PetType + /// + [JsonConverter(typeof(StringEnumConverter))] + public enum PetTypeEnum + { + /// + /// Enum ChildCat for value: ChildCat + /// + [EnumMember(Value = "ChildCat")] + ChildCat = 1 + + } + + + /// + /// Gets or Sets PetType + /// + + [DataMember(Name = "pet_type", IsRequired = true, EmitDefaultValue = false)] + public PetTypeEnum PetType + { + get{ return _PetType;} + set + { + _PetType = value; + _flagPetType = true; + } + } + private PetTypeEnum _PetType; + private bool _flagPetType; + + /// + /// Returns false as PetType should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializePetType() + { + return _flagPetType; + } + /// + /// Initializes a new instance of the class. + /// + [JsonConstructorAttribute] + protected ChildCat() + { + this.AdditionalProperties = new Dictionary(); + } + /// + /// Initializes a new instance of the class. + /// + /// name. + /// petType (required) (default to PetTypeEnum.ChildCat). + public ChildCat(string name = default(string), PetTypeEnum petType = PetTypeEnum.ChildCat) : base() + { + this._PetType = petType; + this._Name = name; + this.AdditionalProperties = new Dictionary(); + } + + /// + /// Gets or Sets Name + /// + [DataMember(Name = "name", EmitDefaultValue = false)] + public string Name + { + get{ return _Name;} + set + { + _Name = value; + _flagName = true; + } + } + private string _Name; + private bool _flagName; + + /// + /// Returns false as Name should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeName() + { + return _flagName; + } + /// + /// 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() + { + var sb = new StringBuilder(); + sb.Append("class ChildCat {\n"); + sb.Append(" ").Append(base.ToString().Replace("\n", "\n ")).Append("\n"); + sb.Append(" Name: ").Append(Name).Append("\n"); + sb.Append(" PetType: ").Append(PetType).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 override 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 ChildCat).AreEqual; + } + + /// + /// Returns true if ChildCat instances are equal + /// + /// Instance of ChildCat to be compared + /// Boolean + public bool Equals(ChildCat 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 = base.GetHashCode(); + if (this.Name != null) + hashCode = hashCode * 59 + this.Name.GetHashCode(); + hashCode = hashCode * 59 + this.PetType.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) + { + return this.BaseValidate(validationContext); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + protected IEnumerable BaseValidate(ValidationContext validationContext) + { + foreach(var x in BaseValidate(validationContext)) yield return x; + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/ChildCatAllOf.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/ChildCatAllOf.cs new file mode 100644 index 00000000000..d3f5e7519b3 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/ChildCatAllOf.cs @@ -0,0 +1,190 @@ +/* + * 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 +{ + /// + /// ChildCatAllOf + /// + [DataContract(Name = "ChildCat_allOf")] + public partial class ChildCatAllOf : IEquatable, IValidatableObject + { + /// + /// Defines PetType + /// + [JsonConverter(typeof(StringEnumConverter))] + public enum PetTypeEnum + { + /// + /// Enum ChildCat for value: ChildCat + /// + [EnumMember(Value = "ChildCat")] + ChildCat = 1 + + } + + + /// + /// Gets or Sets PetType + /// + + [DataMember(Name = "pet_type", EmitDefaultValue = false)] + public PetTypeEnum? PetType + { + get{ return _PetType;} + set + { + _PetType = value; + _flagPetType = true; + } + } + private PetTypeEnum? _PetType; + private bool _flagPetType; + + /// + /// Returns false as PetType should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializePetType() + { + return _flagPetType; + } + /// + /// Initializes a new instance of the class. + /// + /// name. + /// petType (default to PetTypeEnum.ChildCat). + public ChildCatAllOf(string name = default(string), PetTypeEnum? petType = PetTypeEnum.ChildCat) + { + this._Name = name; + this.PetType = petType; + this.AdditionalProperties = new Dictionary(); + } + + /// + /// Gets or Sets Name + /// + [DataMember(Name = "name", EmitDefaultValue = false)] + public string Name + { + get{ return _Name;} + set + { + _Name = value; + _flagName = true; + } + } + private string _Name; + private bool _flagName; + + /// + /// Returns false as Name should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeName() + { + return _flagName; + } + /// + /// 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() + { + var sb = new StringBuilder(); + sb.Append("class ChildCatAllOf {\n"); + sb.Append(" Name: ").Append(Name).Append("\n"); + sb.Append(" PetType: ").Append(PetType).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 ChildCatAllOf).AreEqual; + } + + /// + /// Returns true if ChildCatAllOf instances are equal + /// + /// Instance of ChildCatAllOf to be compared + /// Boolean + public bool Equals(ChildCatAllOf 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.Name != null) + hashCode = hashCode * 59 + this.Name.GetHashCode(); + hashCode = hashCode * 59 + this.PetType.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-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/ClassModel.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/ClassModel.cs new file mode 100644 index 00000000000..398ba005da8 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/ClassModel.cs @@ -0,0 +1,146 @@ +/* + * 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 +{ + /// + /// Model for testing model with \"_class\" property + /// + [DataContract(Name = "ClassModel")] + public partial class ClassModel : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// _class. + public ClassModel(string _class = default(string)) + { + this._Class = _class; + this.AdditionalProperties = new Dictionary(); + } + + /// + /// Gets or Sets Class + /// + [DataMember(Name = "_class", EmitDefaultValue = false)] + public string Class + { + get{ return _Class;} + set + { + _Class = value; + _flagClass = true; + } + } + private string _Class; + private bool _flagClass; + + /// + /// Returns false as Class should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeClass() + { + return _flagClass; + } + /// + /// 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() + { + var sb = new StringBuilder(); + sb.Append("class ClassModel {\n"); + sb.Append(" Class: ").Append(Class).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 ClassModel).AreEqual; + } + + /// + /// Returns true if ClassModel instances are equal + /// + /// Instance of ClassModel to be compared + /// Boolean + public bool Equals(ClassModel 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.Class != null) + hashCode = hashCode * 59 + this.Class.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-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/ComplexQuadrilateral.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/ComplexQuadrilateral.cs new file mode 100644 index 00000000000..50a0471ba56 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/ComplexQuadrilateral.cs @@ -0,0 +1,185 @@ +/* + * 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 +{ + /// + /// ComplexQuadrilateral + /// + [DataContract(Name = "ComplexQuadrilateral")] + public partial class ComplexQuadrilateral : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + [JsonConstructorAttribute] + protected ComplexQuadrilateral() + { + this.AdditionalProperties = new Dictionary(); + } + /// + /// Initializes a new instance of the class. + /// + /// shapeType (required). + /// quadrilateralType (required). + public ComplexQuadrilateral(string shapeType = default(string), string quadrilateralType = default(string)) + { + // to ensure "shapeType" is required (not null) + this._ShapeType = shapeType ?? throw new ArgumentNullException("shapeType is a required property for ComplexQuadrilateral and cannot be null"); + // to ensure "quadrilateralType" is required (not null) + this._QuadrilateralType = quadrilateralType ?? throw new ArgumentNullException("quadrilateralType is a required property for ComplexQuadrilateral and cannot be null"); + this.AdditionalProperties = new Dictionary(); + } + + /// + /// Gets or Sets ShapeType + /// + [DataMember(Name = "shapeType", IsRequired = true, EmitDefaultValue = false)] + public string ShapeType + { + get{ return _ShapeType;} + set + { + _ShapeType = value; + _flagShapeType = true; + } + } + private string _ShapeType; + private bool _flagShapeType; + + /// + /// Returns false as ShapeType should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeShapeType() + { + return _flagShapeType; + } + /// + /// Gets or Sets QuadrilateralType + /// + [DataMember(Name = "quadrilateralType", IsRequired = true, EmitDefaultValue = false)] + public string QuadrilateralType + { + get{ return _QuadrilateralType;} + set + { + _QuadrilateralType = value; + _flagQuadrilateralType = true; + } + } + private string _QuadrilateralType; + private bool _flagQuadrilateralType; + + /// + /// Returns false as QuadrilateralType should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeQuadrilateralType() + { + return _flagQuadrilateralType; + } + /// + /// 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() + { + var sb = new StringBuilder(); + sb.Append("class ComplexQuadrilateral {\n"); + sb.Append(" ShapeType: ").Append(ShapeType).Append("\n"); + sb.Append(" QuadrilateralType: ").Append(QuadrilateralType).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 ComplexQuadrilateral).AreEqual; + } + + /// + /// Returns true if ComplexQuadrilateral instances are equal + /// + /// Instance of ComplexQuadrilateral to be compared + /// Boolean + public bool Equals(ComplexQuadrilateral 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.ShapeType != null) + hashCode = hashCode * 59 + this.ShapeType.GetHashCode(); + if (this.QuadrilateralType != null) + hashCode = hashCode * 59 + this.QuadrilateralType.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-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/DanishPig.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/DanishPig.cs new file mode 100644 index 00000000000..9e783bb28d0 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/DanishPig.cs @@ -0,0 +1,155 @@ +/* + * 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 +{ + /// + /// DanishPig + /// + [DataContract(Name = "DanishPig")] + public partial class DanishPig : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + [JsonConstructorAttribute] + protected DanishPig() + { + this.AdditionalProperties = new Dictionary(); + } + /// + /// Initializes a new instance of the class. + /// + /// className (required). + public DanishPig(string className = default(string)) + { + // to ensure "className" is required (not null) + this._ClassName = className ?? throw new ArgumentNullException("className is a required property for DanishPig and cannot be null"); + this.AdditionalProperties = new Dictionary(); + } + + /// + /// Gets or Sets ClassName + /// + [DataMember(Name = "className", IsRequired = true, EmitDefaultValue = false)] + public string ClassName + { + get{ return _ClassName;} + set + { + _ClassName = value; + _flagClassName = true; + } + } + private string _ClassName; + private bool _flagClassName; + + /// + /// Returns false as ClassName should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeClassName() + { + return _flagClassName; + } + /// + /// 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() + { + var sb = new StringBuilder(); + sb.Append("class DanishPig {\n"); + sb.Append(" ClassName: ").Append(ClassName).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 DanishPig).AreEqual; + } + + /// + /// Returns true if DanishPig instances are equal + /// + /// Instance of DanishPig to be compared + /// Boolean + public bool Equals(DanishPig 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.ClassName != null) + hashCode = hashCode * 59 + this.ClassName.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-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Dog.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Dog.cs new file mode 100644 index 00000000000..713e93b0b13 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Dog.cs @@ -0,0 +1,170 @@ +/* + * 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 JsonSubTypes; +using System.ComponentModel.DataAnnotations; +using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; +using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; + +namespace Org.OpenAPITools.Model +{ + /// + /// Dog + /// + [DataContract(Name = "Dog")] + [JsonConverter(typeof(JsonSubtypes), "ClassName")] + public partial class Dog : Animal, IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + [JsonConstructorAttribute] + protected Dog() + { + this.AdditionalProperties = new Dictionary(); + } + /// + /// Initializes a new instance of the class. + /// + /// breed. + /// className (required) (default to "Dog"). + /// color (default to "red"). + public Dog(string breed = default(string), string className = "Dog", string color = "red") : base(className, color) + { + this._Breed = breed; + this.AdditionalProperties = new Dictionary(); + } + + /// + /// Gets or Sets Breed + /// + [DataMember(Name = "breed", EmitDefaultValue = false)] + public string Breed + { + get{ return _Breed;} + set + { + _Breed = value; + _flagBreed = true; + } + } + private string _Breed; + private bool _flagBreed; + + /// + /// Returns false as Breed should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeBreed() + { + return _flagBreed; + } + /// + /// 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() + { + var sb = new StringBuilder(); + sb.Append("class Dog {\n"); + sb.Append(" ").Append(base.ToString().Replace("\n", "\n ")).Append("\n"); + sb.Append(" Breed: ").Append(Breed).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 override 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 Dog).AreEqual; + } + + /// + /// Returns true if Dog instances are equal + /// + /// Instance of Dog to be compared + /// Boolean + public bool Equals(Dog 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 = base.GetHashCode(); + if (this.Breed != null) + hashCode = hashCode * 59 + this.Breed.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) + { + return this.BaseValidate(validationContext); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + protected IEnumerable BaseValidate(ValidationContext validationContext) + { + foreach(var x in BaseValidate(validationContext)) yield return x; + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/DogAllOf.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/DogAllOf.cs new file mode 100644 index 00000000000..d82ab386dc2 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/DogAllOf.cs @@ -0,0 +1,146 @@ +/* + * 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 +{ + /// + /// DogAllOf + /// + [DataContract(Name = "Dog_allOf")] + public partial class DogAllOf : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// breed. + public DogAllOf(string breed = default(string)) + { + this._Breed = breed; + this.AdditionalProperties = new Dictionary(); + } + + /// + /// Gets or Sets Breed + /// + [DataMember(Name = "breed", EmitDefaultValue = false)] + public string Breed + { + get{ return _Breed;} + set + { + _Breed = value; + _flagBreed = true; + } + } + private string _Breed; + private bool _flagBreed; + + /// + /// Returns false as Breed should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeBreed() + { + return _flagBreed; + } + /// + /// 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() + { + var sb = new StringBuilder(); + sb.Append("class DogAllOf {\n"); + sb.Append(" Breed: ").Append(Breed).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 DogAllOf).AreEqual; + } + + /// + /// Returns true if DogAllOf instances are equal + /// + /// Instance of DogAllOf to be compared + /// Boolean + public bool Equals(DogAllOf 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.Breed != null) + hashCode = hashCode * 59 + this.Breed.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-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Drawing.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Drawing.cs new file mode 100644 index 00000000000..2dd0540c37d --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Drawing.cs @@ -0,0 +1,224 @@ +/* + * 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 +{ + /// + /// Drawing + /// + [DataContract(Name = "Drawing")] + public partial class Drawing : Dictionary, IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// mainShape. + /// shapeOrNull. + /// nullableShape. + /// shapes. + public Drawing(Shape mainShape = default(Shape), ShapeOrNull shapeOrNull = default(ShapeOrNull), NullableShape nullableShape = default(NullableShape), List shapes = default(List)) : base() + { + this._MainShape = mainShape; + this._ShapeOrNull = shapeOrNull; + this._NullableShape = nullableShape; + this._Shapes = shapes; + } + + /// + /// Gets or Sets MainShape + /// + [DataMember(Name = "mainShape", EmitDefaultValue = false)] + public Shape MainShape + { + get{ return _MainShape;} + set + { + _MainShape = value; + _flagMainShape = true; + } + } + private Shape _MainShape; + private bool _flagMainShape; + + /// + /// Returns false as MainShape should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeMainShape() + { + return _flagMainShape; + } + /// + /// Gets or Sets ShapeOrNull + /// + [DataMember(Name = "shapeOrNull", EmitDefaultValue = false)] + public ShapeOrNull ShapeOrNull + { + get{ return _ShapeOrNull;} + set + { + _ShapeOrNull = value; + _flagShapeOrNull = true; + } + } + private ShapeOrNull _ShapeOrNull; + private bool _flagShapeOrNull; + + /// + /// Returns false as ShapeOrNull should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeShapeOrNull() + { + return _flagShapeOrNull; + } + /// + /// Gets or Sets NullableShape + /// + [DataMember(Name = "nullableShape", EmitDefaultValue = true)] + public NullableShape NullableShape + { + get{ return _NullableShape;} + set + { + _NullableShape = value; + _flagNullableShape = true; + } + } + private NullableShape _NullableShape; + private bool _flagNullableShape; + + /// + /// Returns false as NullableShape should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeNullableShape() + { + return _flagNullableShape; + } + /// + /// Gets or Sets Shapes + /// + [DataMember(Name = "shapes", EmitDefaultValue = false)] + public List Shapes + { + get{ return _Shapes;} + set + { + _Shapes = value; + _flagShapes = true; + } + } + private List _Shapes; + private bool _flagShapes; + + /// + /// Returns false as Shapes should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeShapes() + { + return _flagShapes; + } + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + var 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"); + sb.Append(" Shapes: ").Append(Shapes).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public 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 Drawing).AreEqual; + } + + /// + /// Returns true if Drawing instances are equal + /// + /// Instance of Drawing to be compared + /// Boolean + public bool Equals(Drawing 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 = base.GetHashCode(); + if (this.MainShape != null) + hashCode = hashCode * 59 + this.MainShape.GetHashCode(); + if (this.ShapeOrNull != null) + hashCode = hashCode * 59 + this.ShapeOrNull.GetHashCode(); + if (this.NullableShape != null) + hashCode = hashCode * 59 + this.NullableShape.GetHashCode(); + if (this.Shapes != null) + hashCode = hashCode * 59 + this.Shapes.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-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/EnumArrays.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/EnumArrays.cs new file mode 100644 index 00000000000..6d745892008 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/EnumArrays.cs @@ -0,0 +1,218 @@ +/* + * 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 +{ + /// + /// EnumArrays + /// + [DataContract(Name = "EnumArrays")] + public partial class EnumArrays : IEquatable, IValidatableObject + { + /// + /// Defines JustSymbol + /// + [JsonConverter(typeof(StringEnumConverter))] + public enum JustSymbolEnum + { + /// + /// Enum GreaterThanOrEqualTo for value: >= + /// + [EnumMember(Value = ">=")] + GreaterThanOrEqualTo = 1, + + /// + /// Enum Dollar for value: $ + /// + [EnumMember(Value = "$")] + Dollar = 2 + + } + + + /// + /// Gets or Sets JustSymbol + /// + + [DataMember(Name = "just_symbol", EmitDefaultValue = false)] + public JustSymbolEnum? JustSymbol + { + get{ return _JustSymbol;} + set + { + _JustSymbol = value; + _flagJustSymbol = true; + } + } + private JustSymbolEnum? _JustSymbol; + private bool _flagJustSymbol; + + /// + /// Returns false as JustSymbol should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeJustSymbol() + { + return _flagJustSymbol; + } + /// + /// Defines ArrayEnum + /// + [JsonConverter(typeof(StringEnumConverter))] + public enum ArrayEnumEnum + { + /// + /// Enum Fish for value: fish + /// + [EnumMember(Value = "fish")] + Fish = 1, + + /// + /// Enum Crab for value: crab + /// + [EnumMember(Value = "crab")] + Crab = 2 + + } + + + + /// + /// Gets or Sets ArrayEnum + /// + + [DataMember(Name = "array_enum", EmitDefaultValue = false)] + public List ArrayEnum + { + get{ return _ArrayEnum;} + set + { + _ArrayEnum = value; + _flagArrayEnum = true; + } + } + private List _ArrayEnum; + private bool _flagArrayEnum; + + /// + /// Returns false as ArrayEnum should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeArrayEnum() + { + return _flagArrayEnum; + } + /// + /// Initializes a new instance of the class. + /// + /// justSymbol. + /// arrayEnum. + public EnumArrays(JustSymbolEnum? justSymbol = default(JustSymbolEnum?), List arrayEnum = default(List)) + { + this._JustSymbol = justSymbol; + this._ArrayEnum = arrayEnum; + this.AdditionalProperties = new Dictionary(); + } + + /// + /// 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() + { + var sb = new StringBuilder(); + sb.Append("class EnumArrays {\n"); + sb.Append(" JustSymbol: ").Append(JustSymbol).Append("\n"); + sb.Append(" ArrayEnum: ").Append(ArrayEnum).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 EnumArrays).AreEqual; + } + + /// + /// Returns true if EnumArrays instances are equal + /// + /// Instance of EnumArrays to be compared + /// Boolean + public bool Equals(EnumArrays 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; + hashCode = hashCode * 59 + this.JustSymbol.GetHashCode(); + hashCode = hashCode * 59 + this.ArrayEnum.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-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/EnumClass.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/EnumClass.cs new file mode 100644 index 00000000000..48b3d7d0e7e --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/EnumClass.cs @@ -0,0 +1,55 @@ +/* + * 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 +{ + /// + /// Defines EnumClass + /// + [JsonConverter(typeof(StringEnumConverter))] + public enum EnumClass + { + /// + /// Enum Abc for value: _abc + /// + [EnumMember(Value = "_abc")] + Abc = 1, + + /// + /// Enum Efg for value: -efg + /// + [EnumMember(Value = "-efg")] + Efg = 2, + + /// + /// Enum Xyz for value: (xyz) + /// + [EnumMember(Value = "(xyz)")] + Xyz = 3 + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/EnumTest.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/EnumTest.cs new file mode 100644 index 00000000000..a00c9816092 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/EnumTest.cs @@ -0,0 +1,501 @@ +/* + * 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 +{ + /// + /// EnumTest + /// + [DataContract(Name = "Enum_Test")] + public partial class EnumTest : IEquatable, IValidatableObject + { + /// + /// Defines EnumString + /// + [JsonConverter(typeof(StringEnumConverter))] + public enum EnumStringEnum + { + /// + /// 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 + + } + + + /// + /// Gets or Sets EnumString + /// + + [DataMember(Name = "enum_string", EmitDefaultValue = false)] + public EnumStringEnum? EnumString + { + get{ return _EnumString;} + set + { + _EnumString = value; + _flagEnumString = true; + } + } + private EnumStringEnum? _EnumString; + private bool _flagEnumString; + + /// + /// Returns false as EnumString should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeEnumString() + { + return _flagEnumString; + } + /// + /// Defines EnumStringRequired + /// + [JsonConverter(typeof(StringEnumConverter))] + public enum EnumStringRequiredEnum + { + /// + /// 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 + + } + + + /// + /// Gets or Sets EnumStringRequired + /// + + [DataMember(Name = "enum_string_required", IsRequired = true, EmitDefaultValue = false)] + public EnumStringRequiredEnum EnumStringRequired + { + get{ return _EnumStringRequired;} + set + { + _EnumStringRequired = value; + _flagEnumStringRequired = true; + } + } + private EnumStringRequiredEnum _EnumStringRequired; + private bool _flagEnumStringRequired; + + /// + /// Returns false as EnumStringRequired should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeEnumStringRequired() + { + return _flagEnumStringRequired; + } + /// + /// Defines EnumInteger + /// + public enum EnumIntegerEnum + { + /// + /// Enum NUMBER_1 for value: 1 + /// + NUMBER_1 = 1, + + /// + /// Enum NUMBER_MINUS_1 for value: -1 + /// + NUMBER_MINUS_1 = -1 + + } + + + /// + /// Gets or Sets EnumInteger + /// + + [DataMember(Name = "enum_integer", EmitDefaultValue = false)] + public EnumIntegerEnum? EnumInteger + { + get{ return _EnumInteger;} + set + { + _EnumInteger = value; + _flagEnumInteger = true; + } + } + private EnumIntegerEnum? _EnumInteger; + private bool _flagEnumInteger; + + /// + /// Returns false as EnumInteger should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeEnumInteger() + { + return _flagEnumInteger; + } + /// + /// Defines EnumIntegerOnly + /// + public enum EnumIntegerOnlyEnum + { + /// + /// Enum NUMBER_2 for value: 2 + /// + NUMBER_2 = 2, + + /// + /// Enum NUMBER_MINUS_2 for value: -2 + /// + NUMBER_MINUS_2 = -2 + + } + + + /// + /// Gets or Sets EnumIntegerOnly + /// + + [DataMember(Name = "enum_integer_only", EmitDefaultValue = false)] + public EnumIntegerOnlyEnum? EnumIntegerOnly + { + get{ return _EnumIntegerOnly;} + set + { + _EnumIntegerOnly = value; + _flagEnumIntegerOnly = true; + } + } + private EnumIntegerOnlyEnum? _EnumIntegerOnly; + private bool _flagEnumIntegerOnly; + + /// + /// Returns false as EnumIntegerOnly should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeEnumIntegerOnly() + { + return _flagEnumIntegerOnly; + } + /// + /// Defines EnumNumber + /// + [JsonConverter(typeof(StringEnumConverter))] + public enum EnumNumberEnum + { + /// + /// Enum NUMBER_1_DOT_1 for value: 1.1 + /// + [EnumMember(Value = "1.1")] + NUMBER_1_DOT_1 = 1, + + /// + /// Enum NUMBER_MINUS_1_DOT_2 for value: -1.2 + /// + [EnumMember(Value = "-1.2")] + NUMBER_MINUS_1_DOT_2 = 2 + + } + + + /// + /// Gets or Sets EnumNumber + /// + + [DataMember(Name = "enum_number", EmitDefaultValue = false)] + public EnumNumberEnum? EnumNumber + { + get{ return _EnumNumber;} + set + { + _EnumNumber = value; + _flagEnumNumber = true; + } + } + private EnumNumberEnum? _EnumNumber; + private bool _flagEnumNumber; + + /// + /// Returns false as EnumNumber should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeEnumNumber() + { + return _flagEnumNumber; + } + + /// + /// Gets or Sets OuterEnum + /// + + [DataMember(Name = "outerEnum", EmitDefaultValue = true)] + public OuterEnum? OuterEnum + { + get{ return _OuterEnum;} + set + { + _OuterEnum = value; + _flagOuterEnum = true; + } + } + private OuterEnum? _OuterEnum; + private bool _flagOuterEnum; + + /// + /// Returns false as OuterEnum should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeOuterEnum() + { + return _flagOuterEnum; + } + + /// + /// Gets or Sets OuterEnumInteger + /// + + [DataMember(Name = "outerEnumInteger", EmitDefaultValue = false)] + public OuterEnumInteger? OuterEnumInteger + { + get{ return _OuterEnumInteger;} + set + { + _OuterEnumInteger = value; + _flagOuterEnumInteger = true; + } + } + private OuterEnumInteger? _OuterEnumInteger; + private bool _flagOuterEnumInteger; + + /// + /// Returns false as OuterEnumInteger should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeOuterEnumInteger() + { + return _flagOuterEnumInteger; + } + + /// + /// Gets or Sets OuterEnumDefaultValue + /// + + [DataMember(Name = "outerEnumDefaultValue", EmitDefaultValue = false)] + public OuterEnumDefaultValue? OuterEnumDefaultValue + { + get{ return _OuterEnumDefaultValue;} + set + { + _OuterEnumDefaultValue = value; + _flagOuterEnumDefaultValue = true; + } + } + private OuterEnumDefaultValue? _OuterEnumDefaultValue; + private bool _flagOuterEnumDefaultValue; + + /// + /// Returns false as OuterEnumDefaultValue should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeOuterEnumDefaultValue() + { + return _flagOuterEnumDefaultValue; + } + + /// + /// Gets or Sets OuterEnumIntegerDefaultValue + /// + + [DataMember(Name = "outerEnumIntegerDefaultValue", EmitDefaultValue = false)] + public OuterEnumIntegerDefaultValue? OuterEnumIntegerDefaultValue + { + get{ return _OuterEnumIntegerDefaultValue;} + set + { + _OuterEnumIntegerDefaultValue = value; + _flagOuterEnumIntegerDefaultValue = true; + } + } + private OuterEnumIntegerDefaultValue? _OuterEnumIntegerDefaultValue; + private bool _flagOuterEnumIntegerDefaultValue; + + /// + /// Returns false as OuterEnumIntegerDefaultValue should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeOuterEnumIntegerDefaultValue() + { + return _flagOuterEnumIntegerDefaultValue; + } + /// + /// Initializes a new instance of the class. + /// + [JsonConstructorAttribute] + protected EnumTest() + { + this.AdditionalProperties = new Dictionary(); + } + /// + /// Initializes a new instance of the class. + /// + /// enumString. + /// enumStringRequired (required). + /// enumInteger. + /// enumIntegerOnly. + /// enumNumber. + /// outerEnum. + /// outerEnumInteger. + /// outerEnumDefaultValue. + /// outerEnumIntegerDefaultValue. + public EnumTest(EnumStringEnum? enumString = default(EnumStringEnum?), EnumStringRequiredEnum enumStringRequired = default(EnumStringRequiredEnum), EnumIntegerEnum? enumInteger = default(EnumIntegerEnum?), EnumIntegerOnlyEnum? enumIntegerOnly = default(EnumIntegerOnlyEnum?), EnumNumberEnum? enumNumber = default(EnumNumberEnum?), OuterEnum? outerEnum = default(OuterEnum?), OuterEnumInteger? outerEnumInteger = default(OuterEnumInteger?), OuterEnumDefaultValue? outerEnumDefaultValue = default(OuterEnumDefaultValue?), OuterEnumIntegerDefaultValue? outerEnumIntegerDefaultValue = default(OuterEnumIntegerDefaultValue?)) + { + this._EnumStringRequired = enumStringRequired; + this._EnumString = enumString; + this._EnumInteger = enumInteger; + this._EnumIntegerOnly = enumIntegerOnly; + this._EnumNumber = enumNumber; + this._OuterEnum = outerEnum; + this._OuterEnumInteger = outerEnumInteger; + this._OuterEnumDefaultValue = outerEnumDefaultValue; + this._OuterEnumIntegerDefaultValue = outerEnumIntegerDefaultValue; + this.AdditionalProperties = new Dictionary(); + } + + /// + /// 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() + { + var sb = new StringBuilder(); + sb.Append("class EnumTest {\n"); + sb.Append(" EnumString: ").Append(EnumString).Append("\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(" OuterEnum: ").Append(OuterEnum).Append("\n"); + sb.Append(" OuterEnumInteger: ").Append(OuterEnumInteger).Append("\n"); + sb.Append(" OuterEnumDefaultValue: ").Append(OuterEnumDefaultValue).Append("\n"); + sb.Append(" OuterEnumIntegerDefaultValue: ").Append(OuterEnumIntegerDefaultValue).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 EnumTest).AreEqual; + } + + /// + /// Returns true if EnumTest instances are equal + /// + /// Instance of EnumTest to be compared + /// Boolean + public bool Equals(EnumTest 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; + hashCode = hashCode * 59 + this.EnumString.GetHashCode(); + hashCode = hashCode * 59 + this.EnumStringRequired.GetHashCode(); + hashCode = hashCode * 59 + this.EnumInteger.GetHashCode(); + hashCode = hashCode * 59 + this.EnumIntegerOnly.GetHashCode(); + hashCode = hashCode * 59 + this.EnumNumber.GetHashCode(); + hashCode = hashCode * 59 + this.OuterEnum.GetHashCode(); + hashCode = hashCode * 59 + this.OuterEnumInteger.GetHashCode(); + hashCode = hashCode * 59 + this.OuterEnumDefaultValue.GetHashCode(); + hashCode = hashCode * 59 + this.OuterEnumIntegerDefaultValue.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-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/EquilateralTriangle.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/EquilateralTriangle.cs new file mode 100644 index 00000000000..cab8c52b583 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/EquilateralTriangle.cs @@ -0,0 +1,185 @@ +/* + * 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 +{ + /// + /// EquilateralTriangle + /// + [DataContract(Name = "EquilateralTriangle")] + public partial class EquilateralTriangle : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + [JsonConstructorAttribute] + protected EquilateralTriangle() + { + this.AdditionalProperties = new Dictionary(); + } + /// + /// Initializes a new instance of the class. + /// + /// shapeType (required). + /// triangleType (required). + public EquilateralTriangle(string shapeType = default(string), string triangleType = default(string)) + { + // to ensure "shapeType" is required (not null) + this._ShapeType = shapeType ?? throw new ArgumentNullException("shapeType is a required property for EquilateralTriangle and cannot be null"); + // to ensure "triangleType" is required (not null) + this._TriangleType = triangleType ?? throw new ArgumentNullException("triangleType is a required property for EquilateralTriangle and cannot be null"); + this.AdditionalProperties = new Dictionary(); + } + + /// + /// Gets or Sets ShapeType + /// + [DataMember(Name = "shapeType", IsRequired = true, EmitDefaultValue = false)] + public string ShapeType + { + get{ return _ShapeType;} + set + { + _ShapeType = value; + _flagShapeType = true; + } + } + private string _ShapeType; + private bool _flagShapeType; + + /// + /// Returns false as ShapeType should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeShapeType() + { + return _flagShapeType; + } + /// + /// Gets or Sets TriangleType + /// + [DataMember(Name = "triangleType", IsRequired = true, EmitDefaultValue = false)] + public string TriangleType + { + get{ return _TriangleType;} + set + { + _TriangleType = value; + _flagTriangleType = true; + } + } + private string _TriangleType; + private bool _flagTriangleType; + + /// + /// Returns false as TriangleType should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeTriangleType() + { + return _flagTriangleType; + } + /// + /// 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() + { + var sb = new StringBuilder(); + sb.Append("class EquilateralTriangle {\n"); + sb.Append(" ShapeType: ").Append(ShapeType).Append("\n"); + sb.Append(" TriangleType: ").Append(TriangleType).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 EquilateralTriangle).AreEqual; + } + + /// + /// Returns true if EquilateralTriangle instances are equal + /// + /// Instance of EquilateralTriangle to be compared + /// Boolean + public bool Equals(EquilateralTriangle 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.ShapeType != null) + hashCode = hashCode * 59 + this.ShapeType.GetHashCode(); + if (this.TriangleType != null) + hashCode = hashCode * 59 + this.TriangleType.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-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/File.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/File.cs new file mode 100644 index 00000000000..9e67adfbae2 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/File.cs @@ -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 + * 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 +{ + /// + /// Must be named `File` for test. + /// + [DataContract(Name = "File")] + public partial class File : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// Test capitalization. + public File(string sourceURI = default(string)) + { + this._SourceURI = sourceURI; + this.AdditionalProperties = new Dictionary(); + } + + /// + /// Test capitalization + /// + /// Test capitalization + [DataMember(Name = "sourceURI", EmitDefaultValue = false)] + public string SourceURI + { + get{ return _SourceURI;} + set + { + _SourceURI = value; + _flagSourceURI = true; + } + } + private string _SourceURI; + private bool _flagSourceURI; + + /// + /// Returns false as SourceURI should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeSourceURI() + { + return _flagSourceURI; + } + /// + /// 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() + { + var sb = new StringBuilder(); + sb.Append("class File {\n"); + sb.Append(" SourceURI: ").Append(SourceURI).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 File).AreEqual; + } + + /// + /// Returns true if File instances are equal + /// + /// Instance of File to be compared + /// Boolean + public bool Equals(File 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.SourceURI != null) + hashCode = hashCode * 59 + this.SourceURI.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-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/FileSchemaTestClass.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/FileSchemaTestClass.cs new file mode 100644 index 00000000000..9b51606f001 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/FileSchemaTestClass.cs @@ -0,0 +1,175 @@ +/* + * 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 +{ + /// + /// FileSchemaTestClass + /// + [DataContract(Name = "FileSchemaTestClass")] + public partial class FileSchemaTestClass : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// file. + /// files. + public FileSchemaTestClass(File file = default(File), List files = default(List)) + { + this._File = file; + this._Files = files; + this.AdditionalProperties = new Dictionary(); + } + + /// + /// Gets or Sets File + /// + [DataMember(Name = "file", EmitDefaultValue = false)] + public File File + { + get{ return _File;} + set + { + _File = value; + _flagFile = true; + } + } + private File _File; + private bool _flagFile; + + /// + /// Returns false as File should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeFile() + { + return _flagFile; + } + /// + /// Gets or Sets Files + /// + [DataMember(Name = "files", EmitDefaultValue = false)] + public List Files + { + get{ return _Files;} + set + { + _Files = value; + _flagFiles = true; + } + } + private List _Files; + private bool _flagFiles; + + /// + /// Returns false as Files should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeFiles() + { + return _flagFiles; + } + /// + /// 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() + { + var sb = new StringBuilder(); + sb.Append("class FileSchemaTestClass {\n"); + sb.Append(" File: ").Append(File).Append("\n"); + sb.Append(" Files: ").Append(Files).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 FileSchemaTestClass).AreEqual; + } + + /// + /// Returns true if FileSchemaTestClass instances are equal + /// + /// Instance of FileSchemaTestClass to be compared + /// Boolean + public bool Equals(FileSchemaTestClass 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.File != null) + hashCode = hashCode * 59 + this.File.GetHashCode(); + if (this.Files != null) + hashCode = hashCode * 59 + this.Files.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-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Foo.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Foo.cs new file mode 100644 index 00000000000..cf002ab2981 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Foo.cs @@ -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 + * 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 +{ + /// + /// Foo + /// + [DataContract(Name = "Foo")] + public partial class Foo : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// bar (default to "bar"). + public Foo(string bar = "bar") + { + // use default value if no "bar" provided + this.Bar = bar ?? "bar"; + this.AdditionalProperties = new Dictionary(); + } + + /// + /// Gets or Sets Bar + /// + [DataMember(Name = "bar", EmitDefaultValue = false)] + public string Bar + { + get{ return _Bar;} + set + { + _Bar = value; + _flagBar = true; + } + } + private string _Bar; + private bool _flagBar; + + /// + /// Returns false as Bar should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeBar() + { + return _flagBar; + } + /// + /// 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() + { + var sb = new StringBuilder(); + sb.Append("class Foo {\n"); + sb.Append(" Bar: ").Append(Bar).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 Foo).AreEqual; + } + + /// + /// Returns true if Foo instances are equal + /// + /// Instance of Foo to be compared + /// Boolean + public bool Equals(Foo 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.Bar != null) + hashCode = hashCode * 59 + this.Bar.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-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/FormatTest.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/FormatTest.cs new file mode 100644 index 00000000000..771481dcbf4 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/FormatTest.cs @@ -0,0 +1,680 @@ +/* + * 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 +{ + /// + /// FormatTest + /// + [DataContract(Name = "format_test")] + public partial class FormatTest : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + [JsonConstructorAttribute] + protected FormatTest() + { + this.AdditionalProperties = new Dictionary(); + } + /// + /// Initializes a new instance of the class. + /// + /// integer. + /// int32. + /// int64. + /// number (required). + /// _float. + /// _double. + /// _decimal. + /// _string. + /// _byte (required). + /// binary. + /// date (required). + /// dateTime. + /// uuid. + /// password (required). + /// 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.. + public FormatTest(int integer = default(int), int int32 = default(int), long int64 = default(long), decimal number = default(decimal), float _float = default(float), double _double = default(double), decimal _decimal = default(decimal), string _string = default(string), byte[] _byte = 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)) + { + this._Number = number; + // to ensure "_byte" is required (not null) + this._Byte = _byte ?? throw new ArgumentNullException("_byte is a required property for FormatTest and cannot be null"); + this._Date = date; + // to ensure "password" is required (not null) + this._Password = password ?? throw new ArgumentNullException("password is a required property for FormatTest and cannot be null"); + this._Integer = integer; + this._Int32 = int32; + this._Int64 = int64; + this._Float = _float; + this._Double = _double; + this._Decimal = _decimal; + this._String = _string; + this._Binary = binary; + this._DateTime = dateTime; + this._Uuid = uuid; + this._PatternWithDigits = patternWithDigits; + this._PatternWithDigitsAndDelimiter = patternWithDigitsAndDelimiter; + this.AdditionalProperties = new Dictionary(); + } + + /// + /// Gets or Sets Integer + /// + [DataMember(Name = "integer", EmitDefaultValue = false)] + public int Integer + { + get{ return _Integer;} + set + { + _Integer = value; + _flagInteger = true; + } + } + private int _Integer; + private bool _flagInteger; + + /// + /// Returns false as Integer should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeInteger() + { + return _flagInteger; + } + /// + /// Gets or Sets Int32 + /// + [DataMember(Name = "int32", EmitDefaultValue = false)] + public int Int32 + { + get{ return _Int32;} + set + { + _Int32 = value; + _flagInt32 = true; + } + } + private int _Int32; + private bool _flagInt32; + + /// + /// Returns false as Int32 should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeInt32() + { + return _flagInt32; + } + /// + /// Gets or Sets Int64 + /// + [DataMember(Name = "int64", EmitDefaultValue = false)] + public long Int64 + { + get{ return _Int64;} + set + { + _Int64 = value; + _flagInt64 = true; + } + } + private long _Int64; + private bool _flagInt64; + + /// + /// Returns false as Int64 should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeInt64() + { + return _flagInt64; + } + /// + /// Gets or Sets Number + /// + [DataMember(Name = "number", IsRequired = true, EmitDefaultValue = false)] + public decimal Number + { + get{ return _Number;} + set + { + _Number = value; + _flagNumber = true; + } + } + private decimal _Number; + private bool _flagNumber; + + /// + /// Returns false as Number should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeNumber() + { + return _flagNumber; + } + /// + /// Gets or Sets Float + /// + [DataMember(Name = "float", EmitDefaultValue = false)] + public float Float + { + get{ return _Float;} + set + { + _Float = value; + _flagFloat = true; + } + } + private float _Float; + private bool _flagFloat; + + /// + /// Returns false as Float should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeFloat() + { + return _flagFloat; + } + /// + /// Gets or Sets Double + /// + [DataMember(Name = "double", EmitDefaultValue = false)] + public double Double + { + get{ return _Double;} + set + { + _Double = value; + _flagDouble = true; + } + } + private double _Double; + private bool _flagDouble; + + /// + /// Returns false as Double should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeDouble() + { + return _flagDouble; + } + /// + /// Gets or Sets Decimal + /// + [DataMember(Name = "decimal", EmitDefaultValue = false)] + public decimal Decimal + { + get{ return _Decimal;} + set + { + _Decimal = value; + _flagDecimal = true; + } + } + private decimal _Decimal; + private bool _flagDecimal; + + /// + /// Returns false as Decimal should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeDecimal() + { + return _flagDecimal; + } + /// + /// Gets or Sets String + /// + [DataMember(Name = "string", EmitDefaultValue = false)] + public string String + { + get{ return _String;} + set + { + _String = value; + _flagString = true; + } + } + private string _String; + private bool _flagString; + + /// + /// Returns false as String should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeString() + { + return _flagString; + } + /// + /// Gets or Sets Byte + /// + [DataMember(Name = "byte", IsRequired = true, EmitDefaultValue = false)] + public byte[] Byte + { + get{ return _Byte;} + set + { + _Byte = value; + _flagByte = true; + } + } + private byte[] _Byte; + private bool _flagByte; + + /// + /// Returns false as Byte should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeByte() + { + return _flagByte; + } + /// + /// Gets or Sets Binary + /// + [DataMember(Name = "binary", EmitDefaultValue = false)] + public System.IO.Stream Binary + { + get{ return _Binary;} + set + { + _Binary = value; + _flagBinary = true; + } + } + private System.IO.Stream _Binary; + private bool _flagBinary; + + /// + /// Returns false as Binary should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeBinary() + { + return _flagBinary; + } + /// + /// Gets or Sets Date + /// + [JsonConverter(typeof(OpenAPIDateConverter))] + [DataMember(Name = "date", IsRequired = true, EmitDefaultValue = false)] + public DateTime Date + { + get{ return _Date;} + set + { + _Date = value; + _flagDate = true; + } + } + private DateTime _Date; + private bool _flagDate; + + /// + /// Returns false as Date should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeDate() + { + return _flagDate; + } + /// + /// Gets or Sets DateTime + /// + [DataMember(Name = "dateTime", EmitDefaultValue = false)] + public DateTime DateTime + { + get{ return _DateTime;} + set + { + _DateTime = value; + _flagDateTime = true; + } + } + private DateTime _DateTime; + private bool _flagDateTime; + + /// + /// Returns false as DateTime should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeDateTime() + { + return _flagDateTime; + } + /// + /// Gets or Sets Uuid + /// + [DataMember(Name = "uuid", EmitDefaultValue = false)] + public Guid Uuid + { + get{ return _Uuid;} + set + { + _Uuid = value; + _flagUuid = true; + } + } + private Guid _Uuid; + private bool _flagUuid; + + /// + /// Returns false as Uuid should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeUuid() + { + return _flagUuid; + } + /// + /// Gets or Sets Password + /// + [DataMember(Name = "password", IsRequired = true, EmitDefaultValue = false)] + public string Password + { + get{ return _Password;} + set + { + _Password = value; + _flagPassword = true; + } + } + private string _Password; + private bool _flagPassword; + + /// + /// Returns false as Password should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializePassword() + { + return _flagPassword; + } + /// + /// A string that is a 10 digit number. Can have leading zeros. + /// + /// A string that is a 10 digit number. Can have leading zeros. + [DataMember(Name = "pattern_with_digits", EmitDefaultValue = false)] + public string PatternWithDigits + { + get{ return _PatternWithDigits;} + set + { + _PatternWithDigits = value; + _flagPatternWithDigits = true; + } + } + private string _PatternWithDigits; + private bool _flagPatternWithDigits; + + /// + /// Returns false as PatternWithDigits should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializePatternWithDigits() + { + return _flagPatternWithDigits; + } + /// + /// 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. + [DataMember(Name = "pattern_with_digits_and_delimiter", EmitDefaultValue = false)] + public string PatternWithDigitsAndDelimiter + { + get{ return _PatternWithDigitsAndDelimiter;} + set + { + _PatternWithDigitsAndDelimiter = value; + _flagPatternWithDigitsAndDelimiter = true; + } + } + private string _PatternWithDigitsAndDelimiter; + private bool _flagPatternWithDigitsAndDelimiter; + + /// + /// Returns false as PatternWithDigitsAndDelimiter should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializePatternWithDigitsAndDelimiter() + { + return _flagPatternWithDigitsAndDelimiter; + } + /// + /// 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() + { + var sb = new StringBuilder(); + sb.Append("class FormatTest {\n"); + sb.Append(" Integer: ").Append(Integer).Append("\n"); + sb.Append(" Int32: ").Append(Int32).Append("\n"); + sb.Append(" Int64: ").Append(Int64).Append("\n"); + sb.Append(" Number: ").Append(Number).Append("\n"); + sb.Append(" Float: ").Append(Float).Append("\n"); + sb.Append(" Double: ").Append(Double).Append("\n"); + sb.Append(" Decimal: ").Append(Decimal).Append("\n"); + sb.Append(" String: ").Append(String).Append("\n"); + sb.Append(" Byte: ").Append(Byte).Append("\n"); + sb.Append(" Binary: ").Append(Binary).Append("\n"); + sb.Append(" Date: ").Append(Date).Append("\n"); + sb.Append(" DateTime: ").Append(DateTime).Append("\n"); + sb.Append(" Uuid: ").Append(Uuid).Append("\n"); + sb.Append(" Password: ").Append(Password).Append("\n"); + sb.Append(" PatternWithDigits: ").Append(PatternWithDigits).Append("\n"); + sb.Append(" PatternWithDigitsAndDelimiter: ").Append(PatternWithDigitsAndDelimiter).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 FormatTest).AreEqual; + } + + /// + /// Returns true if FormatTest instances are equal + /// + /// Instance of FormatTest to be compared + /// Boolean + public bool Equals(FormatTest 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; + hashCode = hashCode * 59 + this.Integer.GetHashCode(); + hashCode = hashCode * 59 + this.Int32.GetHashCode(); + hashCode = hashCode * 59 + this.Int64.GetHashCode(); + hashCode = hashCode * 59 + this.Number.GetHashCode(); + hashCode = hashCode * 59 + this.Float.GetHashCode(); + hashCode = hashCode * 59 + this.Double.GetHashCode(); + hashCode = hashCode * 59 + this.Decimal.GetHashCode(); + if (this.String != null) + hashCode = hashCode * 59 + this.String.GetHashCode(); + if (this.Byte != null) + hashCode = hashCode * 59 + this.Byte.GetHashCode(); + if (this.Binary != null) + hashCode = hashCode * 59 + this.Binary.GetHashCode(); + if (this.Date != null) + hashCode = hashCode * 59 + this.Date.GetHashCode(); + if (this.DateTime != null) + hashCode = hashCode * 59 + this.DateTime.GetHashCode(); + if (this.Uuid != null) + hashCode = hashCode * 59 + this.Uuid.GetHashCode(); + if (this.Password != null) + hashCode = hashCode * 59 + this.Password.GetHashCode(); + if (this.PatternWithDigits != null) + hashCode = hashCode * 59 + this.PatternWithDigits.GetHashCode(); + if (this.PatternWithDigitsAndDelimiter != null) + hashCode = hashCode * 59 + this.PatternWithDigitsAndDelimiter.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) + { + // Integer (int) maximum + if(this.Integer > (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) + { + yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Integer, must be a value greater than or equal to 10.", new [] { "Integer" }); + } + + // Int32 (int) maximum + if(this.Int32 > (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) + { + yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Int32, must be a value greater than or equal to 20.", new [] { "Int32" }); + } + + // 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" }); + } + + // Float (float) maximum + if(this.Float > (float)987.6) + { + yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Float, must be a value less than or equal to 987.6.", new [] { "Float" }); + } + + // Float (float) minimum + if(this.Float < (float)54.3) + { + yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Float, must be a value greater than or equal to 54.3.", new [] { "Float" }); + } + + // Double (double) maximum + if(this.Double > (double)123.4) + { + yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Double, must be a value less than or equal to 123.4.", new [] { "Double" }); + } + + // Double (double) minimum + if(this.Double < (double)67.8) + { + yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Double, must be a value greater than or equal to 67.8.", new [] { "Double" }); + } + + // String (string) pattern + Regex regexString = new Regex(@"[a-z]", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase); + if (false == regexString.Match(this.String).Success) + { + yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for String, must match a pattern of " + regexString, new [] { "String" }); + } + + // 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" }); + } + + // PatternWithDigits (string) pattern + Regex regexPatternWithDigits = new Regex(@"^\\d{10}$", RegexOptions.CultureInvariant); + if (false == regexPatternWithDigits.Match(this.PatternWithDigits).Success) + { + yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for PatternWithDigits, must match a pattern of " + regexPatternWithDigits, new [] { "PatternWithDigits" }); + } + + // PatternWithDigitsAndDelimiter (string) pattern + Regex regexPatternWithDigitsAndDelimiter = new Regex(@"^image_\\d{1,3}$", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase); + if (false == regexPatternWithDigitsAndDelimiter.Match(this.PatternWithDigitsAndDelimiter).Success) + { + yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for PatternWithDigitsAndDelimiter, must match a pattern of " + regexPatternWithDigitsAndDelimiter, new [] { "PatternWithDigitsAndDelimiter" }); + } + + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Fruit.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Fruit.cs new file mode 100644 index 00000000000..66de6a1c6f1 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Fruit.cs @@ -0,0 +1,291 @@ +/* + * 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; +using System.Reflection; + +namespace Org.OpenAPITools.Model +{ + /// + /// Fruit + /// + [JsonConverter(typeof(FruitJsonConverter))] + [DataContract(Name = "fruit")] + public partial class Fruit : AbstractOpenAPISchema, IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class + /// with the class + /// + /// An instance of Apple. + public Fruit(Apple actualInstance) + { + this.IsNullable = false; + this.SchemaType= "oneOf"; + this.ActualInstance = actualInstance ?? throw new ArgumentException("Invalid instance found. Must not be null."); + } + + /// + /// Initializes a new instance of the class + /// with the class + /// + /// An instance of Banana. + public Fruit(Banana actualInstance) + { + this.IsNullable = false; + this.SchemaType= "oneOf"; + this.ActualInstance = actualInstance ?? throw new ArgumentException("Invalid instance found. Must not be null."); + } + + + private Object _actualInstance; + + /// + /// Gets or Sets ActualInstance + /// + public override Object ActualInstance + { + get + { + return _actualInstance; + } + set + { + if (value.GetType() == typeof(Apple)) + { + this._actualInstance = value; + } + else if (value.GetType() == typeof(Banana)) + { + this._actualInstance = value; + } + else + { + throw new ArgumentException("Invalid instance found. Must be the following types: Apple, Banana"); + } + } + } + + /// + /// Get the actual instance of `Apple`. If the actual instanct is not `Apple`, + /// the InvalidClassException will be thrown + /// + /// An instance of Apple + public Apple GetApple() + { + return (Apple)this.ActualInstance; + } + + /// + /// Get the actual instance of `Banana`. If the actual instanct is not `Banana`, + /// the InvalidClassException will be thrown + /// + /// An instance of Banana + public Banana GetBanana() + { + return (Banana)this.ActualInstance; + } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + var sb = new StringBuilder(); + sb.Append("class Fruit {\n"); + sb.Append(" ActualInstance: ").Append(this.ActualInstance).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public override string ToJson() + { + return JsonConvert.SerializeObject(this.ActualInstance, Fruit.SerializerSettings); + } + + /// + /// Converts the JSON string into an instance of Fruit + /// + /// JSON string + /// An instance of Fruit + public static Fruit FromJson(string jsonString) + { + Fruit newFruit = null; + + if (jsonString == null) + { + return newFruit; + } + int match = 0; + List matchedTypes = new List(); + + try + { + // if it does not contains "AdditionalProperties", use SerializerSettings to deserialize + if (typeof(Apple).GetProperty("AdditionalProperties") == null) + { + newFruit = new Fruit(JsonConvert.DeserializeObject(jsonString, Fruit.SerializerSettings)); + } + else + { + newFruit = new Fruit(JsonConvert.DeserializeObject(jsonString, Fruit.AdditionalPropertiesSerializerSettings)); + } + matchedTypes.Add("Apple"); + match++; + } + catch (Exception exception) + { + // deserialization failed, try the next one + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into Apple: {1}", jsonString, exception.ToString())); + } + + try + { + // if it does not contains "AdditionalProperties", use SerializerSettings to deserialize + if (typeof(Banana).GetProperty("AdditionalProperties") == null) + { + newFruit = new Fruit(JsonConvert.DeserializeObject(jsonString, Fruit.SerializerSettings)); + } + else + { + newFruit = new Fruit(JsonConvert.DeserializeObject(jsonString, Fruit.AdditionalPropertiesSerializerSettings)); + } + matchedTypes.Add("Banana"); + match++; + } + catch (Exception exception) + { + // deserialization failed, try the next one + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into Banana: {1}", jsonString, exception.ToString())); + } + + if (match == 0) + { + throw new InvalidDataException("The JSON string `" + jsonString + "` cannot be deserialized into any schema defined."); + } + else if (match > 1) + { + throw new InvalidDataException("The JSON string `" + jsonString + "` incorrectly matches more than one schema (should be exactly one match): " + matchedTypes); + } + + // deserialization is considered successful at this point if no exception has been thrown. + return newFruit; + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input as Fruit).AreEqual; + } + + /// + /// Returns true if Fruit instances are equal + /// + /// Instance of Fruit to be compared + /// Boolean + public bool Equals(Fruit 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.ActualInstance != null) + hashCode = hashCode * 59 + this.ActualInstance.GetHashCode(); + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// Custom JSON converter for Fruit + /// + public class FruitJsonConverter : JsonConverter + { + /// + /// To write the JSON string + /// + /// JSON writer + /// Object to be converted into a JSON string + /// JSON Serializer + public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) + { + writer.WriteRawValue((string)(typeof(Fruit).GetMethod("ToJson").Invoke(value, null))); + } + + /// + /// To convert a JSON string into an object + /// + /// JSON reader + /// Object type + /// Existing value + /// JSON Serializer + /// The object converted from the JSON string + public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) + { + if(reader.TokenType != JsonToken.Null) + { + return Fruit.FromJson(JObject.Load(reader).ToString(Formatting.None)); + } + return null; + } + + /// + /// Check if the object can be converted + /// + /// Object type + /// True if the object can be converted + public override bool CanConvert(Type objectType) + { + return false; + } + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/FruitReq.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/FruitReq.cs new file mode 100644 index 00000000000..488c489d73a --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/FruitReq.cs @@ -0,0 +1,300 @@ +/* + * 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; +using System.Reflection; + +namespace Org.OpenAPITools.Model +{ + /// + /// FruitReq + /// + [JsonConverter(typeof(FruitReqJsonConverter))] + [DataContract(Name = "fruitReq")] + public partial class FruitReq : AbstractOpenAPISchema, IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + public FruitReq() + { + this.IsNullable = true; + this.SchemaType= "oneOf"; + } + + /// + /// Initializes a new instance of the class + /// with the class + /// + /// An instance of AppleReq. + public FruitReq(AppleReq actualInstance) + { + this.IsNullable = true; + this.SchemaType= "oneOf"; + this.ActualInstance = actualInstance; + } + + /// + /// Initializes a new instance of the class + /// with the class + /// + /// An instance of BananaReq. + public FruitReq(BananaReq actualInstance) + { + this.IsNullable = true; + this.SchemaType= "oneOf"; + this.ActualInstance = actualInstance; + } + + + private Object _actualInstance; + + /// + /// Gets or Sets ActualInstance + /// + public override Object ActualInstance + { + get + { + return _actualInstance; + } + set + { + if (value.GetType() == typeof(AppleReq)) + { + this._actualInstance = value; + } + else if (value.GetType() == typeof(BananaReq)) + { + this._actualInstance = value; + } + else + { + throw new ArgumentException("Invalid instance found. Must be the following types: AppleReq, BananaReq"); + } + } + } + + /// + /// Get the actual instance of `AppleReq`. If the actual instanct is not `AppleReq`, + /// the InvalidClassException will be thrown + /// + /// An instance of AppleReq + public AppleReq GetAppleReq() + { + return (AppleReq)this.ActualInstance; + } + + /// + /// Get the actual instance of `BananaReq`. If the actual instanct is not `BananaReq`, + /// the InvalidClassException will be thrown + /// + /// An instance of BananaReq + public BananaReq GetBananaReq() + { + return (BananaReq)this.ActualInstance; + } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + var sb = new StringBuilder(); + sb.Append("class FruitReq {\n"); + sb.Append(" ActualInstance: ").Append(this.ActualInstance).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public override string ToJson() + { + return JsonConvert.SerializeObject(this.ActualInstance, FruitReq.SerializerSettings); + } + + /// + /// Converts the JSON string into an instance of FruitReq + /// + /// JSON string + /// An instance of FruitReq + public static FruitReq FromJson(string jsonString) + { + FruitReq newFruitReq = null; + + if (jsonString == null) + { + return newFruitReq; + } + int match = 0; + List matchedTypes = new List(); + + try + { + // if it does not contains "AdditionalProperties", use SerializerSettings to deserialize + if (typeof(AppleReq).GetProperty("AdditionalProperties") == null) + { + newFruitReq = new FruitReq(JsonConvert.DeserializeObject(jsonString, FruitReq.SerializerSettings)); + } + else + { + newFruitReq = new FruitReq(JsonConvert.DeserializeObject(jsonString, FruitReq.AdditionalPropertiesSerializerSettings)); + } + matchedTypes.Add("AppleReq"); + match++; + } + catch (Exception exception) + { + // deserialization failed, try the next one + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into AppleReq: {1}", jsonString, exception.ToString())); + } + + try + { + // if it does not contains "AdditionalProperties", use SerializerSettings to deserialize + if (typeof(BananaReq).GetProperty("AdditionalProperties") == null) + { + newFruitReq = new FruitReq(JsonConvert.DeserializeObject(jsonString, FruitReq.SerializerSettings)); + } + else + { + newFruitReq = new FruitReq(JsonConvert.DeserializeObject(jsonString, FruitReq.AdditionalPropertiesSerializerSettings)); + } + matchedTypes.Add("BananaReq"); + match++; + } + catch (Exception exception) + { + // deserialization failed, try the next one + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into BananaReq: {1}", jsonString, exception.ToString())); + } + + if (match == 0) + { + throw new InvalidDataException("The JSON string `" + jsonString + "` cannot be deserialized into any schema defined."); + } + else if (match > 1) + { + throw new InvalidDataException("The JSON string `" + jsonString + "` incorrectly matches more than one schema (should be exactly one match): " + matchedTypes); + } + + // deserialization is considered successful at this point if no exception has been thrown. + return newFruitReq; + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input as FruitReq).AreEqual; + } + + /// + /// Returns true if FruitReq instances are equal + /// + /// Instance of FruitReq to be compared + /// Boolean + public bool Equals(FruitReq 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.ActualInstance != null) + hashCode = hashCode * 59 + this.ActualInstance.GetHashCode(); + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// Custom JSON converter for FruitReq + /// + public class FruitReqJsonConverter : JsonConverter + { + /// + /// To write the JSON string + /// + /// JSON writer + /// Object to be converted into a JSON string + /// JSON Serializer + public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) + { + writer.WriteRawValue((string)(typeof(FruitReq).GetMethod("ToJson").Invoke(value, null))); + } + + /// + /// To convert a JSON string into an object + /// + /// JSON reader + /// Object type + /// Existing value + /// JSON Serializer + /// The object converted from the JSON string + public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) + { + if(reader.TokenType != JsonToken.Null) + { + return FruitReq.FromJson(JObject.Load(reader).ToString(Formatting.None)); + } + return null; + } + + /// + /// Check if the object can be converted + /// + /// Object type + /// True if the object can be converted + public override bool CanConvert(Type objectType) + { + return false; + } + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/GmFruit.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/GmFruit.cs new file mode 100644 index 00000000000..1aaa59d3f8b --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/GmFruit.cs @@ -0,0 +1,263 @@ +/* + * 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 +{ + /// + /// GmFruit + /// + [JsonConverter(typeof(GmFruitJsonConverter))] + [DataContract(Name = "gmFruit")] + public partial class GmFruit : AbstractOpenAPISchema, IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class + /// with the class + /// + /// An instance of Apple. + public GmFruit(Apple actualInstance) + { + this.IsNullable = false; + this.SchemaType= "anyOf"; + this.ActualInstance = actualInstance ?? throw new ArgumentException("Invalid instance found. Must not be null."); + } + + /// + /// Initializes a new instance of the class + /// with the class + /// + /// An instance of Banana. + public GmFruit(Banana actualInstance) + { + this.IsNullable = false; + this.SchemaType= "anyOf"; + this.ActualInstance = actualInstance ?? throw new ArgumentException("Invalid instance found. Must not be null."); + } + + + private Object _actualInstance; + + /// + /// Gets or Sets ActualInstance + /// + public override Object ActualInstance + { + get + { + return _actualInstance; + } + set + { + if (value.GetType() == typeof(Apple)) + { + this._actualInstance = value; + } + else if (value.GetType() == typeof(Banana)) + { + this._actualInstance = value; + } + else + { + throw new ArgumentException("Invalid instance found. Must be the following types: Apple, Banana"); + } + } + } + + /// + /// Get the actual instance of `Apple`. If the actual instanct is not `Apple`, + /// the InvalidClassException will be thrown + /// + /// An instance of Apple + public Apple GetApple() + { + return (Apple)this.ActualInstance; + } + + /// + /// Get the actual instance of `Banana`. If the actual instanct is not `Banana`, + /// the InvalidClassException will be thrown + /// + /// An instance of Banana + public Banana GetBanana() + { + return (Banana)this.ActualInstance; + } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + var sb = new StringBuilder(); + sb.Append("class GmFruit {\n"); + sb.Append(" ActualInstance: ").Append(this.ActualInstance).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public override string ToJson() + { + return JsonConvert.SerializeObject(this.ActualInstance, GmFruit.SerializerSettings); + } + + /// + /// Converts the JSON string into an instance of GmFruit + /// + /// JSON string + /// An instance of GmFruit + public static GmFruit FromJson(string jsonString) + { + GmFruit newGmFruit = null; + + if (jsonString == null) + { + return newGmFruit; + } + + try + { + newGmFruit = new GmFruit(JsonConvert.DeserializeObject(jsonString, GmFruit.SerializerSettings)); + // deserialization is considered successful at this point if no exception has been thrown. + return newGmFruit; + } + catch (Exception exception) + { + // deserialization failed, try the next one + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into Apple: {1}", jsonString, exception.ToString())); + } + + try + { + newGmFruit = new GmFruit(JsonConvert.DeserializeObject(jsonString, GmFruit.SerializerSettings)); + // deserialization is considered successful at this point if no exception has been thrown. + return newGmFruit; + } + catch (Exception exception) + { + // deserialization failed, try the next one + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into Banana: {1}", jsonString, exception.ToString())); + } + + // no match found, throw an exception + throw new InvalidDataException("The JSON string `" + jsonString + "` cannot be deserialized into any schema defined."); + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input as GmFruit).AreEqual; + } + + /// + /// Returns true if GmFruit instances are equal + /// + /// Instance of GmFruit to be compared + /// Boolean + public bool Equals(GmFruit 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.ActualInstance != null) + hashCode = hashCode * 59 + this.ActualInstance.GetHashCode(); + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// Custom JSON converter for GmFruit + /// + public class GmFruitJsonConverter : JsonConverter + { + /// + /// To write the JSON string + /// + /// JSON writer + /// Object to be converted into a JSON string + /// JSON Serializer + public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) + { + writer.WriteRawValue((string)(typeof(GmFruit).GetMethod("ToJson").Invoke(value, null))); + } + + /// + /// To convert a JSON string into an object + /// + /// JSON reader + /// Object type + /// Existing value + /// JSON Serializer + /// The object converted from the JSON string + public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) + { + if(reader.TokenType != JsonToken.Null) + { + return GmFruit.FromJson(JObject.Load(reader).ToString(Formatting.None)); + } + return null; + } + + /// + /// Check if the object can be converted + /// + /// Object type + /// True if the object can be converted + public override bool CanConvert(Type objectType) + { + return false; + } + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/GrandparentAnimal.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/GrandparentAnimal.cs new file mode 100644 index 00000000000..ab4b68f27ac --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/GrandparentAnimal.cs @@ -0,0 +1,169 @@ +/* + * 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 JsonSubTypes; +using System.ComponentModel.DataAnnotations; +using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; +using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; + +namespace Org.OpenAPITools.Model +{ + /// + /// GrandparentAnimal + /// + [DataContract(Name = "GrandparentAnimal")] + [JsonConverter(typeof(JsonSubtypes), "PetType")] + [JsonSubtypes.KnownSubType(typeof(ChildCat), "ChildCat")] + [JsonSubtypes.KnownSubType(typeof(ParentPet), "ParentPet")] + public partial class GrandparentAnimal : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + [JsonConstructorAttribute] + protected GrandparentAnimal() + { + this.AdditionalProperties = new Dictionary(); + } + /// + /// Initializes a new instance of the class. + /// + /// petType (required). + public GrandparentAnimal(string petType = default(string)) + { + // to ensure "petType" is required (not null) + this._PetType = petType ?? throw new ArgumentNullException("petType is a required property for GrandparentAnimal and cannot be null"); + this.AdditionalProperties = new Dictionary(); + } + + /// + /// Gets or Sets PetType + /// + [DataMember(Name = "pet_type", IsRequired = true, EmitDefaultValue = false)] + public string PetType + { + get{ return _PetType;} + set + { + _PetType = value; + _flagPetType = true; + } + } + private string _PetType; + private bool _flagPetType; + + /// + /// Returns false as PetType should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializePetType() + { + return _flagPetType; + } + /// + /// 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() + { + var sb = new StringBuilder(); + sb.Append("class GrandparentAnimal {\n"); + sb.Append(" PetType: ").Append(PetType).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 GrandparentAnimal).AreEqual; + } + + /// + /// Returns true if GrandparentAnimal instances are equal + /// + /// Instance of GrandparentAnimal to be compared + /// Boolean + public bool Equals(GrandparentAnimal 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.PetType != null) + hashCode = hashCode * 59 + this.PetType.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) + { + 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-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/HasOnlyReadOnly.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/HasOnlyReadOnly.cs new file mode 100644 index 00000000000..76b3bfdcce3 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/HasOnlyReadOnly.cs @@ -0,0 +1,152 @@ +/* + * 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 +{ + /// + /// HasOnlyReadOnly + /// + [DataContract(Name = "hasOnlyReadOnly")] + public partial class HasOnlyReadOnly : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + [JsonConstructorAttribute] + public HasOnlyReadOnly() + { + this.AdditionalProperties = new Dictionary(); + } + + /// + /// Gets or Sets Bar + /// + [DataMember(Name = "bar", EmitDefaultValue = false)] + public string Bar { get; private set; } + + /// + /// Returns false as Bar should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeBar() + { + return false; + } + /// + /// Gets or Sets Foo + /// + [DataMember(Name = "foo", EmitDefaultValue = false)] + public string Foo { get; private set; } + + /// + /// Returns false as Foo should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeFoo() + { + return false; + } + /// + /// 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() + { + var sb = new StringBuilder(); + sb.Append("class HasOnlyReadOnly {\n"); + sb.Append(" Bar: ").Append(Bar).Append("\n"); + sb.Append(" Foo: ").Append(Foo).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 HasOnlyReadOnly).AreEqual; + } + + /// + /// Returns true if HasOnlyReadOnly instances are equal + /// + /// Instance of HasOnlyReadOnly to be compared + /// Boolean + public bool Equals(HasOnlyReadOnly 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.Bar != null) + hashCode = hashCode * 59 + this.Bar.GetHashCode(); + if (this.Foo != null) + hashCode = hashCode * 59 + this.Foo.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-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/HealthCheckResult.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/HealthCheckResult.cs new file mode 100644 index 00000000000..d0a48d18a8f --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/HealthCheckResult.cs @@ -0,0 +1,146 @@ +/* + * 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 +{ + /// + /// Just a string to inform instance is up and running. Make it nullable in hope to get it as pointer in generated model. + /// + [DataContract(Name = "HealthCheckResult")] + public partial class HealthCheckResult : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// nullableMessage. + public HealthCheckResult(string nullableMessage = default(string)) + { + this._NullableMessage = nullableMessage; + this.AdditionalProperties = new Dictionary(); + } + + /// + /// Gets or Sets NullableMessage + /// + [DataMember(Name = "NullableMessage", EmitDefaultValue = true)] + public string NullableMessage + { + get{ return _NullableMessage;} + set + { + _NullableMessage = value; + _flagNullableMessage = true; + } + } + private string _NullableMessage; + private bool _flagNullableMessage; + + /// + /// Returns false as NullableMessage should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeNullableMessage() + { + return _flagNullableMessage; + } + /// + /// 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() + { + var sb = new StringBuilder(); + sb.Append("class HealthCheckResult {\n"); + sb.Append(" NullableMessage: ").Append(NullableMessage).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 HealthCheckResult).AreEqual; + } + + /// + /// Returns true if HealthCheckResult instances are equal + /// + /// Instance of HealthCheckResult to be compared + /// Boolean + public bool Equals(HealthCheckResult 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.NullableMessage != null) + hashCode = hashCode * 59 + this.NullableMessage.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-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/InlineResponseDefault.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/InlineResponseDefault.cs new file mode 100644 index 00000000000..3110927e009 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/InlineResponseDefault.cs @@ -0,0 +1,146 @@ +/* + * 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 +{ + /// + /// InlineResponseDefault + /// + [DataContract(Name = "inline_response_default")] + public partial class InlineResponseDefault : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// _string. + public InlineResponseDefault(Foo _string = default(Foo)) + { + this._String = _string; + this.AdditionalProperties = new Dictionary(); + } + + /// + /// Gets or Sets String + /// + [DataMember(Name = "string", EmitDefaultValue = false)] + public Foo String + { + get{ return _String;} + set + { + _String = value; + _flagString = true; + } + } + private Foo _String; + private bool _flagString; + + /// + /// Returns false as String should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeString() + { + return _flagString; + } + /// + /// 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() + { + var sb = new StringBuilder(); + sb.Append("class InlineResponseDefault {\n"); + sb.Append(" String: ").Append(String).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 InlineResponseDefault).AreEqual; + } + + /// + /// Returns true if InlineResponseDefault instances are equal + /// + /// Instance of InlineResponseDefault to be compared + /// Boolean + public bool Equals(InlineResponseDefault 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.String != null) + hashCode = hashCode * 59 + this.String.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-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/IsoscelesTriangle.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/IsoscelesTriangle.cs new file mode 100644 index 00000000000..f23664d54c9 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/IsoscelesTriangle.cs @@ -0,0 +1,172 @@ +/* + * 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 +{ + /// + /// IsoscelesTriangle + /// + [DataContract(Name = "IsoscelesTriangle")] + public partial class IsoscelesTriangle : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + [JsonConstructorAttribute] + protected IsoscelesTriangle() { } + /// + /// Initializes a new instance of the class. + /// + /// shapeType (required). + /// triangleType (required). + public IsoscelesTriangle(string shapeType = default(string), string triangleType = default(string)) + { + // to ensure "shapeType" is required (not null) + this._ShapeType = shapeType ?? throw new ArgumentNullException("shapeType is a required property for IsoscelesTriangle and cannot be null"); + // to ensure "triangleType" is required (not null) + this._TriangleType = triangleType ?? throw new ArgumentNullException("triangleType is a required property for IsoscelesTriangle and cannot be null"); + } + + /// + /// Gets or Sets ShapeType + /// + [DataMember(Name = "shapeType", IsRequired = true, EmitDefaultValue = false)] + public string ShapeType + { + get{ return _ShapeType;} + set + { + _ShapeType = value; + _flagShapeType = true; + } + } + private string _ShapeType; + private bool _flagShapeType; + + /// + /// Returns false as ShapeType should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeShapeType() + { + return _flagShapeType; + } + /// + /// Gets or Sets TriangleType + /// + [DataMember(Name = "triangleType", IsRequired = true, EmitDefaultValue = false)] + public string TriangleType + { + get{ return _TriangleType;} + set + { + _TriangleType = value; + _flagTriangleType = true; + } + } + private string _TriangleType; + private bool _flagTriangleType; + + /// + /// Returns false as TriangleType should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeTriangleType() + { + return _flagTriangleType; + } + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + var sb = new StringBuilder(); + sb.Append("class IsoscelesTriangle {\n"); + sb.Append(" ShapeType: ").Append(ShapeType).Append("\n"); + sb.Append(" TriangleType: ").Append(TriangleType).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 IsoscelesTriangle).AreEqual; + } + + /// + /// Returns true if IsoscelesTriangle instances are equal + /// + /// Instance of IsoscelesTriangle to be compared + /// Boolean + public bool Equals(IsoscelesTriangle 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.ShapeType != null) + hashCode = hashCode * 59 + this.ShapeType.GetHashCode(); + if (this.TriangleType != null) + hashCode = hashCode * 59 + this.TriangleType.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-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/List.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/List.cs new file mode 100644 index 00000000000..dfb5a8abd4c --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/List.cs @@ -0,0 +1,146 @@ +/* + * 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 +{ + /// + /// List + /// + [DataContract(Name = "List")] + public partial class List : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// _123list. + public List(string _123list = default(string)) + { + this.__123List = _123list; + this.AdditionalProperties = new Dictionary(); + } + + /// + /// Gets or Sets _123List + /// + [DataMember(Name = "123-list", EmitDefaultValue = false)] + public string _123List + { + get{ return __123List;} + set + { + __123List = value; + _flag_123List = true; + } + } + private string __123List; + private bool _flag_123List; + + /// + /// Returns false as _123List should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerialize_123List() + { + return _flag_123List; + } + /// + /// 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() + { + var sb = new StringBuilder(); + sb.Append("class List {\n"); + sb.Append(" _123List: ").Append(_123List).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 List).AreEqual; + } + + /// + /// Returns true if List instances are equal + /// + /// Instance of List to be compared + /// Boolean + public bool Equals(List 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._123List != null) + hashCode = hashCode * 59 + this._123List.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-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Mammal.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Mammal.cs new file mode 100644 index 00000000000..ed940d7ab6f --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Mammal.cs @@ -0,0 +1,356 @@ +/* + * 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 JsonSubTypes; +using System.ComponentModel.DataAnnotations; +using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; +using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using System.Reflection; + +namespace Org.OpenAPITools.Model +{ + /// + /// Mammal + /// + [JsonConverter(typeof(MammalJsonConverter))] + [DataContract(Name = "mammal")] + public partial class Mammal : AbstractOpenAPISchema, IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class + /// with the class + /// + /// An instance of Pig. + public Mammal(Pig actualInstance) + { + this.IsNullable = false; + this.SchemaType= "oneOf"; + this.ActualInstance = actualInstance ?? throw new ArgumentException("Invalid instance found. Must not be null."); + } + + /// + /// Initializes a new instance of the class + /// with the class + /// + /// An instance of Whale. + public Mammal(Whale actualInstance) + { + this.IsNullable = false; + this.SchemaType= "oneOf"; + this.ActualInstance = actualInstance ?? throw new ArgumentException("Invalid instance found. Must not be null."); + } + + /// + /// Initializes a new instance of the class + /// with the class + /// + /// An instance of Zebra. + public Mammal(Zebra actualInstance) + { + this.IsNullable = false; + this.SchemaType= "oneOf"; + this.ActualInstance = actualInstance ?? throw new ArgumentException("Invalid instance found. Must not be null."); + } + + + private Object _actualInstance; + + /// + /// Gets or Sets ActualInstance + /// + public override Object ActualInstance + { + get + { + return _actualInstance; + } + set + { + if (value.GetType() == typeof(Pig)) + { + this._actualInstance = value; + } + else if (value.GetType() == typeof(Whale)) + { + this._actualInstance = value; + } + else if (value.GetType() == typeof(Zebra)) + { + this._actualInstance = value; + } + else + { + throw new ArgumentException("Invalid instance found. Must be the following types: Pig, Whale, Zebra"); + } + } + } + + /// + /// Get the actual instance of `Pig`. If the actual instanct is not `Pig`, + /// the InvalidClassException will be thrown + /// + /// An instance of Pig + public Pig GetPig() + { + return (Pig)this.ActualInstance; + } + + /// + /// Get the actual instance of `Whale`. If the actual instanct is not `Whale`, + /// the InvalidClassException will be thrown + /// + /// An instance of Whale + public Whale GetWhale() + { + return (Whale)this.ActualInstance; + } + + /// + /// Get the actual instance of `Zebra`. If the actual instanct is not `Zebra`, + /// the InvalidClassException will be thrown + /// + /// An instance of Zebra + public Zebra GetZebra() + { + return (Zebra)this.ActualInstance; + } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + var sb = new StringBuilder(); + sb.Append("class Mammal {\n"); + sb.Append(" ActualInstance: ").Append(this.ActualInstance).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public override string ToJson() + { + return JsonConvert.SerializeObject(this.ActualInstance, Mammal.SerializerSettings); + } + + /// + /// Converts the JSON string into an instance of Mammal + /// + /// JSON string + /// An instance of Mammal + public static Mammal FromJson(string jsonString) + { + Mammal newMammal = null; + + if (jsonString == null) + { + return newMammal; + } + + string discriminatorValue = JObject.Parse(jsonString)["className"].ToString(); + switch (discriminatorValue) + { + case "Pig": + newMammal = new Mammal(JsonConvert.DeserializeObject(jsonString, Mammal.AdditionalPropertiesSerializerSettings)); + return newMammal; + case "whale": + newMammal = new Mammal(JsonConvert.DeserializeObject(jsonString, Mammal.AdditionalPropertiesSerializerSettings)); + return newMammal; + case "zebra": + newMammal = new Mammal(JsonConvert.DeserializeObject(jsonString, Mammal.AdditionalPropertiesSerializerSettings)); + return newMammal; + default: + System.Diagnostics.Debug.WriteLine(string.Format("Failed to lookup discriminator value `{0}` for Mammal. Possible values: Pig whale zebra", discriminatorValue)); + break; + } + + int match = 0; + List matchedTypes = new List(); + + try + { + // if it does not contains "AdditionalProperties", use SerializerSettings to deserialize + if (typeof(Pig).GetProperty("AdditionalProperties") == null) + { + newMammal = new Mammal(JsonConvert.DeserializeObject(jsonString, Mammal.SerializerSettings)); + } + else + { + newMammal = new Mammal(JsonConvert.DeserializeObject(jsonString, Mammal.AdditionalPropertiesSerializerSettings)); + } + matchedTypes.Add("Pig"); + match++; + } + catch (Exception exception) + { + // deserialization failed, try the next one + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into Pig: {1}", jsonString, exception.ToString())); + } + + try + { + // if it does not contains "AdditionalProperties", use SerializerSettings to deserialize + if (typeof(Whale).GetProperty("AdditionalProperties") == null) + { + newMammal = new Mammal(JsonConvert.DeserializeObject(jsonString, Mammal.SerializerSettings)); + } + else + { + newMammal = new Mammal(JsonConvert.DeserializeObject(jsonString, Mammal.AdditionalPropertiesSerializerSettings)); + } + matchedTypes.Add("Whale"); + match++; + } + catch (Exception exception) + { + // deserialization failed, try the next one + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into Whale: {1}", jsonString, exception.ToString())); + } + + try + { + // if it does not contains "AdditionalProperties", use SerializerSettings to deserialize + if (typeof(Zebra).GetProperty("AdditionalProperties") == null) + { + newMammal = new Mammal(JsonConvert.DeserializeObject(jsonString, Mammal.SerializerSettings)); + } + else + { + newMammal = new Mammal(JsonConvert.DeserializeObject(jsonString, Mammal.AdditionalPropertiesSerializerSettings)); + } + matchedTypes.Add("Zebra"); + match++; + } + catch (Exception exception) + { + // deserialization failed, try the next one + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into Zebra: {1}", jsonString, exception.ToString())); + } + + if (match == 0) + { + throw new InvalidDataException("The JSON string `" + jsonString + "` cannot be deserialized into any schema defined."); + } + else if (match > 1) + { + throw new InvalidDataException("The JSON string `" + jsonString + "` incorrectly matches more than one schema (should be exactly one match): " + matchedTypes); + } + + // deserialization is considered successful at this point if no exception has been thrown. + return newMammal; + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input as Mammal).AreEqual; + } + + /// + /// Returns true if Mammal instances are equal + /// + /// Instance of Mammal to be compared + /// Boolean + public bool Equals(Mammal 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.ActualInstance != null) + hashCode = hashCode * 59 + this.ActualInstance.GetHashCode(); + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// Custom JSON converter for Mammal + /// + public class MammalJsonConverter : JsonConverter + { + /// + /// To write the JSON string + /// + /// JSON writer + /// Object to be converted into a JSON string + /// JSON Serializer + public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) + { + writer.WriteRawValue((string)(typeof(Mammal).GetMethod("ToJson").Invoke(value, null))); + } + + /// + /// To convert a JSON string into an object + /// + /// JSON reader + /// Object type + /// Existing value + /// JSON Serializer + /// The object converted from the JSON string + public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) + { + if(reader.TokenType != JsonToken.Null) + { + return Mammal.FromJson(JObject.Load(reader).ToString(Formatting.None)); + } + return null; + } + + /// + /// Check if the object can be converted + /// + /// Object type + /// True if the object can be converted + public override bool CanConvert(Type objectType) + { + return false; + } + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/MapTest.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/MapTest.cs new file mode 100644 index 00000000000..46684e9a9b3 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/MapTest.cs @@ -0,0 +1,255 @@ +/* + * 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 +{ + /// + /// MapTest + /// + [DataContract(Name = "MapTest")] + public partial class MapTest : IEquatable, IValidatableObject + { + /// + /// Defines Inner + /// + [JsonConverter(typeof(StringEnumConverter))] + public enum InnerEnum + { + /// + /// Enum UPPER for value: UPPER + /// + [EnumMember(Value = "UPPER")] + UPPER = 1, + + /// + /// Enum Lower for value: lower + /// + [EnumMember(Value = "lower")] + Lower = 2 + + } + + + + /// + /// Gets or Sets MapOfEnumString + /// + + [DataMember(Name = "map_of_enum_string", EmitDefaultValue = false)] + public Dictionary MapOfEnumString + { + get{ return _MapOfEnumString;} + set + { + _MapOfEnumString = value; + _flagMapOfEnumString = true; + } + } + private Dictionary _MapOfEnumString; + private bool _flagMapOfEnumString; + + /// + /// Returns false as MapOfEnumString should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeMapOfEnumString() + { + return _flagMapOfEnumString; + } + /// + /// Initializes a new instance of the class. + /// + /// mapMapOfString. + /// mapOfEnumString. + /// directMap. + /// indirectMap. + public MapTest(Dictionary> mapMapOfString = default(Dictionary>), Dictionary mapOfEnumString = default(Dictionary), Dictionary directMap = default(Dictionary), Dictionary indirectMap = default(Dictionary)) + { + this._MapMapOfString = mapMapOfString; + this._MapOfEnumString = mapOfEnumString; + this._DirectMap = directMap; + this._IndirectMap = indirectMap; + this.AdditionalProperties = new Dictionary(); + } + + /// + /// Gets or Sets MapMapOfString + /// + [DataMember(Name = "map_map_of_string", EmitDefaultValue = false)] + public Dictionary> MapMapOfString + { + get{ return _MapMapOfString;} + set + { + _MapMapOfString = value; + _flagMapMapOfString = true; + } + } + private Dictionary> _MapMapOfString; + private bool _flagMapMapOfString; + + /// + /// Returns false as MapMapOfString should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeMapMapOfString() + { + return _flagMapMapOfString; + } + /// + /// Gets or Sets DirectMap + /// + [DataMember(Name = "direct_map", EmitDefaultValue = false)] + public Dictionary DirectMap + { + get{ return _DirectMap;} + set + { + _DirectMap = value; + _flagDirectMap = true; + } + } + private Dictionary _DirectMap; + private bool _flagDirectMap; + + /// + /// Returns false as DirectMap should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeDirectMap() + { + return _flagDirectMap; + } + /// + /// Gets or Sets IndirectMap + /// + [DataMember(Name = "indirect_map", EmitDefaultValue = false)] + public Dictionary IndirectMap + { + get{ return _IndirectMap;} + set + { + _IndirectMap = value; + _flagIndirectMap = true; + } + } + private Dictionary _IndirectMap; + private bool _flagIndirectMap; + + /// + /// Returns false as IndirectMap should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeIndirectMap() + { + return _flagIndirectMap; + } + /// + /// 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() + { + var sb = new StringBuilder(); + sb.Append("class MapTest {\n"); + sb.Append(" MapMapOfString: ").Append(MapMapOfString).Append("\n"); + sb.Append(" MapOfEnumString: ").Append(MapOfEnumString).Append("\n"); + sb.Append(" DirectMap: ").Append(DirectMap).Append("\n"); + sb.Append(" IndirectMap: ").Append(IndirectMap).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 MapTest).AreEqual; + } + + /// + /// Returns true if MapTest instances are equal + /// + /// Instance of MapTest to be compared + /// Boolean + public bool Equals(MapTest 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.MapMapOfString != null) + hashCode = hashCode * 59 + this.MapMapOfString.GetHashCode(); + hashCode = hashCode * 59 + this.MapOfEnumString.GetHashCode(); + if (this.DirectMap != null) + hashCode = hashCode * 59 + this.DirectMap.GetHashCode(); + if (this.IndirectMap != null) + hashCode = hashCode * 59 + this.IndirectMap.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-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/MixedPropertiesAndAdditionalPropertiesClass.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/MixedPropertiesAndAdditionalPropertiesClass.cs new file mode 100644 index 00000000000..398f665583f --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/MixedPropertiesAndAdditionalPropertiesClass.cs @@ -0,0 +1,204 @@ +/* + * 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 +{ + /// + /// MixedPropertiesAndAdditionalPropertiesClass + /// + [DataContract(Name = "MixedPropertiesAndAdditionalPropertiesClass")] + public partial class MixedPropertiesAndAdditionalPropertiesClass : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// uuid. + /// dateTime. + /// map. + public MixedPropertiesAndAdditionalPropertiesClass(Guid uuid = default(Guid), DateTime dateTime = default(DateTime), Dictionary map = default(Dictionary)) + { + this._Uuid = uuid; + this._DateTime = dateTime; + this._Map = map; + this.AdditionalProperties = new Dictionary(); + } + + /// + /// Gets or Sets Uuid + /// + [DataMember(Name = "uuid", EmitDefaultValue = false)] + public Guid Uuid + { + get{ return _Uuid;} + set + { + _Uuid = value; + _flagUuid = true; + } + } + private Guid _Uuid; + private bool _flagUuid; + + /// + /// Returns false as Uuid should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeUuid() + { + return _flagUuid; + } + /// + /// Gets or Sets DateTime + /// + [DataMember(Name = "dateTime", EmitDefaultValue = false)] + public DateTime DateTime + { + get{ return _DateTime;} + set + { + _DateTime = value; + _flagDateTime = true; + } + } + private DateTime _DateTime; + private bool _flagDateTime; + + /// + /// Returns false as DateTime should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeDateTime() + { + return _flagDateTime; + } + /// + /// Gets or Sets Map + /// + [DataMember(Name = "map", EmitDefaultValue = false)] + public Dictionary Map + { + get{ return _Map;} + set + { + _Map = value; + _flagMap = true; + } + } + private Dictionary _Map; + private bool _flagMap; + + /// + /// Returns false as Map should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeMap() + { + return _flagMap; + } + /// + /// 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() + { + var sb = new StringBuilder(); + sb.Append("class MixedPropertiesAndAdditionalPropertiesClass {\n"); + sb.Append(" Uuid: ").Append(Uuid).Append("\n"); + sb.Append(" DateTime: ").Append(DateTime).Append("\n"); + sb.Append(" Map: ").Append(Map).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 MixedPropertiesAndAdditionalPropertiesClass).AreEqual; + } + + /// + /// Returns true if MixedPropertiesAndAdditionalPropertiesClass instances are equal + /// + /// Instance of MixedPropertiesAndAdditionalPropertiesClass to be compared + /// Boolean + public bool Equals(MixedPropertiesAndAdditionalPropertiesClass 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.Uuid != null) + hashCode = hashCode * 59 + this.Uuid.GetHashCode(); + if (this.DateTime != null) + hashCode = hashCode * 59 + this.DateTime.GetHashCode(); + if (this.Map != null) + hashCode = hashCode * 59 + this.Map.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-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Model200Response.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Model200Response.cs new file mode 100644 index 00000000000..551edfd19de --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Model200Response.cs @@ -0,0 +1,174 @@ +/* + * 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 +{ + /// + /// Model for testing model name starting with number + /// + [DataContract(Name = "200_response")] + public partial class Model200Response : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// name. + /// _class. + public Model200Response(int name = default(int), string _class = default(string)) + { + this._Name = name; + this._Class = _class; + this.AdditionalProperties = new Dictionary(); + } + + /// + /// Gets or Sets Name + /// + [DataMember(Name = "name", EmitDefaultValue = false)] + public int Name + { + get{ return _Name;} + set + { + _Name = value; + _flagName = true; + } + } + private int _Name; + private bool _flagName; + + /// + /// Returns false as Name should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeName() + { + return _flagName; + } + /// + /// Gets or Sets Class + /// + [DataMember(Name = "class", EmitDefaultValue = false)] + public string Class + { + get{ return _Class;} + set + { + _Class = value; + _flagClass = true; + } + } + private string _Class; + private bool _flagClass; + + /// + /// Returns false as Class should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeClass() + { + return _flagClass; + } + /// + /// 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() + { + var sb = new StringBuilder(); + sb.Append("class Model200Response {\n"); + sb.Append(" Name: ").Append(Name).Append("\n"); + sb.Append(" Class: ").Append(Class).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 Model200Response).AreEqual; + } + + /// + /// Returns true if Model200Response instances are equal + /// + /// Instance of Model200Response to be compared + /// Boolean + public bool Equals(Model200Response 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; + hashCode = hashCode * 59 + this.Name.GetHashCode(); + if (this.Class != null) + hashCode = hashCode * 59 + this.Class.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-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/ModelClient.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/ModelClient.cs new file mode 100644 index 00000000000..0bef108925e --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/ModelClient.cs @@ -0,0 +1,146 @@ +/* + * 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 +{ + /// + /// ModelClient + /// + [DataContract(Name = "_Client")] + public partial class ModelClient : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// _client. + public ModelClient(string _client = default(string)) + { + this.__Client = _client; + this.AdditionalProperties = new Dictionary(); + } + + /// + /// Gets or Sets _Client + /// + [DataMember(Name = "client", EmitDefaultValue = false)] + public string _Client + { + get{ return __Client;} + set + { + __Client = value; + _flag_Client = true; + } + } + private string __Client; + private bool _flag_Client; + + /// + /// Returns false as _Client should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerialize_Client() + { + return _flag_Client; + } + /// + /// 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() + { + var sb = new StringBuilder(); + sb.Append("class ModelClient {\n"); + sb.Append(" _Client: ").Append(_Client).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 ModelClient).AreEqual; + } + + /// + /// Returns true if ModelClient instances are equal + /// + /// Instance of ModelClient to be compared + /// Boolean + public bool Equals(ModelClient 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._Client != null) + hashCode = hashCode * 59 + this._Client.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-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Name.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Name.cs new file mode 100644 index 00000000000..02b318f8a35 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Name.cs @@ -0,0 +1,214 @@ +/* + * 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 +{ + /// + /// Model for testing model name same as property name + /// + [DataContract(Name = "Name")] + public partial class Name : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + [JsonConstructorAttribute] + protected Name() + { + this.AdditionalProperties = new Dictionary(); + } + /// + /// Initializes a new instance of the class. + /// + /// name (required). + /// property. + public Name(int name = default(int), string property = default(string)) + { + this.__Name = name; + this._Property = property; + this.AdditionalProperties = new Dictionary(); + } + + /// + /// Gets or Sets _Name + /// + [DataMember(Name = "name", IsRequired = true, EmitDefaultValue = false)] + public int _Name + { + get{ return __Name;} + set + { + __Name = value; + _flag_Name = true; + } + } + private int __Name; + private bool _flag_Name; + + /// + /// Returns false as _Name should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerialize_Name() + { + return _flag_Name; + } + /// + /// Gets or Sets SnakeCase + /// + [DataMember(Name = "snake_case", EmitDefaultValue = false)] + public int SnakeCase { get; private set; } + + /// + /// Returns false as SnakeCase should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeSnakeCase() + { + return false; + } + /// + /// Gets or Sets Property + /// + [DataMember(Name = "property", EmitDefaultValue = false)] + public string Property + { + get{ return _Property;} + set + { + _Property = value; + _flagProperty = true; + } + } + private string _Property; + private bool _flagProperty; + + /// + /// Returns false as Property should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeProperty() + { + return _flagProperty; + } + /// + /// Gets or Sets _123Number + /// + [DataMember(Name = "123Number", EmitDefaultValue = false)] + public int _123Number { get; private set; } + + /// + /// Returns false as _123Number should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerialize_123Number() + { + return false; + } + /// + /// 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() + { + var sb = new StringBuilder(); + sb.Append("class Name {\n"); + sb.Append(" _Name: ").Append(_Name).Append("\n"); + sb.Append(" SnakeCase: ").Append(SnakeCase).Append("\n"); + sb.Append(" Property: ").Append(Property).Append("\n"); + sb.Append(" _123Number: ").Append(_123Number).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 Name).AreEqual; + } + + /// + /// Returns true if Name instances are equal + /// + /// Instance of Name to be compared + /// Boolean + public bool Equals(Name 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; + hashCode = hashCode * 59 + this._Name.GetHashCode(); + hashCode = hashCode * 59 + this.SnakeCase.GetHashCode(); + if (this.Property != null) + hashCode = hashCode * 59 + this.Property.GetHashCode(); + hashCode = hashCode * 59 + this._123Number.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-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/NullableClass.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/NullableClass.cs new file mode 100644 index 00000000000..0df684cf534 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/NullableClass.cs @@ -0,0 +1,457 @@ +/* + * 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 +{ + /// + /// NullableClass + /// + [DataContract(Name = "NullableClass")] + public partial class NullableClass : Dictionary, IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// integerProp. + /// numberProp. + /// booleanProp. + /// stringProp. + /// dateProp. + /// datetimeProp. + /// arrayNullableProp. + /// arrayAndItemsNullableProp. + /// arrayItemsNullable. + /// objectNullableProp. + /// 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() + { + this._IntegerProp = integerProp; + this._NumberProp = numberProp; + this._BooleanProp = booleanProp; + this._StringProp = stringProp; + this._DateProp = dateProp; + this._DatetimeProp = datetimeProp; + this._ArrayNullableProp = arrayNullableProp; + this._ArrayAndItemsNullableProp = arrayAndItemsNullableProp; + this._ArrayItemsNullable = arrayItemsNullable; + this._ObjectNullableProp = objectNullableProp; + this._ObjectAndItemsNullableProp = objectAndItemsNullableProp; + this._ObjectItemsNullable = objectItemsNullable; + } + + /// + /// Gets or Sets IntegerProp + /// + [DataMember(Name = "integer_prop", EmitDefaultValue = true)] + public int? IntegerProp + { + get{ return _IntegerProp;} + set + { + _IntegerProp = value; + _flagIntegerProp = true; + } + } + private int? _IntegerProp; + private bool _flagIntegerProp; + + /// + /// Returns false as IntegerProp should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeIntegerProp() + { + return _flagIntegerProp; + } + /// + /// Gets or Sets NumberProp + /// + [DataMember(Name = "number_prop", EmitDefaultValue = true)] + public decimal? NumberProp + { + get{ return _NumberProp;} + set + { + _NumberProp = value; + _flagNumberProp = true; + } + } + private decimal? _NumberProp; + private bool _flagNumberProp; + + /// + /// Returns false as NumberProp should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeNumberProp() + { + return _flagNumberProp; + } + /// + /// Gets or Sets BooleanProp + /// + [DataMember(Name = "boolean_prop", EmitDefaultValue = true)] + public bool? BooleanProp + { + get{ return _BooleanProp;} + set + { + _BooleanProp = value; + _flagBooleanProp = true; + } + } + private bool? _BooleanProp; + private bool _flagBooleanProp; + + /// + /// Returns false as BooleanProp should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeBooleanProp() + { + return _flagBooleanProp; + } + /// + /// Gets or Sets StringProp + /// + [DataMember(Name = "string_prop", EmitDefaultValue = true)] + public string StringProp + { + get{ return _StringProp;} + set + { + _StringProp = value; + _flagStringProp = true; + } + } + private string _StringProp; + private bool _flagStringProp; + + /// + /// Returns false as StringProp should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeStringProp() + { + return _flagStringProp; + } + /// + /// Gets or Sets DateProp + /// + [JsonConverter(typeof(OpenAPIDateConverter))] + [DataMember(Name = "date_prop", EmitDefaultValue = true)] + public DateTime? DateProp + { + get{ return _DateProp;} + set + { + _DateProp = value; + _flagDateProp = true; + } + } + private DateTime? _DateProp; + private bool _flagDateProp; + + /// + /// Returns false as DateProp should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeDateProp() + { + return _flagDateProp; + } + /// + /// Gets or Sets DatetimeProp + /// + [DataMember(Name = "datetime_prop", EmitDefaultValue = true)] + public DateTime? DatetimeProp + { + get{ return _DatetimeProp;} + set + { + _DatetimeProp = value; + _flagDatetimeProp = true; + } + } + private DateTime? _DatetimeProp; + private bool _flagDatetimeProp; + + /// + /// Returns false as DatetimeProp should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeDatetimeProp() + { + return _flagDatetimeProp; + } + /// + /// Gets or Sets ArrayNullableProp + /// + [DataMember(Name = "array_nullable_prop", EmitDefaultValue = true)] + public List ArrayNullableProp + { + get{ return _ArrayNullableProp;} + set + { + _ArrayNullableProp = value; + _flagArrayNullableProp = true; + } + } + private List _ArrayNullableProp; + private bool _flagArrayNullableProp; + + /// + /// Returns false as ArrayNullableProp should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeArrayNullableProp() + { + return _flagArrayNullableProp; + } + /// + /// Gets or Sets ArrayAndItemsNullableProp + /// + [DataMember(Name = "array_and_items_nullable_prop", EmitDefaultValue = true)] + public List ArrayAndItemsNullableProp + { + get{ return _ArrayAndItemsNullableProp;} + set + { + _ArrayAndItemsNullableProp = value; + _flagArrayAndItemsNullableProp = true; + } + } + private List _ArrayAndItemsNullableProp; + private bool _flagArrayAndItemsNullableProp; + + /// + /// Returns false as ArrayAndItemsNullableProp should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeArrayAndItemsNullableProp() + { + return _flagArrayAndItemsNullableProp; + } + /// + /// Gets or Sets ArrayItemsNullable + /// + [DataMember(Name = "array_items_nullable", EmitDefaultValue = false)] + public List ArrayItemsNullable + { + get{ return _ArrayItemsNullable;} + set + { + _ArrayItemsNullable = value; + _flagArrayItemsNullable = true; + } + } + private List _ArrayItemsNullable; + private bool _flagArrayItemsNullable; + + /// + /// Returns false as ArrayItemsNullable should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeArrayItemsNullable() + { + return _flagArrayItemsNullable; + } + /// + /// Gets or Sets ObjectNullableProp + /// + [DataMember(Name = "object_nullable_prop", EmitDefaultValue = true)] + public Dictionary ObjectNullableProp + { + get{ return _ObjectNullableProp;} + set + { + _ObjectNullableProp = value; + _flagObjectNullableProp = true; + } + } + private Dictionary _ObjectNullableProp; + private bool _flagObjectNullableProp; + + /// + /// Returns false as ObjectNullableProp should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeObjectNullableProp() + { + return _flagObjectNullableProp; + } + /// + /// Gets or Sets ObjectAndItemsNullableProp + /// + [DataMember(Name = "object_and_items_nullable_prop", EmitDefaultValue = true)] + public Dictionary ObjectAndItemsNullableProp + { + get{ return _ObjectAndItemsNullableProp;} + set + { + _ObjectAndItemsNullableProp = value; + _flagObjectAndItemsNullableProp = true; + } + } + private Dictionary _ObjectAndItemsNullableProp; + private bool _flagObjectAndItemsNullableProp; + + /// + /// Returns false as ObjectAndItemsNullableProp should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeObjectAndItemsNullableProp() + { + return _flagObjectAndItemsNullableProp; + } + /// + /// Gets or Sets ObjectItemsNullable + /// + [DataMember(Name = "object_items_nullable", EmitDefaultValue = false)] + public Dictionary ObjectItemsNullable + { + get{ return _ObjectItemsNullable;} + set + { + _ObjectItemsNullable = value; + _flagObjectItemsNullable = true; + } + } + private Dictionary _ObjectItemsNullable; + private bool _flagObjectItemsNullable; + + /// + /// Returns false as ObjectItemsNullable should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeObjectItemsNullable() + { + return _flagObjectItemsNullable; + } + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + var 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"); + sb.Append(" StringProp: ").Append(StringProp).Append("\n"); + sb.Append(" DateProp: ").Append(DateProp).Append("\n"); + sb.Append(" DatetimeProp: ").Append(DatetimeProp).Append("\n"); + sb.Append(" ArrayNullableProp: ").Append(ArrayNullableProp).Append("\n"); + sb.Append(" ArrayAndItemsNullableProp: ").Append(ArrayAndItemsNullableProp).Append("\n"); + sb.Append(" ArrayItemsNullable: ").Append(ArrayItemsNullable).Append("\n"); + sb.Append(" ObjectNullableProp: ").Append(ObjectNullableProp).Append("\n"); + sb.Append(" ObjectAndItemsNullableProp: ").Append(ObjectAndItemsNullableProp).Append("\n"); + sb.Append(" ObjectItemsNullable: ").Append(ObjectItemsNullable).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public 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 NullableClass).AreEqual; + } + + /// + /// Returns true if NullableClass instances are equal + /// + /// Instance of NullableClass to be compared + /// Boolean + public bool Equals(NullableClass 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 = base.GetHashCode(); + if (this.IntegerProp != null) + hashCode = hashCode * 59 + this.IntegerProp.GetHashCode(); + if (this.NumberProp != null) + hashCode = hashCode * 59 + this.NumberProp.GetHashCode(); + if (this.BooleanProp != null) + hashCode = hashCode * 59 + this.BooleanProp.GetHashCode(); + if (this.StringProp != null) + hashCode = hashCode * 59 + this.StringProp.GetHashCode(); + if (this.DateProp != null) + hashCode = hashCode * 59 + this.DateProp.GetHashCode(); + if (this.DatetimeProp != null) + hashCode = hashCode * 59 + this.DatetimeProp.GetHashCode(); + if (this.ArrayNullableProp != null) + hashCode = hashCode * 59 + this.ArrayNullableProp.GetHashCode(); + if (this.ArrayAndItemsNullableProp != null) + hashCode = hashCode * 59 + this.ArrayAndItemsNullableProp.GetHashCode(); + if (this.ArrayItemsNullable != null) + hashCode = hashCode * 59 + this.ArrayItemsNullable.GetHashCode(); + if (this.ObjectNullableProp != null) + hashCode = hashCode * 59 + this.ObjectNullableProp.GetHashCode(); + if (this.ObjectAndItemsNullableProp != null) + hashCode = hashCode * 59 + this.ObjectAndItemsNullableProp.GetHashCode(); + if (this.ObjectItemsNullable != null) + hashCode = hashCode * 59 + this.ObjectItemsNullable.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-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/NullableShape.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/NullableShape.cs new file mode 100644 index 00000000000..20be30e5b89 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/NullableShape.cs @@ -0,0 +1,316 @@ +/* + * 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 JsonSubTypes; +using System.ComponentModel.DataAnnotations; +using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; +using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using System.Reflection; + +namespace Org.OpenAPITools.Model +{ + /// + /// The value may be a shape or the 'null' value. The 'nullable' attribute was introduced in OAS schema >= 3.0 and has been deprecated in OAS schema >= 3.1. + /// + [JsonConverter(typeof(NullableShapeJsonConverter))] + [DataContract(Name = "NullableShape")] + public partial class NullableShape : AbstractOpenAPISchema, IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + public NullableShape() + { + this.IsNullable = true; + this.SchemaType= "oneOf"; + } + + /// + /// Initializes a new instance of the class + /// with the class + /// + /// An instance of Quadrilateral. + public NullableShape(Quadrilateral actualInstance) + { + this.IsNullable = true; + this.SchemaType= "oneOf"; + this.ActualInstance = actualInstance; + } + + /// + /// Initializes a new instance of the class + /// with the class + /// + /// An instance of Triangle. + public NullableShape(Triangle actualInstance) + { + this.IsNullable = true; + this.SchemaType= "oneOf"; + this.ActualInstance = actualInstance; + } + + + private Object _actualInstance; + + /// + /// Gets or Sets ActualInstance + /// + public override Object ActualInstance + { + get + { + return _actualInstance; + } + set + { + if (value.GetType() == typeof(Quadrilateral)) + { + this._actualInstance = value; + } + else if (value.GetType() == typeof(Triangle)) + { + this._actualInstance = value; + } + else + { + throw new ArgumentException("Invalid instance found. Must be the following types: Quadrilateral, Triangle"); + } + } + } + + /// + /// Get the actual instance of `Quadrilateral`. If the actual instanct is not `Quadrilateral`, + /// the InvalidClassException will be thrown + /// + /// An instance of Quadrilateral + public Quadrilateral GetQuadrilateral() + { + return (Quadrilateral)this.ActualInstance; + } + + /// + /// Get the actual instance of `Triangle`. If the actual instanct is not `Triangle`, + /// the InvalidClassException will be thrown + /// + /// An instance of Triangle + public Triangle GetTriangle() + { + return (Triangle)this.ActualInstance; + } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + var sb = new StringBuilder(); + sb.Append("class NullableShape {\n"); + sb.Append(" ActualInstance: ").Append(this.ActualInstance).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public override string ToJson() + { + return JsonConvert.SerializeObject(this.ActualInstance, NullableShape.SerializerSettings); + } + + /// + /// Converts the JSON string into an instance of NullableShape + /// + /// JSON string + /// An instance of NullableShape + public static NullableShape FromJson(string jsonString) + { + NullableShape newNullableShape = null; + + if (jsonString == null) + { + return newNullableShape; + } + + string discriminatorValue = JObject.Parse(jsonString)["shapeType"].ToString(); + switch (discriminatorValue) + { + case "Quadrilateral": + newNullableShape = new NullableShape(JsonConvert.DeserializeObject(jsonString, NullableShape.AdditionalPropertiesSerializerSettings)); + return newNullableShape; + case "Triangle": + newNullableShape = new NullableShape(JsonConvert.DeserializeObject(jsonString, NullableShape.AdditionalPropertiesSerializerSettings)); + return newNullableShape; + default: + System.Diagnostics.Debug.WriteLine(string.Format("Failed to lookup discriminator value `{0}` for NullableShape. Possible values: Quadrilateral Triangle", discriminatorValue)); + break; + } + + int match = 0; + List matchedTypes = new List(); + + try + { + // if it does not contains "AdditionalProperties", use SerializerSettings to deserialize + if (typeof(Quadrilateral).GetProperty("AdditionalProperties") == null) + { + newNullableShape = new NullableShape(JsonConvert.DeserializeObject(jsonString, NullableShape.SerializerSettings)); + } + else + { + newNullableShape = new NullableShape(JsonConvert.DeserializeObject(jsonString, NullableShape.AdditionalPropertiesSerializerSettings)); + } + matchedTypes.Add("Quadrilateral"); + match++; + } + catch (Exception exception) + { + // deserialization failed, try the next one + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into Quadrilateral: {1}", jsonString, exception.ToString())); + } + + try + { + // if it does not contains "AdditionalProperties", use SerializerSettings to deserialize + if (typeof(Triangle).GetProperty("AdditionalProperties") == null) + { + newNullableShape = new NullableShape(JsonConvert.DeserializeObject(jsonString, NullableShape.SerializerSettings)); + } + else + { + newNullableShape = new NullableShape(JsonConvert.DeserializeObject(jsonString, NullableShape.AdditionalPropertiesSerializerSettings)); + } + matchedTypes.Add("Triangle"); + match++; + } + catch (Exception exception) + { + // deserialization failed, try the next one + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into Triangle: {1}", jsonString, exception.ToString())); + } + + if (match == 0) + { + throw new InvalidDataException("The JSON string `" + jsonString + "` cannot be deserialized into any schema defined."); + } + else if (match > 1) + { + throw new InvalidDataException("The JSON string `" + jsonString + "` incorrectly matches more than one schema (should be exactly one match): " + matchedTypes); + } + + // deserialization is considered successful at this point if no exception has been thrown. + return newNullableShape; + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input as NullableShape).AreEqual; + } + + /// + /// Returns true if NullableShape instances are equal + /// + /// Instance of NullableShape to be compared + /// Boolean + public bool Equals(NullableShape 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.ActualInstance != null) + hashCode = hashCode * 59 + this.ActualInstance.GetHashCode(); + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// Custom JSON converter for NullableShape + /// + public class NullableShapeJsonConverter : JsonConverter + { + /// + /// To write the JSON string + /// + /// JSON writer + /// Object to be converted into a JSON string + /// JSON Serializer + public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) + { + writer.WriteRawValue((string)(typeof(NullableShape).GetMethod("ToJson").Invoke(value, null))); + } + + /// + /// To convert a JSON string into an object + /// + /// JSON reader + /// Object type + /// Existing value + /// JSON Serializer + /// The object converted from the JSON string + public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) + { + if(reader.TokenType != JsonToken.Null) + { + return NullableShape.FromJson(JObject.Load(reader).ToString(Formatting.None)); + } + return null; + } + + /// + /// Check if the object can be converted + /// + /// Object type + /// True if the object can be converted + public override bool CanConvert(Type objectType) + { + return false; + } + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/NumberOnly.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/NumberOnly.cs new file mode 100644 index 00000000000..9209ffb0261 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/NumberOnly.cs @@ -0,0 +1,145 @@ +/* + * 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 +{ + /// + /// NumberOnly + /// + [DataContract(Name = "NumberOnly")] + public partial class NumberOnly : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// justNumber. + public NumberOnly(decimal justNumber = default(decimal)) + { + this._JustNumber = justNumber; + this.AdditionalProperties = new Dictionary(); + } + + /// + /// Gets or Sets JustNumber + /// + [DataMember(Name = "JustNumber", EmitDefaultValue = false)] + public decimal JustNumber + { + get{ return _JustNumber;} + set + { + _JustNumber = value; + _flagJustNumber = true; + } + } + private decimal _JustNumber; + private bool _flagJustNumber; + + /// + /// Returns false as JustNumber should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeJustNumber() + { + return _flagJustNumber; + } + /// + /// 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() + { + var sb = new StringBuilder(); + sb.Append("class NumberOnly {\n"); + sb.Append(" JustNumber: ").Append(JustNumber).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 NumberOnly).AreEqual; + } + + /// + /// Returns true if NumberOnly instances are equal + /// + /// Instance of NumberOnly to be compared + /// Boolean + public bool Equals(NumberOnly 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; + hashCode = hashCode * 59 + this.JustNumber.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-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Order.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Order.cs new file mode 100644 index 00000000000..57d93427399 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Order.cs @@ -0,0 +1,316 @@ +/* + * 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 +{ + /// + /// Order + /// + [DataContract(Name = "Order")] + public partial class Order : IEquatable, IValidatableObject + { + /// + /// Order Status + /// + /// Order Status + [JsonConverter(typeof(StringEnumConverter))] + public enum StatusEnum + { + /// + /// Enum Placed for value: placed + /// + [EnumMember(Value = "placed")] + Placed = 1, + + /// + /// Enum Approved for value: approved + /// + [EnumMember(Value = "approved")] + Approved = 2, + + /// + /// Enum Delivered for value: delivered + /// + [EnumMember(Value = "delivered")] + Delivered = 3 + + } + + + /// + /// Order Status + /// + /// Order Status + + [DataMember(Name = "status", EmitDefaultValue = false)] + public StatusEnum? Status + { + get{ return _Status;} + set + { + _Status = value; + _flagStatus = true; + } + } + private StatusEnum? _Status; + private bool _flagStatus; + + /// + /// Returns false as Status should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeStatus() + { + return _flagStatus; + } + /// + /// Initializes a new instance of the class. + /// + /// id. + /// petId. + /// quantity. + /// shipDate. + /// Order Status. + /// complete (default to false). + public Order(long id = default(long), long petId = default(long), int quantity = default(int), DateTime shipDate = default(DateTime), StatusEnum? status = default(StatusEnum?), bool complete = false) + { + this._Id = id; + this._PetId = petId; + this._Quantity = quantity; + this._ShipDate = shipDate; + this._Status = status; + this.Complete = complete; + this.AdditionalProperties = new Dictionary(); + } + + /// + /// Gets or Sets Id + /// + [DataMember(Name = "id", EmitDefaultValue = false)] + public long Id + { + get{ return _Id;} + set + { + _Id = value; + _flagId = true; + } + } + private long _Id; + private bool _flagId; + + /// + /// Returns false as Id should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeId() + { + return _flagId; + } + /// + /// Gets or Sets PetId + /// + [DataMember(Name = "petId", EmitDefaultValue = false)] + public long PetId + { + get{ return _PetId;} + set + { + _PetId = value; + _flagPetId = true; + } + } + private long _PetId; + private bool _flagPetId; + + /// + /// Returns false as PetId should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializePetId() + { + return _flagPetId; + } + /// + /// Gets or Sets Quantity + /// + [DataMember(Name = "quantity", EmitDefaultValue = false)] + public int Quantity + { + get{ return _Quantity;} + set + { + _Quantity = value; + _flagQuantity = true; + } + } + private int _Quantity; + private bool _flagQuantity; + + /// + /// Returns false as Quantity should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeQuantity() + { + return _flagQuantity; + } + /// + /// Gets or Sets ShipDate + /// + [DataMember(Name = "shipDate", EmitDefaultValue = false)] + public DateTime ShipDate + { + get{ return _ShipDate;} + set + { + _ShipDate = value; + _flagShipDate = true; + } + } + private DateTime _ShipDate; + private bool _flagShipDate; + + /// + /// Returns false as ShipDate should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeShipDate() + { + return _flagShipDate; + } + /// + /// Gets or Sets Complete + /// + [DataMember(Name = "complete", EmitDefaultValue = true)] + public bool Complete + { + get{ return _Complete;} + set + { + _Complete = value; + _flagComplete = true; + } + } + private bool _Complete; + private bool _flagComplete; + + /// + /// Returns false as Complete should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeComplete() + { + return _flagComplete; + } + /// + /// 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() + { + var sb = new StringBuilder(); + sb.Append("class Order {\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(); + } + + /// + /// 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 Order).AreEqual; + } + + /// + /// Returns true if Order instances are equal + /// + /// Instance of Order to be compared + /// Boolean + public bool Equals(Order 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; + hashCode = hashCode * 59 + this.Id.GetHashCode(); + hashCode = hashCode * 59 + this.PetId.GetHashCode(); + hashCode = hashCode * 59 + this.Quantity.GetHashCode(); + if (this.ShipDate != null) + hashCode = hashCode * 59 + this.ShipDate.GetHashCode(); + hashCode = hashCode * 59 + this.Status.GetHashCode(); + hashCode = hashCode * 59 + this.Complete.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-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/OuterComposite.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/OuterComposite.cs new file mode 100644 index 00000000000..9fb0d68d1a8 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/OuterComposite.cs @@ -0,0 +1,202 @@ +/* + * 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 +{ + /// + /// OuterComposite + /// + [DataContract(Name = "OuterComposite")] + public partial class OuterComposite : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// myNumber. + /// myString. + /// myBoolean. + public OuterComposite(decimal myNumber = default(decimal), string myString = default(string), bool myBoolean = default(bool)) + { + this._MyNumber = myNumber; + this._MyString = myString; + this._MyBoolean = myBoolean; + this.AdditionalProperties = new Dictionary(); + } + + /// + /// Gets or Sets MyNumber + /// + [DataMember(Name = "my_number", EmitDefaultValue = false)] + public decimal MyNumber + { + get{ return _MyNumber;} + set + { + _MyNumber = value; + _flagMyNumber = true; + } + } + private decimal _MyNumber; + private bool _flagMyNumber; + + /// + /// Returns false as MyNumber should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeMyNumber() + { + return _flagMyNumber; + } + /// + /// Gets or Sets MyString + /// + [DataMember(Name = "my_string", EmitDefaultValue = false)] + public string MyString + { + get{ return _MyString;} + set + { + _MyString = value; + _flagMyString = true; + } + } + private string _MyString; + private bool _flagMyString; + + /// + /// Returns false as MyString should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeMyString() + { + return _flagMyString; + } + /// + /// Gets or Sets MyBoolean + /// + [DataMember(Name = "my_boolean", EmitDefaultValue = true)] + public bool MyBoolean + { + get{ return _MyBoolean;} + set + { + _MyBoolean = value; + _flagMyBoolean = true; + } + } + private bool _MyBoolean; + private bool _flagMyBoolean; + + /// + /// Returns false as MyBoolean should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeMyBoolean() + { + return _flagMyBoolean; + } + /// + /// 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() + { + var sb = new StringBuilder(); + sb.Append("class OuterComposite {\n"); + sb.Append(" MyNumber: ").Append(MyNumber).Append("\n"); + sb.Append(" MyString: ").Append(MyString).Append("\n"); + sb.Append(" MyBoolean: ").Append(MyBoolean).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 OuterComposite).AreEqual; + } + + /// + /// Returns true if OuterComposite instances are equal + /// + /// Instance of OuterComposite to be compared + /// Boolean + public bool Equals(OuterComposite 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; + hashCode = hashCode * 59 + this.MyNumber.GetHashCode(); + if (this.MyString != null) + hashCode = hashCode * 59 + this.MyString.GetHashCode(); + hashCode = hashCode * 59 + this.MyBoolean.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-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/OuterEnum.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/OuterEnum.cs new file mode 100644 index 00000000000..2aa496a2e07 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/OuterEnum.cs @@ -0,0 +1,55 @@ +/* + * 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 +{ + /// + /// Defines OuterEnum + /// + [JsonConverter(typeof(StringEnumConverter))] + public enum OuterEnum + { + /// + /// Enum Placed for value: placed + /// + [EnumMember(Value = "placed")] + Placed = 1, + + /// + /// Enum Approved for value: approved + /// + [EnumMember(Value = "approved")] + Approved = 2, + + /// + /// Enum Delivered for value: delivered + /// + [EnumMember(Value = "delivered")] + Delivered = 3 + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/OuterEnumDefaultValue.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/OuterEnumDefaultValue.cs new file mode 100644 index 00000000000..dd79c7010d6 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/OuterEnumDefaultValue.cs @@ -0,0 +1,55 @@ +/* + * 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 +{ + /// + /// Defines OuterEnumDefaultValue + /// + [JsonConverter(typeof(StringEnumConverter))] + public enum OuterEnumDefaultValue + { + /// + /// Enum Placed for value: placed + /// + [EnumMember(Value = "placed")] + Placed = 1, + + /// + /// Enum Approved for value: approved + /// + [EnumMember(Value = "approved")] + Approved = 2, + + /// + /// Enum Delivered for value: delivered + /// + [EnumMember(Value = "delivered")] + Delivered = 3 + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/OuterEnumInteger.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/OuterEnumInteger.cs new file mode 100644 index 00000000000..44dc91c700a --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/OuterEnumInteger.cs @@ -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 + * 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 +{ + /// + /// Defines OuterEnumInteger + /// + public enum OuterEnumInteger + { + /// + /// Enum NUMBER_0 for value: 0 + /// + NUMBER_0 = 0, + + /// + /// Enum NUMBER_1 for value: 1 + /// + NUMBER_1 = 1, + + /// + /// Enum NUMBER_2 for value: 2 + /// + NUMBER_2 = 2 + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/OuterEnumIntegerDefaultValue.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/OuterEnumIntegerDefaultValue.cs new file mode 100644 index 00000000000..b927507cf97 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/OuterEnumIntegerDefaultValue.cs @@ -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 + * 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 +{ + /// + /// Defines OuterEnumIntegerDefaultValue + /// + public enum OuterEnumIntegerDefaultValue + { + /// + /// Enum NUMBER_0 for value: 0 + /// + NUMBER_0 = 0, + + /// + /// Enum NUMBER_1 for value: 1 + /// + NUMBER_1 = 1, + + /// + /// Enum NUMBER_2 for value: 2 + /// + NUMBER_2 = 2 + + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/ParentPet.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/ParentPet.cs new file mode 100644 index 00000000000..a205b59b6d0 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/ParentPet.cs @@ -0,0 +1,141 @@ +/* + * 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 JsonSubTypes; +using System.ComponentModel.DataAnnotations; +using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; +using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; + +namespace Org.OpenAPITools.Model +{ + /// + /// ParentPet + /// + [DataContract(Name = "ParentPet")] + [JsonConverter(typeof(JsonSubtypes), "PetType")] + [JsonSubtypes.KnownSubType(typeof(ChildCat), "ChildCat")] + public partial class ParentPet : GrandparentAnimal, IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + [JsonConstructorAttribute] + protected ParentPet() + { + this.AdditionalProperties = new Dictionary(); + } + /// + /// Initializes a new instance of the class. + /// + /// petType (required) (default to "ParentPet"). + public ParentPet(string petType = "ParentPet") : base(petType) + { + this.AdditionalProperties = new Dictionary(); + } + + /// + /// 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() + { + var sb = new StringBuilder(); + sb.Append("class ParentPet {\n"); + sb.Append(" ").Append(base.ToString().Replace("\n", "\n ")).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 override 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 ParentPet).AreEqual; + } + + /// + /// Returns true if ParentPet instances are equal + /// + /// Instance of ParentPet to be compared + /// Boolean + public bool Equals(ParentPet 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 = base.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) + { + return this.BaseValidate(validationContext); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + protected IEnumerable BaseValidate(ValidationContext validationContext) + { + foreach(var x in BaseValidate(validationContext)) yield return x; + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Pet.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Pet.cs new file mode 100644 index 00000000000..d9b77cf3b8f --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Pet.cs @@ -0,0 +1,329 @@ +/* + * 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 +{ + /// + /// Pet + /// + [DataContract(Name = "Pet")] + public partial class Pet : IEquatable, IValidatableObject + { + /// + /// pet status in the store + /// + /// pet status in the store + [JsonConverter(typeof(StringEnumConverter))] + public enum StatusEnum + { + /// + /// Enum Available for value: available + /// + [EnumMember(Value = "available")] + Available = 1, + + /// + /// Enum Pending for value: pending + /// + [EnumMember(Value = "pending")] + Pending = 2, + + /// + /// Enum Sold for value: sold + /// + [EnumMember(Value = "sold")] + Sold = 3 + + } + + + /// + /// pet status in the store + /// + /// pet status in the store + + [DataMember(Name = "status", EmitDefaultValue = false)] + public StatusEnum? Status + { + get{ return _Status;} + set + { + _Status = value; + _flagStatus = true; + } + } + private StatusEnum? _Status; + private bool _flagStatus; + + /// + /// Returns false as Status should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeStatus() + { + return _flagStatus; + } + /// + /// Initializes a new instance of the class. + /// + [JsonConstructorAttribute] + protected Pet() + { + this.AdditionalProperties = new Dictionary(); + } + /// + /// Initializes a new instance of the class. + /// + /// id. + /// category. + /// name (required). + /// photoUrls (required). + /// tags. + /// pet status in the store. + public Pet(long id = default(long), Category category = default(Category), string name = default(string), List photoUrls = default(List), List tags = default(List), StatusEnum? status = default(StatusEnum?)) + { + // to ensure "name" is required (not null) + this._Name = name ?? throw new ArgumentNullException("name is a required property for Pet and cannot be null"); + // to ensure "photoUrls" is required (not null) + this._PhotoUrls = photoUrls ?? throw new ArgumentNullException("photoUrls is a required property for Pet and cannot be null"); + this._Id = id; + this._Category = category; + this._Tags = tags; + this._Status = status; + this.AdditionalProperties = new Dictionary(); + } + + /// + /// Gets or Sets Id + /// + [DataMember(Name = "id", EmitDefaultValue = false)] + public long Id + { + get{ return _Id;} + set + { + _Id = value; + _flagId = true; + } + } + private long _Id; + private bool _flagId; + + /// + /// Returns false as Id should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeId() + { + return _flagId; + } + /// + /// Gets or Sets Category + /// + [DataMember(Name = "category", EmitDefaultValue = false)] + public Category Category + { + get{ return _Category;} + set + { + _Category = value; + _flagCategory = true; + } + } + private Category _Category; + private bool _flagCategory; + + /// + /// Returns false as Category should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeCategory() + { + return _flagCategory; + } + /// + /// Gets or Sets Name + /// + [DataMember(Name = "name", IsRequired = true, EmitDefaultValue = false)] + public string Name + { + get{ return _Name;} + set + { + _Name = value; + _flagName = true; + } + } + private string _Name; + private bool _flagName; + + /// + /// Returns false as Name should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeName() + { + return _flagName; + } + /// + /// Gets or Sets PhotoUrls + /// + [DataMember(Name = "photoUrls", IsRequired = true, EmitDefaultValue = false)] + public List PhotoUrls + { + get{ return _PhotoUrls;} + set + { + _PhotoUrls = value; + _flagPhotoUrls = true; + } + } + private List _PhotoUrls; + private bool _flagPhotoUrls; + + /// + /// Returns false as PhotoUrls should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializePhotoUrls() + { + return _flagPhotoUrls; + } + /// + /// Gets or Sets Tags + /// + [DataMember(Name = "tags", EmitDefaultValue = false)] + public List Tags + { + get{ return _Tags;} + set + { + _Tags = value; + _flagTags = true; + } + } + private List _Tags; + private bool _flagTags; + + /// + /// Returns false as Tags should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeTags() + { + return _flagTags; + } + /// + /// 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() + { + var sb = new StringBuilder(); + sb.Append("class Pet {\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" Category: ").Append(Category).Append("\n"); + sb.Append(" Name: ").Append(Name).Append("\n"); + sb.Append(" PhotoUrls: ").Append(PhotoUrls).Append("\n"); + sb.Append(" Tags: ").Append(Tags).Append("\n"); + sb.Append(" Status: ").Append(Status).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 Pet).AreEqual; + } + + /// + /// Returns true if Pet instances are equal + /// + /// Instance of Pet to be compared + /// Boolean + public bool Equals(Pet 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; + hashCode = hashCode * 59 + this.Id.GetHashCode(); + if (this.Category != null) + hashCode = hashCode * 59 + this.Category.GetHashCode(); + if (this.Name != null) + hashCode = hashCode * 59 + this.Name.GetHashCode(); + if (this.PhotoUrls != null) + hashCode = hashCode * 59 + this.PhotoUrls.GetHashCode(); + if (this.Tags != null) + hashCode = hashCode * 59 + this.Tags.GetHashCode(); + hashCode = hashCode * 59 + this.Status.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-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Pig.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Pig.cs new file mode 100644 index 00000000000..967d2139a0a --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Pig.cs @@ -0,0 +1,307 @@ +/* + * 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 JsonSubTypes; +using System.ComponentModel.DataAnnotations; +using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; +using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using System.Reflection; + +namespace Org.OpenAPITools.Model +{ + /// + /// Pig + /// + [JsonConverter(typeof(PigJsonConverter))] + [DataContract(Name = "Pig")] + public partial class Pig : AbstractOpenAPISchema, IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class + /// with the class + /// + /// An instance of BasquePig. + public Pig(BasquePig actualInstance) + { + this.IsNullable = false; + this.SchemaType= "oneOf"; + this.ActualInstance = actualInstance ?? throw new ArgumentException("Invalid instance found. Must not be null."); + } + + /// + /// Initializes a new instance of the class + /// with the class + /// + /// An instance of DanishPig. + public Pig(DanishPig actualInstance) + { + this.IsNullable = false; + this.SchemaType= "oneOf"; + this.ActualInstance = actualInstance ?? throw new ArgumentException("Invalid instance found. Must not be null."); + } + + + private Object _actualInstance; + + /// + /// Gets or Sets ActualInstance + /// + public override Object ActualInstance + { + get + { + return _actualInstance; + } + set + { + if (value.GetType() == typeof(BasquePig)) + { + this._actualInstance = value; + } + else if (value.GetType() == typeof(DanishPig)) + { + this._actualInstance = value; + } + else + { + throw new ArgumentException("Invalid instance found. Must be the following types: BasquePig, DanishPig"); + } + } + } + + /// + /// Get the actual instance of `BasquePig`. If the actual instanct is not `BasquePig`, + /// the InvalidClassException will be thrown + /// + /// An instance of BasquePig + public BasquePig GetBasquePig() + { + return (BasquePig)this.ActualInstance; + } + + /// + /// Get the actual instance of `DanishPig`. If the actual instanct is not `DanishPig`, + /// the InvalidClassException will be thrown + /// + /// An instance of DanishPig + public DanishPig GetDanishPig() + { + return (DanishPig)this.ActualInstance; + } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + var sb = new StringBuilder(); + sb.Append("class Pig {\n"); + sb.Append(" ActualInstance: ").Append(this.ActualInstance).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public override string ToJson() + { + return JsonConvert.SerializeObject(this.ActualInstance, Pig.SerializerSettings); + } + + /// + /// Converts the JSON string into an instance of Pig + /// + /// JSON string + /// An instance of Pig + public static Pig FromJson(string jsonString) + { + Pig newPig = null; + + if (jsonString == null) + { + return newPig; + } + + string discriminatorValue = JObject.Parse(jsonString)["className"].ToString(); + switch (discriminatorValue) + { + case "BasquePig": + newPig = new Pig(JsonConvert.DeserializeObject(jsonString, Pig.AdditionalPropertiesSerializerSettings)); + return newPig; + case "DanishPig": + newPig = new Pig(JsonConvert.DeserializeObject(jsonString, Pig.AdditionalPropertiesSerializerSettings)); + return newPig; + default: + System.Diagnostics.Debug.WriteLine(string.Format("Failed to lookup discriminator value `{0}` for Pig. Possible values: BasquePig DanishPig", discriminatorValue)); + break; + } + + int match = 0; + List matchedTypes = new List(); + + try + { + // if it does not contains "AdditionalProperties", use SerializerSettings to deserialize + if (typeof(BasquePig).GetProperty("AdditionalProperties") == null) + { + newPig = new Pig(JsonConvert.DeserializeObject(jsonString, Pig.SerializerSettings)); + } + else + { + newPig = new Pig(JsonConvert.DeserializeObject(jsonString, Pig.AdditionalPropertiesSerializerSettings)); + } + matchedTypes.Add("BasquePig"); + match++; + } + catch (Exception exception) + { + // deserialization failed, try the next one + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into BasquePig: {1}", jsonString, exception.ToString())); + } + + try + { + // if it does not contains "AdditionalProperties", use SerializerSettings to deserialize + if (typeof(DanishPig).GetProperty("AdditionalProperties") == null) + { + newPig = new Pig(JsonConvert.DeserializeObject(jsonString, Pig.SerializerSettings)); + } + else + { + newPig = new Pig(JsonConvert.DeserializeObject(jsonString, Pig.AdditionalPropertiesSerializerSettings)); + } + matchedTypes.Add("DanishPig"); + match++; + } + catch (Exception exception) + { + // deserialization failed, try the next one + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into DanishPig: {1}", jsonString, exception.ToString())); + } + + if (match == 0) + { + throw new InvalidDataException("The JSON string `" + jsonString + "` cannot be deserialized into any schema defined."); + } + else if (match > 1) + { + throw new InvalidDataException("The JSON string `" + jsonString + "` incorrectly matches more than one schema (should be exactly one match): " + matchedTypes); + } + + // deserialization is considered successful at this point if no exception has been thrown. + return newPig; + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input as Pig).AreEqual; + } + + /// + /// Returns true if Pig instances are equal + /// + /// Instance of Pig to be compared + /// Boolean + public bool Equals(Pig 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.ActualInstance != null) + hashCode = hashCode * 59 + this.ActualInstance.GetHashCode(); + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// Custom JSON converter for Pig + /// + public class PigJsonConverter : JsonConverter + { + /// + /// To write the JSON string + /// + /// JSON writer + /// Object to be converted into a JSON string + /// JSON Serializer + public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) + { + writer.WriteRawValue((string)(typeof(Pig).GetMethod("ToJson").Invoke(value, null))); + } + + /// + /// To convert a JSON string into an object + /// + /// JSON reader + /// Object type + /// Existing value + /// JSON Serializer + /// The object converted from the JSON string + public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) + { + if(reader.TokenType != JsonToken.Null) + { + return Pig.FromJson(JObject.Load(reader).ToString(Formatting.None)); + } + return null; + } + + /// + /// Check if the object can be converted + /// + /// Object type + /// True if the object can be converted + public override bool CanConvert(Type objectType) + { + return false; + } + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Quadrilateral.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Quadrilateral.cs new file mode 100644 index 00000000000..19bc98ed2ec --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Quadrilateral.cs @@ -0,0 +1,307 @@ +/* + * 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 JsonSubTypes; +using System.ComponentModel.DataAnnotations; +using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; +using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using System.Reflection; + +namespace Org.OpenAPITools.Model +{ + /// + /// Quadrilateral + /// + [JsonConverter(typeof(QuadrilateralJsonConverter))] + [DataContract(Name = "Quadrilateral")] + public partial class Quadrilateral : AbstractOpenAPISchema, IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class + /// with the class + /// + /// An instance of ComplexQuadrilateral. + public Quadrilateral(ComplexQuadrilateral actualInstance) + { + this.IsNullable = false; + this.SchemaType= "oneOf"; + this.ActualInstance = actualInstance ?? throw new ArgumentException("Invalid instance found. Must not be null."); + } + + /// + /// Initializes a new instance of the class + /// with the class + /// + /// An instance of SimpleQuadrilateral. + public Quadrilateral(SimpleQuadrilateral actualInstance) + { + this.IsNullable = false; + this.SchemaType= "oneOf"; + this.ActualInstance = actualInstance ?? throw new ArgumentException("Invalid instance found. Must not be null."); + } + + + private Object _actualInstance; + + /// + /// Gets or Sets ActualInstance + /// + public override Object ActualInstance + { + get + { + return _actualInstance; + } + set + { + if (value.GetType() == typeof(ComplexQuadrilateral)) + { + this._actualInstance = value; + } + else if (value.GetType() == typeof(SimpleQuadrilateral)) + { + this._actualInstance = value; + } + else + { + throw new ArgumentException("Invalid instance found. Must be the following types: ComplexQuadrilateral, SimpleQuadrilateral"); + } + } + } + + /// + /// Get the actual instance of `ComplexQuadrilateral`. If the actual instanct is not `ComplexQuadrilateral`, + /// the InvalidClassException will be thrown + /// + /// An instance of ComplexQuadrilateral + public ComplexQuadrilateral GetComplexQuadrilateral() + { + return (ComplexQuadrilateral)this.ActualInstance; + } + + /// + /// Get the actual instance of `SimpleQuadrilateral`. If the actual instanct is not `SimpleQuadrilateral`, + /// the InvalidClassException will be thrown + /// + /// An instance of SimpleQuadrilateral + public SimpleQuadrilateral GetSimpleQuadrilateral() + { + return (SimpleQuadrilateral)this.ActualInstance; + } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + var sb = new StringBuilder(); + sb.Append("class Quadrilateral {\n"); + sb.Append(" ActualInstance: ").Append(this.ActualInstance).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public override string ToJson() + { + return JsonConvert.SerializeObject(this.ActualInstance, Quadrilateral.SerializerSettings); + } + + /// + /// Converts the JSON string into an instance of Quadrilateral + /// + /// JSON string + /// An instance of Quadrilateral + public static Quadrilateral FromJson(string jsonString) + { + Quadrilateral newQuadrilateral = null; + + if (jsonString == null) + { + return newQuadrilateral; + } + + string discriminatorValue = JObject.Parse(jsonString)["quadrilateralType"].ToString(); + switch (discriminatorValue) + { + case "ComplexQuadrilateral": + newQuadrilateral = new Quadrilateral(JsonConvert.DeserializeObject(jsonString, Quadrilateral.AdditionalPropertiesSerializerSettings)); + return newQuadrilateral; + case "SimpleQuadrilateral": + newQuadrilateral = new Quadrilateral(JsonConvert.DeserializeObject(jsonString, Quadrilateral.AdditionalPropertiesSerializerSettings)); + return newQuadrilateral; + default: + System.Diagnostics.Debug.WriteLine(string.Format("Failed to lookup discriminator value `{0}` for Quadrilateral. Possible values: ComplexQuadrilateral SimpleQuadrilateral", discriminatorValue)); + break; + } + + int match = 0; + List matchedTypes = new List(); + + try + { + // if it does not contains "AdditionalProperties", use SerializerSettings to deserialize + if (typeof(ComplexQuadrilateral).GetProperty("AdditionalProperties") == null) + { + newQuadrilateral = new Quadrilateral(JsonConvert.DeserializeObject(jsonString, Quadrilateral.SerializerSettings)); + } + else + { + newQuadrilateral = new Quadrilateral(JsonConvert.DeserializeObject(jsonString, Quadrilateral.AdditionalPropertiesSerializerSettings)); + } + matchedTypes.Add("ComplexQuadrilateral"); + match++; + } + catch (Exception exception) + { + // deserialization failed, try the next one + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into ComplexQuadrilateral: {1}", jsonString, exception.ToString())); + } + + try + { + // if it does not contains "AdditionalProperties", use SerializerSettings to deserialize + if (typeof(SimpleQuadrilateral).GetProperty("AdditionalProperties") == null) + { + newQuadrilateral = new Quadrilateral(JsonConvert.DeserializeObject(jsonString, Quadrilateral.SerializerSettings)); + } + else + { + newQuadrilateral = new Quadrilateral(JsonConvert.DeserializeObject(jsonString, Quadrilateral.AdditionalPropertiesSerializerSettings)); + } + matchedTypes.Add("SimpleQuadrilateral"); + match++; + } + catch (Exception exception) + { + // deserialization failed, try the next one + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into SimpleQuadrilateral: {1}", jsonString, exception.ToString())); + } + + if (match == 0) + { + throw new InvalidDataException("The JSON string `" + jsonString + "` cannot be deserialized into any schema defined."); + } + else if (match > 1) + { + throw new InvalidDataException("The JSON string `" + jsonString + "` incorrectly matches more than one schema (should be exactly one match): " + matchedTypes); + } + + // deserialization is considered successful at this point if no exception has been thrown. + return newQuadrilateral; + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input as Quadrilateral).AreEqual; + } + + /// + /// Returns true if Quadrilateral instances are equal + /// + /// Instance of Quadrilateral to be compared + /// Boolean + public bool Equals(Quadrilateral 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.ActualInstance != null) + hashCode = hashCode * 59 + this.ActualInstance.GetHashCode(); + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// Custom JSON converter for Quadrilateral + /// + public class QuadrilateralJsonConverter : JsonConverter + { + /// + /// To write the JSON string + /// + /// JSON writer + /// Object to be converted into a JSON string + /// JSON Serializer + public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) + { + writer.WriteRawValue((string)(typeof(Quadrilateral).GetMethod("ToJson").Invoke(value, null))); + } + + /// + /// To convert a JSON string into an object + /// + /// JSON reader + /// Object type + /// Existing value + /// JSON Serializer + /// The object converted from the JSON string + public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) + { + if(reader.TokenType != JsonToken.Null) + { + return Quadrilateral.FromJson(JObject.Load(reader).ToString(Formatting.None)); + } + return null; + } + + /// + /// Check if the object can be converted + /// + /// Object type + /// True if the object can be converted + public override bool CanConvert(Type objectType) + { + return false; + } + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/QuadrilateralInterface.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/QuadrilateralInterface.cs new file mode 100644 index 00000000000..08a2bfdd7fe --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/QuadrilateralInterface.cs @@ -0,0 +1,155 @@ +/* + * 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 +{ + /// + /// QuadrilateralInterface + /// + [DataContract(Name = "QuadrilateralInterface")] + public partial class QuadrilateralInterface : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + [JsonConstructorAttribute] + protected QuadrilateralInterface() + { + this.AdditionalProperties = new Dictionary(); + } + /// + /// Initializes a new instance of the class. + /// + /// quadrilateralType (required). + public QuadrilateralInterface(string quadrilateralType = default(string)) + { + // to ensure "quadrilateralType" is required (not null) + this._QuadrilateralType = quadrilateralType ?? throw new ArgumentNullException("quadrilateralType is a required property for QuadrilateralInterface and cannot be null"); + this.AdditionalProperties = new Dictionary(); + } + + /// + /// Gets or Sets QuadrilateralType + /// + [DataMember(Name = "quadrilateralType", IsRequired = true, EmitDefaultValue = false)] + public string QuadrilateralType + { + get{ return _QuadrilateralType;} + set + { + _QuadrilateralType = value; + _flagQuadrilateralType = true; + } + } + private string _QuadrilateralType; + private bool _flagQuadrilateralType; + + /// + /// Returns false as QuadrilateralType should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeQuadrilateralType() + { + return _flagQuadrilateralType; + } + /// + /// 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() + { + var sb = new StringBuilder(); + sb.Append("class QuadrilateralInterface {\n"); + sb.Append(" QuadrilateralType: ").Append(QuadrilateralType).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 QuadrilateralInterface).AreEqual; + } + + /// + /// Returns true if QuadrilateralInterface instances are equal + /// + /// Instance of QuadrilateralInterface to be compared + /// Boolean + public bool Equals(QuadrilateralInterface 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.QuadrilateralType != null) + hashCode = hashCode * 59 + this.QuadrilateralType.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-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/ReadOnlyFirst.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/ReadOnlyFirst.cs new file mode 100644 index 00000000000..0720f542905 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/ReadOnlyFirst.cs @@ -0,0 +1,163 @@ +/* + * 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 +{ + /// + /// ReadOnlyFirst + /// + [DataContract(Name = "ReadOnlyFirst")] + public partial class ReadOnlyFirst : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// baz. + public ReadOnlyFirst(string baz = default(string)) + { + this._Baz = baz; + this.AdditionalProperties = new Dictionary(); + } + + /// + /// Gets or Sets Bar + /// + [DataMember(Name = "bar", EmitDefaultValue = false)] + public string Bar { get; private set; } + + /// + /// Returns false as Bar should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeBar() + { + return false; + } + /// + /// Gets or Sets Baz + /// + [DataMember(Name = "baz", EmitDefaultValue = false)] + public string Baz + { + get{ return _Baz;} + set + { + _Baz = value; + _flagBaz = true; + } + } + private string _Baz; + private bool _flagBaz; + + /// + /// Returns false as Baz should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeBaz() + { + return _flagBaz; + } + /// + /// 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() + { + var sb = new StringBuilder(); + sb.Append("class ReadOnlyFirst {\n"); + sb.Append(" Bar: ").Append(Bar).Append("\n"); + sb.Append(" Baz: ").Append(Baz).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 ReadOnlyFirst).AreEqual; + } + + /// + /// Returns true if ReadOnlyFirst instances are equal + /// + /// Instance of ReadOnlyFirst to be compared + /// Boolean + public bool Equals(ReadOnlyFirst 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.Bar != null) + hashCode = hashCode * 59 + this.Bar.GetHashCode(); + if (this.Baz != null) + hashCode = hashCode * 59 + this.Baz.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-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Return.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Return.cs new file mode 100644 index 00000000000..4d71922d6bf --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Return.cs @@ -0,0 +1,145 @@ +/* + * 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 +{ + /// + /// Model for testing reserved words + /// + [DataContract(Name = "Return")] + public partial class Return : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// _return. + public Return(int _return = default(int)) + { + this.__Return = _return; + this.AdditionalProperties = new Dictionary(); + } + + /// + /// Gets or Sets _Return + /// + [DataMember(Name = "return", EmitDefaultValue = false)] + public int _Return + { + get{ return __Return;} + set + { + __Return = value; + _flag_Return = true; + } + } + private int __Return; + private bool _flag_Return; + + /// + /// Returns false as _Return should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerialize_Return() + { + return _flag_Return; + } + /// + /// 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() + { + var sb = new StringBuilder(); + sb.Append("class Return {\n"); + sb.Append(" _Return: ").Append(_Return).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 Return).AreEqual; + } + + /// + /// Returns true if Return instances are equal + /// + /// Instance of Return to be compared + /// Boolean + public bool Equals(Return 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; + hashCode = hashCode * 59 + this._Return.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-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/ScaleneTriangle.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/ScaleneTriangle.cs new file mode 100644 index 00000000000..c99f9c1b94b --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/ScaleneTriangle.cs @@ -0,0 +1,185 @@ +/* + * 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 +{ + /// + /// ScaleneTriangle + /// + [DataContract(Name = "ScaleneTriangle")] + public partial class ScaleneTriangle : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + [JsonConstructorAttribute] + protected ScaleneTriangle() + { + this.AdditionalProperties = new Dictionary(); + } + /// + /// Initializes a new instance of the class. + /// + /// shapeType (required). + /// triangleType (required). + public ScaleneTriangle(string shapeType = default(string), string triangleType = default(string)) + { + // to ensure "shapeType" is required (not null) + this._ShapeType = shapeType ?? throw new ArgumentNullException("shapeType is a required property for ScaleneTriangle and cannot be null"); + // to ensure "triangleType" is required (not null) + this._TriangleType = triangleType ?? throw new ArgumentNullException("triangleType is a required property for ScaleneTriangle and cannot be null"); + this.AdditionalProperties = new Dictionary(); + } + + /// + /// Gets or Sets ShapeType + /// + [DataMember(Name = "shapeType", IsRequired = true, EmitDefaultValue = false)] + public string ShapeType + { + get{ return _ShapeType;} + set + { + _ShapeType = value; + _flagShapeType = true; + } + } + private string _ShapeType; + private bool _flagShapeType; + + /// + /// Returns false as ShapeType should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeShapeType() + { + return _flagShapeType; + } + /// + /// Gets or Sets TriangleType + /// + [DataMember(Name = "triangleType", IsRequired = true, EmitDefaultValue = false)] + public string TriangleType + { + get{ return _TriangleType;} + set + { + _TriangleType = value; + _flagTriangleType = true; + } + } + private string _TriangleType; + private bool _flagTriangleType; + + /// + /// Returns false as TriangleType should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeTriangleType() + { + return _flagTriangleType; + } + /// + /// 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() + { + var sb = new StringBuilder(); + sb.Append("class ScaleneTriangle {\n"); + sb.Append(" ShapeType: ").Append(ShapeType).Append("\n"); + sb.Append(" TriangleType: ").Append(TriangleType).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 ScaleneTriangle).AreEqual; + } + + /// + /// Returns true if ScaleneTriangle instances are equal + /// + /// Instance of ScaleneTriangle to be compared + /// Boolean + public bool Equals(ScaleneTriangle 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.ShapeType != null) + hashCode = hashCode * 59 + this.ShapeType.GetHashCode(); + if (this.TriangleType != null) + hashCode = hashCode * 59 + this.TriangleType.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-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Shape.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Shape.cs new file mode 100644 index 00000000000..f17c4d9a8f5 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Shape.cs @@ -0,0 +1,307 @@ +/* + * 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 JsonSubTypes; +using System.ComponentModel.DataAnnotations; +using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; +using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using System.Reflection; + +namespace Org.OpenAPITools.Model +{ + /// + /// Shape + /// + [JsonConverter(typeof(ShapeJsonConverter))] + [DataContract(Name = "Shape")] + public partial class Shape : AbstractOpenAPISchema, IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class + /// with the class + /// + /// An instance of Quadrilateral. + public Shape(Quadrilateral actualInstance) + { + this.IsNullable = false; + this.SchemaType= "oneOf"; + this.ActualInstance = actualInstance ?? throw new ArgumentException("Invalid instance found. Must not be null."); + } + + /// + /// Initializes a new instance of the class + /// with the class + /// + /// An instance of Triangle. + public Shape(Triangle actualInstance) + { + this.IsNullable = false; + this.SchemaType= "oneOf"; + this.ActualInstance = actualInstance ?? throw new ArgumentException("Invalid instance found. Must not be null."); + } + + + private Object _actualInstance; + + /// + /// Gets or Sets ActualInstance + /// + public override Object ActualInstance + { + get + { + return _actualInstance; + } + set + { + if (value.GetType() == typeof(Quadrilateral)) + { + this._actualInstance = value; + } + else if (value.GetType() == typeof(Triangle)) + { + this._actualInstance = value; + } + else + { + throw new ArgumentException("Invalid instance found. Must be the following types: Quadrilateral, Triangle"); + } + } + } + + /// + /// Get the actual instance of `Quadrilateral`. If the actual instanct is not `Quadrilateral`, + /// the InvalidClassException will be thrown + /// + /// An instance of Quadrilateral + public Quadrilateral GetQuadrilateral() + { + return (Quadrilateral)this.ActualInstance; + } + + /// + /// Get the actual instance of `Triangle`. If the actual instanct is not `Triangle`, + /// the InvalidClassException will be thrown + /// + /// An instance of Triangle + public Triangle GetTriangle() + { + return (Triangle)this.ActualInstance; + } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + var sb = new StringBuilder(); + sb.Append("class Shape {\n"); + sb.Append(" ActualInstance: ").Append(this.ActualInstance).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public override string ToJson() + { + return JsonConvert.SerializeObject(this.ActualInstance, Shape.SerializerSettings); + } + + /// + /// Converts the JSON string into an instance of Shape + /// + /// JSON string + /// An instance of Shape + public static Shape FromJson(string jsonString) + { + Shape newShape = null; + + if (jsonString == null) + { + return newShape; + } + + string discriminatorValue = JObject.Parse(jsonString)["shapeType"].ToString(); + switch (discriminatorValue) + { + case "Quadrilateral": + newShape = new Shape(JsonConvert.DeserializeObject(jsonString, Shape.AdditionalPropertiesSerializerSettings)); + return newShape; + case "Triangle": + newShape = new Shape(JsonConvert.DeserializeObject(jsonString, Shape.AdditionalPropertiesSerializerSettings)); + return newShape; + default: + System.Diagnostics.Debug.WriteLine(string.Format("Failed to lookup discriminator value `{0}` for Shape. Possible values: Quadrilateral Triangle", discriminatorValue)); + break; + } + + int match = 0; + List matchedTypes = new List(); + + try + { + // if it does not contains "AdditionalProperties", use SerializerSettings to deserialize + if (typeof(Quadrilateral).GetProperty("AdditionalProperties") == null) + { + newShape = new Shape(JsonConvert.DeserializeObject(jsonString, Shape.SerializerSettings)); + } + else + { + newShape = new Shape(JsonConvert.DeserializeObject(jsonString, Shape.AdditionalPropertiesSerializerSettings)); + } + matchedTypes.Add("Quadrilateral"); + match++; + } + catch (Exception exception) + { + // deserialization failed, try the next one + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into Quadrilateral: {1}", jsonString, exception.ToString())); + } + + try + { + // if it does not contains "AdditionalProperties", use SerializerSettings to deserialize + if (typeof(Triangle).GetProperty("AdditionalProperties") == null) + { + newShape = new Shape(JsonConvert.DeserializeObject(jsonString, Shape.SerializerSettings)); + } + else + { + newShape = new Shape(JsonConvert.DeserializeObject(jsonString, Shape.AdditionalPropertiesSerializerSettings)); + } + matchedTypes.Add("Triangle"); + match++; + } + catch (Exception exception) + { + // deserialization failed, try the next one + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into Triangle: {1}", jsonString, exception.ToString())); + } + + if (match == 0) + { + throw new InvalidDataException("The JSON string `" + jsonString + "` cannot be deserialized into any schema defined."); + } + else if (match > 1) + { + throw new InvalidDataException("The JSON string `" + jsonString + "` incorrectly matches more than one schema (should be exactly one match): " + matchedTypes); + } + + // deserialization is considered successful at this point if no exception has been thrown. + return newShape; + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input as Shape).AreEqual; + } + + /// + /// Returns true if Shape instances are equal + /// + /// Instance of Shape to be compared + /// Boolean + public bool Equals(Shape 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.ActualInstance != null) + hashCode = hashCode * 59 + this.ActualInstance.GetHashCode(); + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// Custom JSON converter for Shape + /// + public class ShapeJsonConverter : JsonConverter + { + /// + /// To write the JSON string + /// + /// JSON writer + /// Object to be converted into a JSON string + /// JSON Serializer + public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) + { + writer.WriteRawValue((string)(typeof(Shape).GetMethod("ToJson").Invoke(value, null))); + } + + /// + /// To convert a JSON string into an object + /// + /// JSON reader + /// Object type + /// Existing value + /// JSON Serializer + /// The object converted from the JSON string + public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) + { + if(reader.TokenType != JsonToken.Null) + { + return Shape.FromJson(JObject.Load(reader).ToString(Formatting.None)); + } + return null; + } + + /// + /// Check if the object can be converted + /// + /// Object type + /// True if the object can be converted + public override bool CanConvert(Type objectType) + { + return false; + } + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/ShapeInterface.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/ShapeInterface.cs new file mode 100644 index 00000000000..252d2f1b67d --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/ShapeInterface.cs @@ -0,0 +1,155 @@ +/* + * 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 +{ + /// + /// ShapeInterface + /// + [DataContract(Name = "ShapeInterface")] + public partial class ShapeInterface : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + [JsonConstructorAttribute] + protected ShapeInterface() + { + this.AdditionalProperties = new Dictionary(); + } + /// + /// Initializes a new instance of the class. + /// + /// shapeType (required). + public ShapeInterface(string shapeType = default(string)) + { + // to ensure "shapeType" is required (not null) + this._ShapeType = shapeType ?? throw new ArgumentNullException("shapeType is a required property for ShapeInterface and cannot be null"); + this.AdditionalProperties = new Dictionary(); + } + + /// + /// Gets or Sets ShapeType + /// + [DataMember(Name = "shapeType", IsRequired = true, EmitDefaultValue = false)] + public string ShapeType + { + get{ return _ShapeType;} + set + { + _ShapeType = value; + _flagShapeType = true; + } + } + private string _ShapeType; + private bool _flagShapeType; + + /// + /// Returns false as ShapeType should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeShapeType() + { + return _flagShapeType; + } + /// + /// 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() + { + var sb = new StringBuilder(); + sb.Append("class ShapeInterface {\n"); + sb.Append(" ShapeType: ").Append(ShapeType).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 ShapeInterface).AreEqual; + } + + /// + /// Returns true if ShapeInterface instances are equal + /// + /// Instance of ShapeInterface to be compared + /// Boolean + public bool Equals(ShapeInterface 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.ShapeType != null) + hashCode = hashCode * 59 + this.ShapeType.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-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/ShapeOrNull.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/ShapeOrNull.cs new file mode 100644 index 00000000000..df321dc9e81 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/ShapeOrNull.cs @@ -0,0 +1,316 @@ +/* + * 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 JsonSubTypes; +using System.ComponentModel.DataAnnotations; +using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; +using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using System.Reflection; + +namespace Org.OpenAPITools.Model +{ + /// + /// The value may be a shape or the 'null' value. This is introduced in OAS schema >= 3.1. + /// + [JsonConverter(typeof(ShapeOrNullJsonConverter))] + [DataContract(Name = "ShapeOrNull")] + public partial class ShapeOrNull : AbstractOpenAPISchema, IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + public ShapeOrNull() + { + this.IsNullable = true; + this.SchemaType= "oneOf"; + } + + /// + /// Initializes a new instance of the class + /// with the class + /// + /// An instance of Quadrilateral. + public ShapeOrNull(Quadrilateral actualInstance) + { + this.IsNullable = true; + this.SchemaType= "oneOf"; + this.ActualInstance = actualInstance; + } + + /// + /// Initializes a new instance of the class + /// with the class + /// + /// An instance of Triangle. + public ShapeOrNull(Triangle actualInstance) + { + this.IsNullable = true; + this.SchemaType= "oneOf"; + this.ActualInstance = actualInstance; + } + + + private Object _actualInstance; + + /// + /// Gets or Sets ActualInstance + /// + public override Object ActualInstance + { + get + { + return _actualInstance; + } + set + { + if (value.GetType() == typeof(Quadrilateral)) + { + this._actualInstance = value; + } + else if (value.GetType() == typeof(Triangle)) + { + this._actualInstance = value; + } + else + { + throw new ArgumentException("Invalid instance found. Must be the following types: Quadrilateral, Triangle"); + } + } + } + + /// + /// Get the actual instance of `Quadrilateral`. If the actual instanct is not `Quadrilateral`, + /// the InvalidClassException will be thrown + /// + /// An instance of Quadrilateral + public Quadrilateral GetQuadrilateral() + { + return (Quadrilateral)this.ActualInstance; + } + + /// + /// Get the actual instance of `Triangle`. If the actual instanct is not `Triangle`, + /// the InvalidClassException will be thrown + /// + /// An instance of Triangle + public Triangle GetTriangle() + { + return (Triangle)this.ActualInstance; + } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + var sb = new StringBuilder(); + sb.Append("class ShapeOrNull {\n"); + sb.Append(" ActualInstance: ").Append(this.ActualInstance).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public override string ToJson() + { + return JsonConvert.SerializeObject(this.ActualInstance, ShapeOrNull.SerializerSettings); + } + + /// + /// Converts the JSON string into an instance of ShapeOrNull + /// + /// JSON string + /// An instance of ShapeOrNull + public static ShapeOrNull FromJson(string jsonString) + { + ShapeOrNull newShapeOrNull = null; + + if (jsonString == null) + { + return newShapeOrNull; + } + + string discriminatorValue = JObject.Parse(jsonString)["shapeType"].ToString(); + switch (discriminatorValue) + { + case "Quadrilateral": + newShapeOrNull = new ShapeOrNull(JsonConvert.DeserializeObject(jsonString, ShapeOrNull.AdditionalPropertiesSerializerSettings)); + return newShapeOrNull; + case "Triangle": + newShapeOrNull = new ShapeOrNull(JsonConvert.DeserializeObject(jsonString, ShapeOrNull.AdditionalPropertiesSerializerSettings)); + return newShapeOrNull; + default: + System.Diagnostics.Debug.WriteLine(string.Format("Failed to lookup discriminator value `{0}` for ShapeOrNull. Possible values: Quadrilateral Triangle", discriminatorValue)); + break; + } + + int match = 0; + List matchedTypes = new List(); + + try + { + // if it does not contains "AdditionalProperties", use SerializerSettings to deserialize + if (typeof(Quadrilateral).GetProperty("AdditionalProperties") == null) + { + newShapeOrNull = new ShapeOrNull(JsonConvert.DeserializeObject(jsonString, ShapeOrNull.SerializerSettings)); + } + else + { + newShapeOrNull = new ShapeOrNull(JsonConvert.DeserializeObject(jsonString, ShapeOrNull.AdditionalPropertiesSerializerSettings)); + } + matchedTypes.Add("Quadrilateral"); + match++; + } + catch (Exception exception) + { + // deserialization failed, try the next one + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into Quadrilateral: {1}", jsonString, exception.ToString())); + } + + try + { + // if it does not contains "AdditionalProperties", use SerializerSettings to deserialize + if (typeof(Triangle).GetProperty("AdditionalProperties") == null) + { + newShapeOrNull = new ShapeOrNull(JsonConvert.DeserializeObject(jsonString, ShapeOrNull.SerializerSettings)); + } + else + { + newShapeOrNull = new ShapeOrNull(JsonConvert.DeserializeObject(jsonString, ShapeOrNull.AdditionalPropertiesSerializerSettings)); + } + matchedTypes.Add("Triangle"); + match++; + } + catch (Exception exception) + { + // deserialization failed, try the next one + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into Triangle: {1}", jsonString, exception.ToString())); + } + + if (match == 0) + { + throw new InvalidDataException("The JSON string `" + jsonString + "` cannot be deserialized into any schema defined."); + } + else if (match > 1) + { + throw new InvalidDataException("The JSON string `" + jsonString + "` incorrectly matches more than one schema (should be exactly one match): " + matchedTypes); + } + + // deserialization is considered successful at this point if no exception has been thrown. + return newShapeOrNull; + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input as ShapeOrNull).AreEqual; + } + + /// + /// Returns true if ShapeOrNull instances are equal + /// + /// Instance of ShapeOrNull to be compared + /// Boolean + public bool Equals(ShapeOrNull 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.ActualInstance != null) + hashCode = hashCode * 59 + this.ActualInstance.GetHashCode(); + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// Custom JSON converter for ShapeOrNull + /// + public class ShapeOrNullJsonConverter : JsonConverter + { + /// + /// To write the JSON string + /// + /// JSON writer + /// Object to be converted into a JSON string + /// JSON Serializer + public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) + { + writer.WriteRawValue((string)(typeof(ShapeOrNull).GetMethod("ToJson").Invoke(value, null))); + } + + /// + /// To convert a JSON string into an object + /// + /// JSON reader + /// Object type + /// Existing value + /// JSON Serializer + /// The object converted from the JSON string + public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) + { + if(reader.TokenType != JsonToken.Null) + { + return ShapeOrNull.FromJson(JObject.Load(reader).ToString(Formatting.None)); + } + return null; + } + + /// + /// Check if the object can be converted + /// + /// Object type + /// True if the object can be converted + public override bool CanConvert(Type objectType) + { + return false; + } + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/SimpleQuadrilateral.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/SimpleQuadrilateral.cs new file mode 100644 index 00000000000..987c37ca8fd --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/SimpleQuadrilateral.cs @@ -0,0 +1,185 @@ +/* + * 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 +{ + /// + /// SimpleQuadrilateral + /// + [DataContract(Name = "SimpleQuadrilateral")] + public partial class SimpleQuadrilateral : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + [JsonConstructorAttribute] + protected SimpleQuadrilateral() + { + this.AdditionalProperties = new Dictionary(); + } + /// + /// Initializes a new instance of the class. + /// + /// shapeType (required). + /// quadrilateralType (required). + public SimpleQuadrilateral(string shapeType = default(string), string quadrilateralType = default(string)) + { + // to ensure "shapeType" is required (not null) + this._ShapeType = shapeType ?? throw new ArgumentNullException("shapeType is a required property for SimpleQuadrilateral and cannot be null"); + // to ensure "quadrilateralType" is required (not null) + this._QuadrilateralType = quadrilateralType ?? throw new ArgumentNullException("quadrilateralType is a required property for SimpleQuadrilateral and cannot be null"); + this.AdditionalProperties = new Dictionary(); + } + + /// + /// Gets or Sets ShapeType + /// + [DataMember(Name = "shapeType", IsRequired = true, EmitDefaultValue = false)] + public string ShapeType + { + get{ return _ShapeType;} + set + { + _ShapeType = value; + _flagShapeType = true; + } + } + private string _ShapeType; + private bool _flagShapeType; + + /// + /// Returns false as ShapeType should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeShapeType() + { + return _flagShapeType; + } + /// + /// Gets or Sets QuadrilateralType + /// + [DataMember(Name = "quadrilateralType", IsRequired = true, EmitDefaultValue = false)] + public string QuadrilateralType + { + get{ return _QuadrilateralType;} + set + { + _QuadrilateralType = value; + _flagQuadrilateralType = true; + } + } + private string _QuadrilateralType; + private bool _flagQuadrilateralType; + + /// + /// Returns false as QuadrilateralType should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeQuadrilateralType() + { + return _flagQuadrilateralType; + } + /// + /// 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() + { + var sb = new StringBuilder(); + sb.Append("class SimpleQuadrilateral {\n"); + sb.Append(" ShapeType: ").Append(ShapeType).Append("\n"); + sb.Append(" QuadrilateralType: ").Append(QuadrilateralType).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 SimpleQuadrilateral).AreEqual; + } + + /// + /// Returns true if SimpleQuadrilateral instances are equal + /// + /// Instance of SimpleQuadrilateral to be compared + /// Boolean + public bool Equals(SimpleQuadrilateral 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.ShapeType != null) + hashCode = hashCode * 59 + this.ShapeType.GetHashCode(); + if (this.QuadrilateralType != null) + hashCode = hashCode * 59 + this.QuadrilateralType.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-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/SpecialModelName.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/SpecialModelName.cs new file mode 100644 index 00000000000..15361a89e62 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/SpecialModelName.cs @@ -0,0 +1,174 @@ +/* + * 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 +{ + /// + /// SpecialModelName + /// + [DataContract(Name = "_special_model.name_")] + public partial class SpecialModelName : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// specialPropertyName. + /// specialModelName. + public SpecialModelName(long specialPropertyName = default(long), string specialModelName = default(string)) + { + this._SpecialPropertyName = specialPropertyName; + this.__SpecialModelName = specialModelName; + this.AdditionalProperties = new Dictionary(); + } + + /// + /// Gets or Sets SpecialPropertyName + /// + [DataMember(Name = "$special[property.name]", EmitDefaultValue = false)] + public long SpecialPropertyName + { + get{ return _SpecialPropertyName;} + set + { + _SpecialPropertyName = value; + _flagSpecialPropertyName = true; + } + } + private long _SpecialPropertyName; + private bool _flagSpecialPropertyName; + + /// + /// Returns false as SpecialPropertyName should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeSpecialPropertyName() + { + return _flagSpecialPropertyName; + } + /// + /// Gets or Sets _SpecialModelName + /// + [DataMember(Name = "_special_model.name_", EmitDefaultValue = false)] + public string _SpecialModelName + { + get{ return __SpecialModelName;} + set + { + __SpecialModelName = value; + _flag_SpecialModelName = true; + } + } + private string __SpecialModelName; + private bool _flag_SpecialModelName; + + /// + /// Returns false as _SpecialModelName should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerialize_SpecialModelName() + { + return _flag_SpecialModelName; + } + /// + /// 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() + { + var sb = new StringBuilder(); + sb.Append("class SpecialModelName {\n"); + sb.Append(" SpecialPropertyName: ").Append(SpecialPropertyName).Append("\n"); + sb.Append(" _SpecialModelName: ").Append(_SpecialModelName).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 SpecialModelName).AreEqual; + } + + /// + /// Returns true if SpecialModelName instances are equal + /// + /// Instance of SpecialModelName to be compared + /// Boolean + public bool Equals(SpecialModelName 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; + hashCode = hashCode * 59 + this.SpecialPropertyName.GetHashCode(); + if (this._SpecialModelName != null) + hashCode = hashCode * 59 + this._SpecialModelName.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-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Tag.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Tag.cs new file mode 100644 index 00000000000..573443ca6ad --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Tag.cs @@ -0,0 +1,174 @@ +/* + * 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 +{ + /// + /// Tag + /// + [DataContract(Name = "Tag")] + public partial class Tag : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// id. + /// name. + public Tag(long id = default(long), string name = default(string)) + { + this._Id = id; + this._Name = name; + this.AdditionalProperties = new Dictionary(); + } + + /// + /// Gets or Sets Id + /// + [DataMember(Name = "id", EmitDefaultValue = false)] + public long Id + { + get{ return _Id;} + set + { + _Id = value; + _flagId = true; + } + } + private long _Id; + private bool _flagId; + + /// + /// Returns false as Id should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeId() + { + return _flagId; + } + /// + /// Gets or Sets Name + /// + [DataMember(Name = "name", EmitDefaultValue = false)] + public string Name + { + get{ return _Name;} + set + { + _Name = value; + _flagName = true; + } + } + private string _Name; + private bool _flagName; + + /// + /// Returns false as Name should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeName() + { + return _flagName; + } + /// + /// 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() + { + var sb = new StringBuilder(); + sb.Append("class Tag {\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" Name: ").Append(Name).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 Tag).AreEqual; + } + + /// + /// Returns true if Tag instances are equal + /// + /// Instance of Tag to be compared + /// Boolean + public bool Equals(Tag 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; + hashCode = hashCode * 59 + this.Id.GetHashCode(); + if (this.Name != null) + hashCode = hashCode * 59 + this.Name.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-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Triangle.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Triangle.cs new file mode 100644 index 00000000000..6f33859a898 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Triangle.cs @@ -0,0 +1,356 @@ +/* + * 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 JsonSubTypes; +using System.ComponentModel.DataAnnotations; +using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; +using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using System.Reflection; + +namespace Org.OpenAPITools.Model +{ + /// + /// Triangle + /// + [JsonConverter(typeof(TriangleJsonConverter))] + [DataContract(Name = "Triangle")] + public partial class Triangle : AbstractOpenAPISchema, IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class + /// with the class + /// + /// An instance of EquilateralTriangle. + public Triangle(EquilateralTriangle actualInstance) + { + this.IsNullable = false; + this.SchemaType= "oneOf"; + this.ActualInstance = actualInstance ?? throw new ArgumentException("Invalid instance found. Must not be null."); + } + + /// + /// Initializes a new instance of the class + /// with the class + /// + /// An instance of IsoscelesTriangle. + public Triangle(IsoscelesTriangle actualInstance) + { + this.IsNullable = false; + this.SchemaType= "oneOf"; + this.ActualInstance = actualInstance ?? throw new ArgumentException("Invalid instance found. Must not be null."); + } + + /// + /// Initializes a new instance of the class + /// with the class + /// + /// An instance of ScaleneTriangle. + public Triangle(ScaleneTriangle actualInstance) + { + this.IsNullable = false; + this.SchemaType= "oneOf"; + this.ActualInstance = actualInstance ?? throw new ArgumentException("Invalid instance found. Must not be null."); + } + + + private Object _actualInstance; + + /// + /// Gets or Sets ActualInstance + /// + public override Object ActualInstance + { + get + { + return _actualInstance; + } + set + { + if (value.GetType() == typeof(EquilateralTriangle)) + { + this._actualInstance = value; + } + else if (value.GetType() == typeof(IsoscelesTriangle)) + { + this._actualInstance = value; + } + else if (value.GetType() == typeof(ScaleneTriangle)) + { + this._actualInstance = value; + } + else + { + throw new ArgumentException("Invalid instance found. Must be the following types: EquilateralTriangle, IsoscelesTriangle, ScaleneTriangle"); + } + } + } + + /// + /// Get the actual instance of `EquilateralTriangle`. If the actual instanct is not `EquilateralTriangle`, + /// the InvalidClassException will be thrown + /// + /// An instance of EquilateralTriangle + public EquilateralTriangle GetEquilateralTriangle() + { + return (EquilateralTriangle)this.ActualInstance; + } + + /// + /// Get the actual instance of `IsoscelesTriangle`. If the actual instanct is not `IsoscelesTriangle`, + /// the InvalidClassException will be thrown + /// + /// An instance of IsoscelesTriangle + public IsoscelesTriangle GetIsoscelesTriangle() + { + return (IsoscelesTriangle)this.ActualInstance; + } + + /// + /// Get the actual instance of `ScaleneTriangle`. If the actual instanct is not `ScaleneTriangle`, + /// the InvalidClassException will be thrown + /// + /// An instance of ScaleneTriangle + public ScaleneTriangle GetScaleneTriangle() + { + return (ScaleneTriangle)this.ActualInstance; + } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + var sb = new StringBuilder(); + sb.Append("class Triangle {\n"); + sb.Append(" ActualInstance: ").Append(this.ActualInstance).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public override string ToJson() + { + return JsonConvert.SerializeObject(this.ActualInstance, Triangle.SerializerSettings); + } + + /// + /// Converts the JSON string into an instance of Triangle + /// + /// JSON string + /// An instance of Triangle + public static Triangle FromJson(string jsonString) + { + Triangle newTriangle = null; + + if (jsonString == null) + { + return newTriangle; + } + + string discriminatorValue = JObject.Parse(jsonString)["triangleType"].ToString(); + switch (discriminatorValue) + { + case "EquilateralTriangle": + newTriangle = new Triangle(JsonConvert.DeserializeObject(jsonString, Triangle.AdditionalPropertiesSerializerSettings)); + return newTriangle; + case "IsoscelesTriangle": + newTriangle = new Triangle(JsonConvert.DeserializeObject(jsonString, Triangle.AdditionalPropertiesSerializerSettings)); + return newTriangle; + case "ScaleneTriangle": + newTriangle = new Triangle(JsonConvert.DeserializeObject(jsonString, Triangle.AdditionalPropertiesSerializerSettings)); + return newTriangle; + default: + System.Diagnostics.Debug.WriteLine(string.Format("Failed to lookup discriminator value `{0}` for Triangle. Possible values: EquilateralTriangle IsoscelesTriangle ScaleneTriangle", discriminatorValue)); + break; + } + + int match = 0; + List matchedTypes = new List(); + + try + { + // if it does not contains "AdditionalProperties", use SerializerSettings to deserialize + if (typeof(EquilateralTriangle).GetProperty("AdditionalProperties") == null) + { + newTriangle = new Triangle(JsonConvert.DeserializeObject(jsonString, Triangle.SerializerSettings)); + } + else + { + newTriangle = new Triangle(JsonConvert.DeserializeObject(jsonString, Triangle.AdditionalPropertiesSerializerSettings)); + } + matchedTypes.Add("EquilateralTriangle"); + match++; + } + catch (Exception exception) + { + // deserialization failed, try the next one + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into EquilateralTriangle: {1}", jsonString, exception.ToString())); + } + + try + { + // if it does not contains "AdditionalProperties", use SerializerSettings to deserialize + if (typeof(IsoscelesTriangle).GetProperty("AdditionalProperties") == null) + { + newTriangle = new Triangle(JsonConvert.DeserializeObject(jsonString, Triangle.SerializerSettings)); + } + else + { + newTriangle = new Triangle(JsonConvert.DeserializeObject(jsonString, Triangle.AdditionalPropertiesSerializerSettings)); + } + matchedTypes.Add("IsoscelesTriangle"); + match++; + } + catch (Exception exception) + { + // deserialization failed, try the next one + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into IsoscelesTriangle: {1}", jsonString, exception.ToString())); + } + + try + { + // if it does not contains "AdditionalProperties", use SerializerSettings to deserialize + if (typeof(ScaleneTriangle).GetProperty("AdditionalProperties") == null) + { + newTriangle = new Triangle(JsonConvert.DeserializeObject(jsonString, Triangle.SerializerSettings)); + } + else + { + newTriangle = new Triangle(JsonConvert.DeserializeObject(jsonString, Triangle.AdditionalPropertiesSerializerSettings)); + } + matchedTypes.Add("ScaleneTriangle"); + match++; + } + catch (Exception exception) + { + // deserialization failed, try the next one + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into ScaleneTriangle: {1}", jsonString, exception.ToString())); + } + + if (match == 0) + { + throw new InvalidDataException("The JSON string `" + jsonString + "` cannot be deserialized into any schema defined."); + } + else if (match > 1) + { + throw new InvalidDataException("The JSON string `" + jsonString + "` incorrectly matches more than one schema (should be exactly one match): " + matchedTypes); + } + + // deserialization is considered successful at this point if no exception has been thrown. + return newTriangle; + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input as Triangle).AreEqual; + } + + /// + /// Returns true if Triangle instances are equal + /// + /// Instance of Triangle to be compared + /// Boolean + public bool Equals(Triangle 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.ActualInstance != null) + hashCode = hashCode * 59 + this.ActualInstance.GetHashCode(); + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// Custom JSON converter for Triangle + /// + public class TriangleJsonConverter : JsonConverter + { + /// + /// To write the JSON string + /// + /// JSON writer + /// Object to be converted into a JSON string + /// JSON Serializer + public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) + { + writer.WriteRawValue((string)(typeof(Triangle).GetMethod("ToJson").Invoke(value, null))); + } + + /// + /// To convert a JSON string into an object + /// + /// JSON reader + /// Object type + /// Existing value + /// JSON Serializer + /// The object converted from the JSON string + public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) + { + if(reader.TokenType != JsonToken.Null) + { + return Triangle.FromJson(JObject.Load(reader).ToString(Formatting.None)); + } + return null; + } + + /// + /// Check if the object can be converted + /// + /// Object type + /// True if the object can be converted + public override bool CanConvert(Type objectType) + { + return false; + } + } + +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/TriangleInterface.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/TriangleInterface.cs new file mode 100644 index 00000000000..21ef9120066 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/TriangleInterface.cs @@ -0,0 +1,155 @@ +/* + * 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 +{ + /// + /// TriangleInterface + /// + [DataContract(Name = "TriangleInterface")] + public partial class TriangleInterface : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + [JsonConstructorAttribute] + protected TriangleInterface() + { + this.AdditionalProperties = new Dictionary(); + } + /// + /// Initializes a new instance of the class. + /// + /// triangleType (required). + public TriangleInterface(string triangleType = default(string)) + { + // to ensure "triangleType" is required (not null) + this._TriangleType = triangleType ?? throw new ArgumentNullException("triangleType is a required property for TriangleInterface and cannot be null"); + this.AdditionalProperties = new Dictionary(); + } + + /// + /// Gets or Sets TriangleType + /// + [DataMember(Name = "triangleType", IsRequired = true, EmitDefaultValue = false)] + public string TriangleType + { + get{ return _TriangleType;} + set + { + _TriangleType = value; + _flagTriangleType = true; + } + } + private string _TriangleType; + private bool _flagTriangleType; + + /// + /// Returns false as TriangleType should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeTriangleType() + { + return _flagTriangleType; + } + /// + /// 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() + { + var sb = new StringBuilder(); + sb.Append("class TriangleInterface {\n"); + sb.Append(" TriangleType: ").Append(TriangleType).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 TriangleInterface).AreEqual; + } + + /// + /// Returns true if TriangleInterface instances are equal + /// + /// Instance of TriangleInterface to be compared + /// Boolean + public bool Equals(TriangleInterface 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.TriangleType != null) + hashCode = hashCode * 59 + this.TriangleType.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-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/User.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/User.cs new file mode 100644 index 00000000000..16e9fdf6b7f --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/User.cs @@ -0,0 +1,468 @@ +/* + * 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 +{ + /// + /// User + /// + [DataContract(Name = "User")] + public partial class User : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// id. + /// username. + /// firstName. + /// lastName. + /// email. + /// password. + /// phone. + /// User Status. + /// 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.. + /// 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.. + public User(long id = default(long), string username = default(string), string firstName = default(string), string lastName = default(string), string email = default(string), string password = default(string), string phone = default(string), int userStatus = default(int), Object objectWithNoDeclaredProps = default(Object), Object objectWithNoDeclaredPropsNullable = default(Object), Object anyTypeProp = default(Object), Object anyTypePropNullable = default(Object)) + { + this._Id = id; + this._Username = username; + this._FirstName = firstName; + this._LastName = lastName; + this._Email = email; + this._Password = password; + this._Phone = phone; + this._UserStatus = userStatus; + this._ObjectWithNoDeclaredProps = objectWithNoDeclaredProps; + this._ObjectWithNoDeclaredPropsNullable = objectWithNoDeclaredPropsNullable; + this._AnyTypeProp = anyTypeProp; + this._AnyTypePropNullable = anyTypePropNullable; + this.AdditionalProperties = new Dictionary(); + } + + /// + /// Gets or Sets Id + /// + [DataMember(Name = "id", EmitDefaultValue = false)] + public long Id + { + get{ return _Id;} + set + { + _Id = value; + _flagId = true; + } + } + private long _Id; + private bool _flagId; + + /// + /// Returns false as Id should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeId() + { + return _flagId; + } + /// + /// Gets or Sets Username + /// + [DataMember(Name = "username", EmitDefaultValue = false)] + public string Username + { + get{ return _Username;} + set + { + _Username = value; + _flagUsername = true; + } + } + private string _Username; + private bool _flagUsername; + + /// + /// Returns false as Username should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeUsername() + { + return _flagUsername; + } + /// + /// Gets or Sets FirstName + /// + [DataMember(Name = "firstName", EmitDefaultValue = false)] + public string FirstName + { + get{ return _FirstName;} + set + { + _FirstName = value; + _flagFirstName = true; + } + } + private string _FirstName; + private bool _flagFirstName; + + /// + /// Returns false as FirstName should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeFirstName() + { + return _flagFirstName; + } + /// + /// Gets or Sets LastName + /// + [DataMember(Name = "lastName", EmitDefaultValue = false)] + public string LastName + { + get{ return _LastName;} + set + { + _LastName = value; + _flagLastName = true; + } + } + private string _LastName; + private bool _flagLastName; + + /// + /// Returns false as LastName should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeLastName() + { + return _flagLastName; + } + /// + /// Gets or Sets Email + /// + [DataMember(Name = "email", EmitDefaultValue = false)] + public string Email + { + get{ return _Email;} + set + { + _Email = value; + _flagEmail = true; + } + } + private string _Email; + private bool _flagEmail; + + /// + /// Returns false as Email should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeEmail() + { + return _flagEmail; + } + /// + /// Gets or Sets Password + /// + [DataMember(Name = "password", EmitDefaultValue = false)] + public string Password + { + get{ return _Password;} + set + { + _Password = value; + _flagPassword = true; + } + } + private string _Password; + private bool _flagPassword; + + /// + /// Returns false as Password should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializePassword() + { + return _flagPassword; + } + /// + /// Gets or Sets Phone + /// + [DataMember(Name = "phone", EmitDefaultValue = false)] + public string Phone + { + get{ return _Phone;} + set + { + _Phone = value; + _flagPhone = true; + } + } + private string _Phone; + private bool _flagPhone; + + /// + /// Returns false as Phone should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializePhone() + { + return _flagPhone; + } + /// + /// User Status + /// + /// User Status + [DataMember(Name = "userStatus", EmitDefaultValue = false)] + public int UserStatus + { + get{ return _UserStatus;} + set + { + _UserStatus = value; + _flagUserStatus = true; + } + } + private int _UserStatus; + private bool _flagUserStatus; + + /// + /// Returns false as UserStatus should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeUserStatus() + { + return _flagUserStatus; + } + /// + /// 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. + [DataMember(Name = "objectWithNoDeclaredProps", EmitDefaultValue = false)] + public Object ObjectWithNoDeclaredProps + { + get{ return _ObjectWithNoDeclaredProps;} + set + { + _ObjectWithNoDeclaredProps = value; + _flagObjectWithNoDeclaredProps = true; + } + } + private Object _ObjectWithNoDeclaredProps; + private bool _flagObjectWithNoDeclaredProps; + + /// + /// Returns false as ObjectWithNoDeclaredProps should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeObjectWithNoDeclaredProps() + { + return _flagObjectWithNoDeclaredProps; + } + /// + /// 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. + [DataMember(Name = "objectWithNoDeclaredPropsNullable", EmitDefaultValue = true)] + public Object ObjectWithNoDeclaredPropsNullable + { + get{ return _ObjectWithNoDeclaredPropsNullable;} + set + { + _ObjectWithNoDeclaredPropsNullable = value; + _flagObjectWithNoDeclaredPropsNullable = true; + } + } + private Object _ObjectWithNoDeclaredPropsNullable; + private bool _flagObjectWithNoDeclaredPropsNullable; + + /// + /// Returns false as ObjectWithNoDeclaredPropsNullable should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeObjectWithNoDeclaredPropsNullable() + { + return _flagObjectWithNoDeclaredPropsNullable; + } + /// + /// 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 + [DataMember(Name = "anyTypeProp", EmitDefaultValue = true)] + public Object AnyTypeProp + { + get{ return _AnyTypeProp;} + set + { + _AnyTypeProp = value; + _flagAnyTypeProp = true; + } + } + private Object _AnyTypeProp; + private bool _flagAnyTypeProp; + + /// + /// Returns false as AnyTypeProp should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeAnyTypeProp() + { + return _flagAnyTypeProp; + } + /// + /// 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. + [DataMember(Name = "anyTypePropNullable", EmitDefaultValue = true)] + public Object AnyTypePropNullable + { + get{ return _AnyTypePropNullable;} + set + { + _AnyTypePropNullable = value; + _flagAnyTypePropNullable = true; + } + } + private Object _AnyTypePropNullable; + private bool _flagAnyTypePropNullable; + + /// + /// Returns false as AnyTypePropNullable should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeAnyTypePropNullable() + { + return _flagAnyTypePropNullable; + } + /// + /// 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() + { + var sb = new StringBuilder(); + sb.Append("class User {\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" Username: ").Append(Username).Append("\n"); + sb.Append(" FirstName: ").Append(FirstName).Append("\n"); + sb.Append(" LastName: ").Append(LastName).Append("\n"); + sb.Append(" Email: ").Append(Email).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(" ObjectWithNoDeclaredProps: ").Append(ObjectWithNoDeclaredProps).Append("\n"); + sb.Append(" ObjectWithNoDeclaredPropsNullable: ").Append(ObjectWithNoDeclaredPropsNullable).Append("\n"); + sb.Append(" AnyTypeProp: ").Append(AnyTypeProp).Append("\n"); + sb.Append(" AnyTypePropNullable: ").Append(AnyTypePropNullable).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 User).AreEqual; + } + + /// + /// Returns true if User instances are equal + /// + /// Instance of User to be compared + /// Boolean + public bool Equals(User 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; + hashCode = hashCode * 59 + this.Id.GetHashCode(); + if (this.Username != null) + hashCode = hashCode * 59 + this.Username.GetHashCode(); + if (this.FirstName != null) + hashCode = hashCode * 59 + this.FirstName.GetHashCode(); + if (this.LastName != null) + hashCode = hashCode * 59 + this.LastName.GetHashCode(); + if (this.Email != null) + hashCode = hashCode * 59 + this.Email.GetHashCode(); + if (this.Password != null) + hashCode = hashCode * 59 + this.Password.GetHashCode(); + if (this.Phone != null) + hashCode = hashCode * 59 + this.Phone.GetHashCode(); + hashCode = hashCode * 59 + this.UserStatus.GetHashCode(); + if (this.ObjectWithNoDeclaredProps != null) + hashCode = hashCode * 59 + this.ObjectWithNoDeclaredProps.GetHashCode(); + if (this.ObjectWithNoDeclaredPropsNullable != null) + hashCode = hashCode * 59 + this.ObjectWithNoDeclaredPropsNullable.GetHashCode(); + if (this.AnyTypeProp != null) + hashCode = hashCode * 59 + this.AnyTypeProp.GetHashCode(); + if (this.AnyTypePropNullable != null) + hashCode = hashCode * 59 + this.AnyTypePropNullable.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-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Whale.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Whale.cs new file mode 100644 index 00000000000..74433740aa0 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Whale.cs @@ -0,0 +1,211 @@ +/* + * 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 +{ + /// + /// Whale + /// + [DataContract(Name = "whale")] + public partial class Whale : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + [JsonConstructorAttribute] + protected Whale() + { + this.AdditionalProperties = new Dictionary(); + } + /// + /// Initializes a new instance of the class. + /// + /// hasBaleen. + /// hasTeeth. + /// className (required). + public Whale(bool hasBaleen = default(bool), bool hasTeeth = default(bool), string className = default(string)) + { + // to ensure "className" is required (not null) + this._ClassName = className ?? throw new ArgumentNullException("className is a required property for Whale and cannot be null"); + this._HasBaleen = hasBaleen; + this._HasTeeth = hasTeeth; + this.AdditionalProperties = new Dictionary(); + } + + /// + /// Gets or Sets HasBaleen + /// + [DataMember(Name = "hasBaleen", EmitDefaultValue = true)] + public bool HasBaleen + { + get{ return _HasBaleen;} + set + { + _HasBaleen = value; + _flagHasBaleen = true; + } + } + private bool _HasBaleen; + private bool _flagHasBaleen; + + /// + /// Returns false as HasBaleen should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeHasBaleen() + { + return _flagHasBaleen; + } + /// + /// Gets or Sets HasTeeth + /// + [DataMember(Name = "hasTeeth", EmitDefaultValue = true)] + public bool HasTeeth + { + get{ return _HasTeeth;} + set + { + _HasTeeth = value; + _flagHasTeeth = true; + } + } + private bool _HasTeeth; + private bool _flagHasTeeth; + + /// + /// Returns false as HasTeeth should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeHasTeeth() + { + return _flagHasTeeth; + } + /// + /// Gets or Sets ClassName + /// + [DataMember(Name = "className", IsRequired = true, EmitDefaultValue = false)] + public string ClassName + { + get{ return _ClassName;} + set + { + _ClassName = value; + _flagClassName = true; + } + } + private string _ClassName; + private bool _flagClassName; + + /// + /// Returns false as ClassName should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeClassName() + { + return _flagClassName; + } + /// + /// 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() + { + var sb = new StringBuilder(); + sb.Append("class Whale {\n"); + sb.Append(" HasBaleen: ").Append(HasBaleen).Append("\n"); + sb.Append(" HasTeeth: ").Append(HasTeeth).Append("\n"); + sb.Append(" ClassName: ").Append(ClassName).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 Whale).AreEqual; + } + + /// + /// Returns true if Whale instances are equal + /// + /// Instance of Whale to be compared + /// Boolean + public bool Equals(Whale 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; + hashCode = hashCode * 59 + this.HasBaleen.GetHashCode(); + hashCode = hashCode * 59 + this.HasTeeth.GetHashCode(); + if (this.ClassName != null) + hashCode = hashCode * 59 + this.ClassName.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-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Zebra.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Zebra.cs new file mode 100644 index 00000000000..ea635932f88 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Zebra.cs @@ -0,0 +1,212 @@ +/* + * 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 +{ + /// + /// Zebra + /// + [DataContract(Name = "zebra")] + public partial class Zebra : Dictionary, IEquatable, IValidatableObject + { + /// + /// Defines Type + /// + [JsonConverter(typeof(StringEnumConverter))] + public enum TypeEnum + { + /// + /// Enum Plains for value: plains + /// + [EnumMember(Value = "plains")] + Plains = 1, + + /// + /// Enum Mountain for value: mountain + /// + [EnumMember(Value = "mountain")] + Mountain = 2, + + /// + /// Enum Grevys for value: grevys + /// + [EnumMember(Value = "grevys")] + Grevys = 3 + + } + + + /// + /// Gets or Sets Type + /// + + [DataMember(Name = "type", EmitDefaultValue = false)] + public TypeEnum? Type + { + get{ return _Type;} + set + { + _Type = value; + _flagType = true; + } + } + private TypeEnum? _Type; + private bool _flagType; + + /// + /// Returns false as Type should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeType() + { + return _flagType; + } + /// + /// Initializes a new instance of the class. + /// + [JsonConstructorAttribute] + protected Zebra() + { + this.AdditionalProperties = new Dictionary(); + } + /// + /// Initializes a new instance of the class. + /// + /// type. + /// className (required). + public Zebra(TypeEnum? type = default(TypeEnum?), string className = default(string)) : base() + { + // to ensure "className" is required (not null) + this._ClassName = className ?? throw new ArgumentNullException("className is a required property for Zebra and cannot be null"); + this._Type = type; + this.AdditionalProperties = new Dictionary(); + } + + /// + /// Gets or Sets ClassName + /// + [DataMember(Name = "className", IsRequired = true, EmitDefaultValue = false)] + public string ClassName + { + get{ return _ClassName;} + set + { + _ClassName = value; + _flagClassName = true; + } + } + private string _ClassName; + private bool _flagClassName; + + /// + /// Returns false as ClassName should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeClassName() + { + return _flagClassName; + } + /// + /// 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() + { + var 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"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public 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 Zebra).AreEqual; + } + + /// + /// Returns true if Zebra instances are equal + /// + /// Instance of Zebra to be compared + /// Boolean + public bool Equals(Zebra 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 = base.GetHashCode(); + hashCode = hashCode * 59 + this.Type.GetHashCode(); + if (this.ClassName != null) + hashCode = hashCode * 59 + this.ClassName.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-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Org.OpenAPITools.csproj b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Org.OpenAPITools.csproj new file mode 100644 index 00000000000..46d46e09809 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Org.OpenAPITools.csproj @@ -0,0 +1,31 @@ + + + + false + netstandard2.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 + + + + + + + + + + + + diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/.openapi-generator/FILES b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/.openapi-generator/FILES index e6b9861f332..d317e612051 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/.openapi-generator/FILES +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/.openapi-generator/FILES @@ -97,6 +97,7 @@ 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/FileParameter.cs src/Org.OpenAPITools/Client/GlobalConfiguration.cs src/Org.OpenAPITools/Client/HttpSigningConfiguration.cs src/Org.OpenAPITools/Client/IApiAccessor.cs diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/.openapi-generator/VERSION b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/.openapi-generator/VERSION +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/docs/FakeApi.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/docs/FakeApi.md index 947fbb114ef..c5a0b767f3d 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/docs/FakeApi.md +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/docs/FakeApi.md @@ -678,7 +678,7 @@ No authorization required # **TestEndpointParameters** -> void TestEndpointParameters (decimal number, double _double, string patternWithoutDelimiter, byte[] _byte, int? integer = null, int? int32 = null, long? int64 = null, float? _float = null, string _string = null, System.IO.Stream binary = null, DateTime? date = null, DateTime? dateTime = null, string password = null, string callback = null) +> void TestEndpointParameters (decimal number, double _double, string patternWithoutDelimiter, byte[] _byte, int? integer = null, int? int32 = null, long? int64 = null, float? _float = null, string _string = null, FileParameter binary = null, DateTime? date = null, DateTime? dateTime = null, string password = null, string callback = null) Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 @@ -718,7 +718,7 @@ namespace Example var int64 = 789; // long? | None (optional) var _float = 3.4F; // float? | None (optional) var _string = _string_example; // string | None (optional) - var binary = BINARY_DATA_HERE; // System.IO.Stream | None (optional) + var binary = BINARY_DATA_HERE; // FileParameter | None (optional) var date = 2013-10-20; // DateTime? | None (optional) var dateTime = 2013-10-20T19:20:30+01:00; // DateTime? | None (optional) (default to "2010-02-01T10:20:10.111110+01:00") var password = password_example; // string | None (optional) @@ -753,7 +753,7 @@ Name | Type | Description | Notes **int64** | **long?**| None | [optional] **_float** | **float?**| None | [optional] **_string** | **string**| None | [optional] - **binary** | **System.IO.Stream****System.IO.Stream**| None | [optional] + **binary** | **FileParameter****FileParameter**| None | [optional] **date** | **DateTime?**| None | [optional] **dateTime** | **DateTime?**| None | [optional] [default to "2010-02-01T10:20:10.111110+01:00"] **password** | **string**| None | [optional] diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/docs/FormatTest.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/docs/FormatTest.md index 39a70be7ad4..505dbad52df 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/docs/FormatTest.md +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/docs/FormatTest.md @@ -13,7 +13,7 @@ Name | Type | Description | Notes **Decimal** | **decimal** | | [optional] **String** | **string** | | [optional] **Byte** | **byte[]** | | -**Binary** | **System.IO.Stream** | | [optional] +**Binary** | [**FileParameter**](FileParameter.md) | | [optional] **Date** | **DateTime** | | **DateTime** | **DateTime** | | [optional] **Uuid** | **Guid** | | [optional] diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/docs/PetApi.md b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/docs/PetApi.md index 9f4ec108d05..02d0e8e111a 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/docs/PetApi.md +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/docs/PetApi.md @@ -565,7 +565,7 @@ void (empty response body) # **UploadFile** -> ApiResponse UploadFile (long petId, string additionalMetadata = null, System.IO.Stream file = null) +> ApiResponse UploadFile (long petId, string additionalMetadata = null, FileParameter file = null) uploads an image @@ -595,7 +595,7 @@ namespace Example var apiInstance = new PetApi(httpClient, config, httpClientHandler); var petId = 789; // long | ID of pet to update var additionalMetadata = additionalMetadata_example; // string | Additional data to pass to server (optional) - var file = BINARY_DATA_HERE; // System.IO.Stream | file to upload (optional) + var file = BINARY_DATA_HERE; // FileParameter | file to upload (optional) try { @@ -620,7 +620,7 @@ Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **petId** | **long**| ID of pet to update | **additionalMetadata** | **string**| Additional data to pass to server | [optional] - **file** | **System.IO.Stream****System.IO.Stream**| file to upload | [optional] + **file** | **FileParameter****FileParameter**| file to upload | [optional] ### Return type @@ -645,7 +645,7 @@ Name | Type | Description | Notes # **UploadFileWithRequiredFile** -> ApiResponse UploadFileWithRequiredFile (long petId, System.IO.Stream requiredFile, string additionalMetadata = null) +> ApiResponse UploadFileWithRequiredFile (long petId, FileParameter requiredFile, string additionalMetadata = null) uploads an image (required) @@ -674,7 +674,7 @@ namespace Example HttpClientHandler httpClientHandler = new HttpClientHandler(); var apiInstance = new PetApi(httpClient, config, httpClientHandler); var petId = 789; // long | ID of pet to update - var requiredFile = BINARY_DATA_HERE; // System.IO.Stream | file to upload + var requiredFile = BINARY_DATA_HERE; // FileParameter | file to upload var additionalMetadata = additionalMetadata_example; // string | Additional data to pass to server (optional) try @@ -699,7 +699,7 @@ namespace Example Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **petId** | **long**| ID of pet to update | - **requiredFile** | **System.IO.Stream****System.IO.Stream**| file to upload | + **requiredFile** | **FileParameter****FileParameter**| file to upload | **additionalMetadata** | **string**| Additional data to pass to server | [optional] ### Return type diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Api/AnotherFakeApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Api/AnotherFakeApi.cs index 8498781b05c..e12e4f11ae6 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Api/AnotherFakeApi.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Api/AnotherFakeApi.cs @@ -116,7 +116,7 @@ namespace Org.OpenAPITools.Api /// The target service's base path in URL format. /// /// - public AnotherFakeApi(String basePath) + public AnotherFakeApi(string basePath) { this.Configuration = Org.OpenAPITools.Client.Configuration.MergeConfigurations( Org.OpenAPITools.Client.GlobalConfiguration.Instance, @@ -178,7 +178,7 @@ namespace Org.OpenAPITools.Api /// Some configuration settings will not be applied without passing an HttpClientHandler. /// The features affected are: Setting and Retrieving Cookies, Client Certificates, Proxy settings. /// - public AnotherFakeApi(HttpClient client, String basePath, HttpClientHandler handler = null) + public AnotherFakeApi(HttpClient client, string basePath, HttpClientHandler handler = null) { if (client == null) throw new ArgumentNullException("client"); @@ -266,7 +266,7 @@ namespace Org.OpenAPITools.Api /// Gets the base path of the API client. /// /// The base path - public String GetBasePath() + public string GetBasePath() { return this.Configuration.BasePath; } @@ -319,12 +319,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/json" }; @@ -378,12 +378,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/json" }; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Api/DefaultApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Api/DefaultApi.cs index 299f2875b21..f9443fab762 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Api/DefaultApi.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Api/DefaultApi.cs @@ -109,7 +109,7 @@ namespace Org.OpenAPITools.Api /// The target service's base path in URL format. /// /// - public DefaultApi(String basePath) + public DefaultApi(string basePath) { this.Configuration = Org.OpenAPITools.Client.Configuration.MergeConfigurations( Org.OpenAPITools.Client.GlobalConfiguration.Instance, @@ -171,7 +171,7 @@ namespace Org.OpenAPITools.Api /// Some configuration settings will not be applied without passing an HttpClientHandler. /// The features affected are: Setting and Retrieving Cookies, Client Certificates, Proxy settings. /// - public DefaultApi(HttpClient client, String basePath, HttpClientHandler handler = null) + public DefaultApi(HttpClient client, string basePath, HttpClientHandler handler = null) { if (client == null) throw new ArgumentNullException("client"); @@ -259,7 +259,7 @@ namespace Org.OpenAPITools.Api /// Gets the base path of the API client. /// /// The base path - public String GetBasePath() + public string GetBasePath() { return this.Configuration.BasePath; } @@ -306,11 +306,11 @@ namespace Org.OpenAPITools.Api { Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/json" }; @@ -357,11 +357,11 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/json" }; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Api/FakeApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Api/FakeApi.cs index 66f86c619fc..9a2358e3f4c 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Api/FakeApi.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Api/FakeApi.cs @@ -227,7 +227,7 @@ namespace Org.OpenAPITools.Api /// None (optional) /// None (optional) /// - void TestEndpointParameters(decimal number, double _double, string patternWithoutDelimiter, byte[] _byte, int? integer = default(int?), int? int32 = default(int?), long? int64 = default(long?), float? _float = default(float?), string _string = 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)); + void TestEndpointParameters(decimal number, double _double, string patternWithoutDelimiter, byte[] _byte, int? integer = default(int?), int? int32 = default(int?), long? int64 = default(long?), float? _float = default(float?), string _string = default(string), FileParameter binary = default(FileParameter), DateTime? date = default(DateTime?), DateTime? dateTime = default(DateTime?), string password = default(string), string callback = default(string)); /// /// Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 @@ -251,7 +251,7 @@ namespace Org.OpenAPITools.Api /// None (optional) /// None (optional) /// ApiResponse of Object(void) - ApiResponse TestEndpointParametersWithHttpInfo(decimal number, double _double, string patternWithoutDelimiter, byte[] _byte, int? integer = default(int?), int? int32 = default(int?), long? int64 = default(long?), float? _float = default(float?), string _string = 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)); + ApiResponse TestEndpointParametersWithHttpInfo(decimal number, double _double, string patternWithoutDelimiter, byte[] _byte, int? integer = default(int?), int? int32 = default(int?), long? int64 = default(long?), float? _float = default(float?), string _string = default(string), FileParameter binary = default(FileParameter), DateTime? date = default(DateTime?), DateTime? dateTime = default(DateTime?), string password = default(string), string callback = default(string)); /// /// To test enum parameters /// @@ -622,7 +622,7 @@ namespace Org.OpenAPITools.Api /// None (optional) /// Cancellation Token to cancel the request. /// Task of void - System.Threading.Tasks.Task TestEndpointParametersAsync(decimal number, double _double, string patternWithoutDelimiter, byte[] _byte, int? integer = default(int?), int? int32 = default(int?), long? int64 = default(long?), float? _float = default(float?), string _string = 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), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + System.Threading.Tasks.Task TestEndpointParametersAsync(decimal number, double _double, string patternWithoutDelimiter, byte[] _byte, int? integer = default(int?), int? int32 = default(int?), long? int64 = default(long?), float? _float = default(float?), string _string = default(string), FileParameter binary = default(FileParameter), DateTime? date = default(DateTime?), DateTime? dateTime = default(DateTime?), string password = default(string), string callback = default(string), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// /// Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 @@ -647,7 +647,7 @@ namespace Org.OpenAPITools.Api /// None (optional) /// Cancellation Token to cancel the request. /// Task of ApiResponse - System.Threading.Tasks.Task> TestEndpointParametersWithHttpInfoAsync(decimal number, double _double, string patternWithoutDelimiter, byte[] _byte, int? integer = default(int?), int? int32 = default(int?), long? int64 = default(long?), float? _float = default(float?), string _string = 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), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + System.Threading.Tasks.Task> TestEndpointParametersWithHttpInfoAsync(decimal number, double _double, string patternWithoutDelimiter, byte[] _byte, int? integer = default(int?), int? int32 = default(int?), long? int64 = default(long?), float? _float = default(float?), string _string = default(string), FileParameter binary = default(FileParameter), DateTime? date = default(DateTime?), DateTime? dateTime = default(DateTime?), string password = default(string), string callback = default(string), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// /// To test enum parameters /// @@ -833,7 +833,7 @@ namespace Org.OpenAPITools.Api /// The target service's base path in URL format. /// /// - public FakeApi(String basePath) + public FakeApi(string basePath) { this.Configuration = Org.OpenAPITools.Client.Configuration.MergeConfigurations( Org.OpenAPITools.Client.GlobalConfiguration.Instance, @@ -895,7 +895,7 @@ namespace Org.OpenAPITools.Api /// Some configuration settings will not be applied without passing an HttpClientHandler. /// The features affected are: Setting and Retrieving Cookies, Client Certificates, Proxy settings. /// - public FakeApi(HttpClient client, String basePath, HttpClientHandler handler = null) + public FakeApi(HttpClient client, string basePath, HttpClientHandler handler = null) { if (client == null) throw new ArgumentNullException("client"); @@ -983,7 +983,7 @@ namespace Org.OpenAPITools.Api /// Gets the base path of the API client. /// /// The base path - public String GetBasePath() + public string GetBasePath() { return this.Configuration.BasePath; } @@ -1030,11 +1030,11 @@ namespace Org.OpenAPITools.Api { Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/json" }; @@ -1081,11 +1081,11 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/json" }; @@ -1133,12 +1133,12 @@ namespace Org.OpenAPITools.Api { Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "*/*" }; @@ -1188,12 +1188,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "*/*" }; @@ -1242,12 +1242,12 @@ namespace Org.OpenAPITools.Api { Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "*/*" }; @@ -1297,12 +1297,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "*/*" }; @@ -1351,12 +1351,12 @@ namespace Org.OpenAPITools.Api { Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "*/*" }; @@ -1406,12 +1406,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "*/*" }; @@ -1460,12 +1460,12 @@ namespace Org.OpenAPITools.Api { Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "*/*" }; @@ -1515,12 +1515,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "*/*" }; @@ -1567,11 +1567,11 @@ namespace Org.OpenAPITools.Api { Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/json" }; @@ -1618,11 +1618,11 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/json" }; @@ -1673,12 +1673,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); @@ -1730,12 +1730,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; @@ -1792,12 +1792,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); @@ -1856,12 +1856,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; @@ -1914,12 +1914,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/json" }; @@ -1973,12 +1973,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/json" }; @@ -2024,7 +2024,7 @@ namespace Org.OpenAPITools.Api /// None (optional) /// None (optional) /// - public void TestEndpointParameters(decimal number, double _double, string patternWithoutDelimiter, byte[] _byte, int? integer = default(int?), int? int32 = default(int?), long? int64 = default(long?), float? _float = default(float?), string _string = 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)) + public void TestEndpointParameters(decimal number, double _double, string patternWithoutDelimiter, byte[] _byte, int? integer = default(int?), int? int32 = default(int?), long? int64 = default(long?), float? _float = default(float?), string _string = default(string), FileParameter binary = default(FileParameter), DateTime? date = default(DateTime?), DateTime? dateTime = default(DateTime?), string password = default(string), string callback = default(string)) { TestEndpointParametersWithHttpInfo(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, _string, binary, date, dateTime, password, callback); } @@ -2048,7 +2048,7 @@ namespace Org.OpenAPITools.Api /// None (optional) /// None (optional) /// ApiResponse of Object(void) - public Org.OpenAPITools.Client.ApiResponse TestEndpointParametersWithHttpInfo(decimal number, double _double, string patternWithoutDelimiter, byte[] _byte, int? integer = default(int?), int? int32 = default(int?), long? int64 = default(long?), float? _float = default(float?), string _string = 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)) + public Org.OpenAPITools.Client.ApiResponse TestEndpointParametersWithHttpInfo(decimal number, double _double, string patternWithoutDelimiter, byte[] _byte, int? integer = default(int?), int? int32 = default(int?), long? int64 = default(long?), float? _float = default(float?), string _string = default(string), FileParameter binary = default(FileParameter), DateTime? date = default(DateTime?), DateTime? dateTime = default(DateTime?), string password = default(string), string callback = default(string)) { // verify the required parameter 'patternWithoutDelimiter' is set if (patternWithoutDelimiter == null) @@ -2060,12 +2060,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/x-www-form-urlencoded" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); @@ -2121,7 +2121,7 @@ namespace Org.OpenAPITools.Api // authentication (http_basic_test) required // http basic authentication required - if (!String.IsNullOrEmpty(this.Configuration.Username) || !String.IsNullOrEmpty(this.Configuration.Password)) + if (!string.IsNullOrEmpty(this.Configuration.Username) || !string.IsNullOrEmpty(this.Configuration.Password)) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Basic " + Org.OpenAPITools.Client.ClientUtils.Base64Encode(this.Configuration.Username + ":" + this.Configuration.Password)); } @@ -2158,7 +2158,7 @@ namespace Org.OpenAPITools.Api /// None (optional) /// Cancellation Token to cancel the request. /// Task of void - public async System.Threading.Tasks.Task TestEndpointParametersAsync(decimal number, double _double, string patternWithoutDelimiter, byte[] _byte, int? integer = default(int?), int? int32 = default(int?), long? int64 = default(long?), float? _float = default(float?), string _string = 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), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + public async System.Threading.Tasks.Task TestEndpointParametersAsync(decimal number, double _double, string patternWithoutDelimiter, byte[] _byte, int? integer = default(int?), int? int32 = default(int?), long? int64 = default(long?), float? _float = default(float?), string _string = default(string), FileParameter binary = default(FileParameter), DateTime? date = default(DateTime?), DateTime? dateTime = default(DateTime?), string password = default(string), string callback = default(string), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { await TestEndpointParametersWithHttpInfoAsync(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, _string, binary, date, dateTime, password, callback, cancellationToken).ConfigureAwait(false); } @@ -2183,7 +2183,7 @@ namespace Org.OpenAPITools.Api /// None (optional) /// Cancellation Token to cancel the request. /// Task of ApiResponse - public async System.Threading.Tasks.Task> TestEndpointParametersWithHttpInfoAsync(decimal number, double _double, string patternWithoutDelimiter, byte[] _byte, int? integer = default(int?), int? int32 = default(int?), long? int64 = default(long?), float? _float = default(float?), string _string = 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), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + public async System.Threading.Tasks.Task> TestEndpointParametersWithHttpInfoAsync(decimal number, double _double, string patternWithoutDelimiter, byte[] _byte, int? integer = default(int?), int? int32 = default(int?), long? int64 = default(long?), float? _float = default(float?), string _string = default(string), FileParameter binary = default(FileParameter), DateTime? date = default(DateTime?), DateTime? dateTime = default(DateTime?), string password = default(string), string callback = default(string), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { // verify the required parameter 'patternWithoutDelimiter' is set if (patternWithoutDelimiter == null) @@ -2196,12 +2196,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/x-www-form-urlencoded" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; @@ -2258,7 +2258,7 @@ namespace Org.OpenAPITools.Api // authentication (http_basic_test) required // http basic authentication required - if (!String.IsNullOrEmpty(this.Configuration.Username) || !String.IsNullOrEmpty(this.Configuration.Password)) + if (!string.IsNullOrEmpty(this.Configuration.Username) || !string.IsNullOrEmpty(this.Configuration.Password)) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Basic " + Org.OpenAPITools.Client.ClientUtils.Base64Encode(this.Configuration.Username + ":" + this.Configuration.Password)); } @@ -2311,12 +2311,12 @@ namespace Org.OpenAPITools.Api { Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/x-www-form-urlencoded" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); @@ -2409,12 +2409,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/x-www-form-urlencoded" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; @@ -2502,11 +2502,11 @@ namespace Org.OpenAPITools.Api { Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); @@ -2533,7 +2533,7 @@ namespace Org.OpenAPITools.Api // authentication (bearer_test) required // bearer authentication required - if (!String.IsNullOrEmpty(this.Configuration.AccessToken)) + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); } @@ -2584,11 +2584,11 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; @@ -2616,7 +2616,7 @@ namespace Org.OpenAPITools.Api // authentication (bearer_test) required // bearer authentication required - if (!String.IsNullOrEmpty(this.Configuration.AccessToken)) + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); } @@ -2659,12 +2659,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); @@ -2716,12 +2716,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; @@ -2778,12 +2778,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/x-www-form-urlencoded" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); @@ -2842,12 +2842,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/x-www-form-urlencoded" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; @@ -2923,11 +2923,11 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); @@ -3007,11 +3007,11 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Api/FakeClassnameTags123Api.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Api/FakeClassnameTags123Api.cs index efec560791e..47d80c96307 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Api/FakeClassnameTags123Api.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Api/FakeClassnameTags123Api.cs @@ -116,7 +116,7 @@ namespace Org.OpenAPITools.Api /// The target service's base path in URL format. /// /// - public FakeClassnameTags123Api(String basePath) + public FakeClassnameTags123Api(string basePath) { this.Configuration = Org.OpenAPITools.Client.Configuration.MergeConfigurations( Org.OpenAPITools.Client.GlobalConfiguration.Instance, @@ -178,7 +178,7 @@ namespace Org.OpenAPITools.Api /// Some configuration settings will not be applied without passing an HttpClientHandler. /// The features affected are: Setting and Retrieving Cookies, Client Certificates, Proxy settings. /// - public FakeClassnameTags123Api(HttpClient client, String basePath, HttpClientHandler handler = null) + public FakeClassnameTags123Api(HttpClient client, string basePath, HttpClientHandler handler = null) { if (client == null) throw new ArgumentNullException("client"); @@ -266,7 +266,7 @@ namespace Org.OpenAPITools.Api /// Gets the base path of the API client. /// /// The base path - public String GetBasePath() + public string GetBasePath() { return this.Configuration.BasePath; } @@ -319,12 +319,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/json" }; @@ -337,7 +337,7 @@ namespace Org.OpenAPITools.Api localVarRequestOptions.Data = modelClient; // authentication (api_key_query) required - if (!String.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("api_key_query"))) + 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"))); } @@ -383,12 +383,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/json" }; @@ -402,7 +402,7 @@ namespace Org.OpenAPITools.Api localVarRequestOptions.Data = modelClient; // authentication (api_key_query) required - if (!String.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("api_key_query"))) + 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"))); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Api/PetApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Api/PetApi.cs index 7f9a79b6bb3..f835c81b4d5 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Api/PetApi.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Api/PetApi.cs @@ -176,7 +176,7 @@ namespace Org.OpenAPITools.Api /// Additional data to pass to server (optional) /// file to upload (optional) /// ApiResponse - ApiResponse UploadFile(long petId, string additionalMetadata = default(string), System.IO.Stream file = default(System.IO.Stream)); + ApiResponse UploadFile(long petId, string additionalMetadata = default(string), FileParameter file = default(FileParameter)); /// /// uploads an image @@ -189,7 +189,7 @@ namespace Org.OpenAPITools.Api /// Additional data to pass to server (optional) /// file to upload (optional) /// ApiResponse of ApiResponse - ApiResponse UploadFileWithHttpInfo(long petId, string additionalMetadata = default(string), System.IO.Stream file = default(System.IO.Stream)); + ApiResponse UploadFileWithHttpInfo(long petId, string additionalMetadata = default(string), FileParameter file = default(FileParameter)); /// /// uploads an image (required) /// @@ -198,7 +198,7 @@ namespace Org.OpenAPITools.Api /// file to upload /// Additional data to pass to server (optional) /// ApiResponse - ApiResponse UploadFileWithRequiredFile(long petId, System.IO.Stream requiredFile, string additionalMetadata = default(string)); + ApiResponse UploadFileWithRequiredFile(long petId, FileParameter requiredFile, string additionalMetadata = default(string)); /// /// uploads an image (required) @@ -211,7 +211,7 @@ namespace Org.OpenAPITools.Api /// file to upload /// Additional data to pass to server (optional) /// ApiResponse of ApiResponse - ApiResponse UploadFileWithRequiredFileWithHttpInfo(long petId, System.IO.Stream requiredFile, string additionalMetadata = default(string)); + ApiResponse UploadFileWithRequiredFileWithHttpInfo(long petId, FileParameter requiredFile, string additionalMetadata = default(string)); #endregion Synchronous Operations } @@ -400,7 +400,7 @@ namespace Org.OpenAPITools.Api /// file to upload (optional) /// Cancellation Token to cancel the request. /// Task of ApiResponse - System.Threading.Tasks.Task UploadFileAsync(long petId, string additionalMetadata = default(string), System.IO.Stream file = default(System.IO.Stream), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + System.Threading.Tasks.Task UploadFileAsync(long petId, string additionalMetadata = default(string), FileParameter file = default(FileParameter), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// /// uploads an image @@ -414,7 +414,7 @@ namespace Org.OpenAPITools.Api /// file to upload (optional) /// Cancellation Token to cancel the request. /// Task of ApiResponse (ApiResponse) - System.Threading.Tasks.Task> UploadFileWithHttpInfoAsync(long petId, string additionalMetadata = default(string), System.IO.Stream file = default(System.IO.Stream), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + System.Threading.Tasks.Task> UploadFileWithHttpInfoAsync(long petId, string additionalMetadata = default(string), FileParameter file = default(FileParameter), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// /// uploads an image (required) /// @@ -427,7 +427,7 @@ namespace Org.OpenAPITools.Api /// Additional data to pass to server (optional) /// Cancellation Token to cancel the request. /// Task of ApiResponse - System.Threading.Tasks.Task UploadFileWithRequiredFileAsync(long petId, System.IO.Stream requiredFile, string additionalMetadata = default(string), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + System.Threading.Tasks.Task UploadFileWithRequiredFileAsync(long petId, FileParameter requiredFile, string additionalMetadata = default(string), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// /// uploads an image (required) @@ -441,7 +441,7 @@ namespace Org.OpenAPITools.Api /// Additional data to pass to server (optional) /// Cancellation Token to cancel the request. /// Task of ApiResponse (ApiResponse) - System.Threading.Tasks.Task> UploadFileWithRequiredFileWithHttpInfoAsync(long petId, System.IO.Stream requiredFile, string additionalMetadata = default(string), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + System.Threading.Tasks.Task> UploadFileWithRequiredFileWithHttpInfoAsync(long petId, FileParameter requiredFile, string additionalMetadata = default(string), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); #endregion Asynchronous Operations } @@ -478,7 +478,7 @@ namespace Org.OpenAPITools.Api /// The target service's base path in URL format. /// /// - public PetApi(String basePath) + public PetApi(string basePath) { this.Configuration = Org.OpenAPITools.Client.Configuration.MergeConfigurations( Org.OpenAPITools.Client.GlobalConfiguration.Instance, @@ -540,7 +540,7 @@ namespace Org.OpenAPITools.Api /// Some configuration settings will not be applied without passing an HttpClientHandler. /// The features affected are: Setting and Retrieving Cookies, Client Certificates, Proxy settings. /// - public PetApi(HttpClient client, String basePath, HttpClientHandler handler = null) + public PetApi(HttpClient client, string basePath, HttpClientHandler handler = null) { if (client == null) throw new ArgumentNullException("client"); @@ -628,7 +628,7 @@ namespace Org.OpenAPITools.Api /// Gets the base path of the API client. /// /// The base path - public String GetBasePath() + public string GetBasePath() { return this.Configuration.BasePath; } @@ -680,13 +680,13 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json", "application/xml" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); @@ -715,7 +715,7 @@ namespace Org.OpenAPITools.Api } // authentication (petstore_auth) required // oauth required - if (!String.IsNullOrEmpty(this.Configuration.AccessToken)) + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); } @@ -760,13 +760,13 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json", "application/xml" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; @@ -796,7 +796,7 @@ namespace Org.OpenAPITools.Api } // authentication (petstore_auth) required // oauth required - if (!String.IsNullOrEmpty(this.Configuration.AccessToken)) + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); } @@ -837,11 +837,11 @@ namespace Org.OpenAPITools.Api { Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); @@ -858,7 +858,7 @@ namespace Org.OpenAPITools.Api // authentication (petstore_auth) required // oauth required - if (!String.IsNullOrEmpty(this.Configuration.AccessToken)) + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); } @@ -901,11 +901,11 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; @@ -923,7 +923,7 @@ namespace Org.OpenAPITools.Api // authentication (petstore_auth) required // oauth required - if (!String.IsNullOrEmpty(this.Configuration.AccessToken)) + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); } @@ -967,11 +967,11 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/xml", "application/json" }; @@ -1002,7 +1002,7 @@ namespace Org.OpenAPITools.Api } // authentication (petstore_auth) required // oauth required - if (!String.IsNullOrEmpty(this.Configuration.AccessToken)) + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); } @@ -1048,11 +1048,11 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/xml", "application/json" }; @@ -1084,7 +1084,7 @@ namespace Org.OpenAPITools.Api } // authentication (petstore_auth) required // oauth required - if (!String.IsNullOrEmpty(this.Configuration.AccessToken)) + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); } @@ -1128,11 +1128,11 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/xml", "application/json" }; @@ -1163,7 +1163,7 @@ namespace Org.OpenAPITools.Api } // authentication (petstore_auth) required // oauth required - if (!String.IsNullOrEmpty(this.Configuration.AccessToken)) + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); } @@ -1209,11 +1209,11 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/xml", "application/json" }; @@ -1245,7 +1245,7 @@ namespace Org.OpenAPITools.Api } // authentication (petstore_auth) required // oauth required - if (!String.IsNullOrEmpty(this.Configuration.AccessToken)) + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); } @@ -1285,11 +1285,11 @@ namespace Org.OpenAPITools.Api { Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/xml", "application/json" }; @@ -1303,7 +1303,7 @@ namespace Org.OpenAPITools.Api localVarRequestOptions.PathParameters.Add("petId", Org.OpenAPITools.Client.ClientUtils.ParameterToString(petId)); // path parameter // authentication (api_key) required - if (!String.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("api_key"))) + if (!string.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("api_key"))) { localVarRequestOptions.HeaderParameters.Add("api_key", this.Configuration.GetApiKeyWithPrefix("api_key")); } @@ -1345,11 +1345,11 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/xml", "application/json" }; @@ -1364,7 +1364,7 @@ namespace Org.OpenAPITools.Api localVarRequestOptions.PathParameters.Add("petId", Org.OpenAPITools.Client.ClientUtils.ParameterToString(petId)); // path parameter // authentication (api_key) required - if (!String.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("api_key"))) + if (!string.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("api_key"))) { localVarRequestOptions.HeaderParameters.Add("api_key", this.Configuration.GetApiKeyWithPrefix("api_key")); } @@ -1407,13 +1407,13 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json", "application/xml" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); @@ -1442,7 +1442,7 @@ namespace Org.OpenAPITools.Api } // authentication (petstore_auth) required // oauth required - if (!String.IsNullOrEmpty(this.Configuration.AccessToken)) + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); } @@ -1487,13 +1487,13 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json", "application/xml" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; @@ -1523,7 +1523,7 @@ namespace Org.OpenAPITools.Api } // authentication (petstore_auth) required // oauth required - if (!String.IsNullOrEmpty(this.Configuration.AccessToken)) + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); } @@ -1566,12 +1566,12 @@ namespace Org.OpenAPITools.Api { Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/x-www-form-urlencoded" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); @@ -1592,7 +1592,7 @@ namespace Org.OpenAPITools.Api // authentication (petstore_auth) required // oauth required - if (!String.IsNullOrEmpty(this.Configuration.AccessToken)) + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); } @@ -1637,12 +1637,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/x-www-form-urlencoded" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; @@ -1664,7 +1664,7 @@ namespace Org.OpenAPITools.Api // authentication (petstore_auth) required // oauth required - if (!String.IsNullOrEmpty(this.Configuration.AccessToken)) + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); } @@ -1690,7 +1690,7 @@ namespace Org.OpenAPITools.Api /// Additional data to pass to server (optional) /// file to upload (optional) /// ApiResponse - public ApiResponse UploadFile(long petId, string additionalMetadata = default(string), System.IO.Stream file = default(System.IO.Stream)) + public ApiResponse UploadFile(long petId, string additionalMetadata = default(string), FileParameter file = default(FileParameter)) { Org.OpenAPITools.Client.ApiResponse localVarResponse = UploadFileWithHttpInfo(petId, additionalMetadata, file); return localVarResponse.Data; @@ -1704,16 +1704,16 @@ namespace Org.OpenAPITools.Api /// Additional data to pass to server (optional) /// file to upload (optional) /// ApiResponse of ApiResponse - public Org.OpenAPITools.Client.ApiResponse UploadFileWithHttpInfo(long petId, string additionalMetadata = default(string), System.IO.Stream file = default(System.IO.Stream)) + public Org.OpenAPITools.Client.ApiResponse UploadFileWithHttpInfo(long petId, string additionalMetadata = default(string), FileParameter file = default(FileParameter)) { Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "multipart/form-data" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/json" }; @@ -1735,7 +1735,7 @@ namespace Org.OpenAPITools.Api // authentication (petstore_auth) required // oauth required - if (!String.IsNullOrEmpty(this.Configuration.AccessToken)) + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); } @@ -1761,7 +1761,7 @@ namespace Org.OpenAPITools.Api /// file to upload (optional) /// Cancellation Token to cancel the request. /// Task of ApiResponse - public async System.Threading.Tasks.Task UploadFileAsync(long petId, string additionalMetadata = default(string), System.IO.Stream file = default(System.IO.Stream), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + public async System.Threading.Tasks.Task UploadFileAsync(long petId, string additionalMetadata = default(string), FileParameter file = default(FileParameter), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { Org.OpenAPITools.Client.ApiResponse localVarResponse = await UploadFileWithHttpInfoAsync(petId, additionalMetadata, file, cancellationToken).ConfigureAwait(false); return localVarResponse.Data; @@ -1776,17 +1776,17 @@ namespace Org.OpenAPITools.Api /// file to upload (optional) /// Cancellation Token to cancel the request. /// Task of ApiResponse (ApiResponse) - public async System.Threading.Tasks.Task> UploadFileWithHttpInfoAsync(long petId, string additionalMetadata = default(string), System.IO.Stream file = default(System.IO.Stream), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + public async System.Threading.Tasks.Task> UploadFileWithHttpInfoAsync(long petId, string additionalMetadata = default(string), FileParameter file = default(FileParameter), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "multipart/form-data" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/json" }; @@ -1809,7 +1809,7 @@ namespace Org.OpenAPITools.Api // authentication (petstore_auth) required // oauth required - if (!String.IsNullOrEmpty(this.Configuration.AccessToken)) + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); } @@ -1835,7 +1835,7 @@ namespace Org.OpenAPITools.Api /// file to upload /// Additional data to pass to server (optional) /// ApiResponse - public ApiResponse UploadFileWithRequiredFile(long petId, System.IO.Stream requiredFile, string additionalMetadata = default(string)) + public ApiResponse UploadFileWithRequiredFile(long petId, FileParameter requiredFile, string additionalMetadata = default(string)) { Org.OpenAPITools.Client.ApiResponse localVarResponse = UploadFileWithRequiredFileWithHttpInfo(petId, requiredFile, additionalMetadata); return localVarResponse.Data; @@ -1849,7 +1849,7 @@ namespace Org.OpenAPITools.Api /// file to upload /// Additional data to pass to server (optional) /// ApiResponse of ApiResponse - public Org.OpenAPITools.Client.ApiResponse UploadFileWithRequiredFileWithHttpInfo(long petId, System.IO.Stream requiredFile, string additionalMetadata = default(string)) + public Org.OpenAPITools.Client.ApiResponse UploadFileWithRequiredFileWithHttpInfo(long petId, FileParameter requiredFile, string additionalMetadata = default(string)) { // verify the required parameter 'requiredFile' is set if (requiredFile == null) @@ -1857,12 +1857,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "multipart/form-data" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/json" }; @@ -1881,7 +1881,7 @@ namespace Org.OpenAPITools.Api // authentication (petstore_auth) required // oauth required - if (!String.IsNullOrEmpty(this.Configuration.AccessToken)) + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); } @@ -1907,7 +1907,7 @@ namespace Org.OpenAPITools.Api /// Additional data to pass to server (optional) /// Cancellation Token to cancel the request. /// Task of ApiResponse - public async System.Threading.Tasks.Task UploadFileWithRequiredFileAsync(long petId, System.IO.Stream requiredFile, string additionalMetadata = default(string), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + public async System.Threading.Tasks.Task UploadFileWithRequiredFileAsync(long petId, FileParameter requiredFile, string additionalMetadata = default(string), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { Org.OpenAPITools.Client.ApiResponse localVarResponse = await UploadFileWithRequiredFileWithHttpInfoAsync(petId, requiredFile, additionalMetadata, cancellationToken).ConfigureAwait(false); return localVarResponse.Data; @@ -1922,7 +1922,7 @@ namespace Org.OpenAPITools.Api /// Additional data to pass to server (optional) /// Cancellation Token to cancel the request. /// Task of ApiResponse (ApiResponse) - public async System.Threading.Tasks.Task> UploadFileWithRequiredFileWithHttpInfoAsync(long petId, System.IO.Stream requiredFile, string additionalMetadata = default(string), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + public async System.Threading.Tasks.Task> UploadFileWithRequiredFileWithHttpInfoAsync(long petId, FileParameter requiredFile, string additionalMetadata = default(string), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { // verify the required parameter 'requiredFile' is set if (requiredFile == null) @@ -1931,12 +1931,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "multipart/form-data" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/json" }; @@ -1956,7 +1956,7 @@ namespace Org.OpenAPITools.Api // authentication (petstore_auth) required // oauth required - if (!String.IsNullOrEmpty(this.Configuration.AccessToken)) + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Api/StoreApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Api/StoreApi.cs index d7b0b43698a..c4775513db3 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Api/StoreApi.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Api/StoreApi.cs @@ -241,7 +241,7 @@ namespace Org.OpenAPITools.Api /// The target service's base path in URL format. /// /// - public StoreApi(String basePath) + public StoreApi(string basePath) { this.Configuration = Org.OpenAPITools.Client.Configuration.MergeConfigurations( Org.OpenAPITools.Client.GlobalConfiguration.Instance, @@ -303,7 +303,7 @@ namespace Org.OpenAPITools.Api /// Some configuration settings will not be applied without passing an HttpClientHandler. /// The features affected are: Setting and Retrieving Cookies, Client Certificates, Proxy settings. /// - public StoreApi(HttpClient client, String basePath, HttpClientHandler handler = null) + public StoreApi(HttpClient client, string basePath, HttpClientHandler handler = null) { if (client == null) throw new ArgumentNullException("client"); @@ -391,7 +391,7 @@ namespace Org.OpenAPITools.Api /// Gets the base path of the API client. /// /// The base path - public String GetBasePath() + public string GetBasePath() { return this.Configuration.BasePath; } @@ -443,11 +443,11 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); @@ -499,11 +499,11 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; @@ -549,11 +549,11 @@ namespace Org.OpenAPITools.Api { Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/json" }; @@ -565,7 +565,7 @@ namespace Org.OpenAPITools.Api // authentication (api_key) required - if (!String.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("api_key"))) + if (!string.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("api_key"))) { localVarRequestOptions.HeaderParameters.Add("api_key", this.Configuration.GetApiKeyWithPrefix("api_key")); } @@ -605,11 +605,11 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/json" }; @@ -622,7 +622,7 @@ namespace Org.OpenAPITools.Api // authentication (api_key) required - if (!String.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("api_key"))) + if (!string.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("api_key"))) { localVarRequestOptions.HeaderParameters.Add("api_key", this.Configuration.GetApiKeyWithPrefix("api_key")); } @@ -662,11 +662,11 @@ namespace Org.OpenAPITools.Api { Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/xml", "application/json" }; @@ -717,11 +717,11 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/xml", "application/json" }; @@ -775,12 +775,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/xml", "application/json" }; @@ -835,12 +835,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/xml", "application/json" }; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Api/UserApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Api/UserApi.cs index 9b4826f955e..889a90d75f2 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Api/UserApi.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Api/UserApi.cs @@ -413,7 +413,7 @@ namespace Org.OpenAPITools.Api /// The target service's base path in URL format. /// /// - public UserApi(String basePath) + public UserApi(string basePath) { this.Configuration = Org.OpenAPITools.Client.Configuration.MergeConfigurations( Org.OpenAPITools.Client.GlobalConfiguration.Instance, @@ -475,7 +475,7 @@ namespace Org.OpenAPITools.Api /// Some configuration settings will not be applied without passing an HttpClientHandler. /// The features affected are: Setting and Retrieving Cookies, Client Certificates, Proxy settings. /// - public UserApi(HttpClient client, String basePath, HttpClientHandler handler = null) + public UserApi(HttpClient client, string basePath, HttpClientHandler handler = null) { if (client == null) throw new ArgumentNullException("client"); @@ -563,7 +563,7 @@ namespace Org.OpenAPITools.Api /// Gets the base path of the API client. /// /// The base path - public String GetBasePath() + public string GetBasePath() { return this.Configuration.BasePath; } @@ -615,12 +615,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); @@ -672,12 +672,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; @@ -728,12 +728,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); @@ -785,12 +785,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; @@ -841,12 +841,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); @@ -898,12 +898,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; @@ -954,11 +954,11 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); @@ -1010,11 +1010,11 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; @@ -1066,11 +1066,11 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/xml", "application/json" }; @@ -1125,11 +1125,11 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/xml", "application/json" }; @@ -1189,11 +1189,11 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/xml", "application/json" }; @@ -1255,11 +1255,11 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/xml", "application/json" }; @@ -1307,11 +1307,11 @@ namespace Org.OpenAPITools.Api { Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); @@ -1356,11 +1356,11 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; @@ -1416,12 +1416,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); @@ -1480,12 +1480,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Client/ApiClient.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Client/ApiClient.cs index 526a4311117..364fe9d25aa 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Client/ApiClient.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Client/ApiClient.cs @@ -80,9 +80,9 @@ namespace Org.OpenAPITools.Client } } - public T Deserialize(HttpResponseMessage response) + public async Task Deserialize(HttpResponseMessage response) { - var result = (T)Deserialize(response, typeof(T)); + var result = (T) await Deserialize(response, typeof(T)); return result; } @@ -92,22 +92,22 @@ namespace Org.OpenAPITools.Client /// The HTTP response. /// Object type. /// Object representation of the JSON string. - internal object Deserialize(HttpResponseMessage response, Type type) + internal async Task Deserialize(HttpResponseMessage response, Type type) { IList headers = response.Headers.Select(x => x.Key + "=" + x.Value).ToList(); if (type == typeof(byte[])) // return byte array { - return response.Content.ReadAsByteArrayAsync().GetAwaiter().GetResult(); + return await response.Content.ReadAsByteArrayAsync(); } // TODO: ? if (type.IsAssignableFrom(typeof(Stream))) if (type == typeof(Stream)) { - var bytes = response.Content.ReadAsByteArrayAsync().GetAwaiter().GetResult(); + var bytes = await response.Content.ReadAsByteArrayAsync(); if (headers != null) { - var filePath = String.IsNullOrEmpty(_configuration.TempFolderPath) + var filePath = string.IsNullOrEmpty(_configuration.TempFolderPath) ? Path.GetTempPath() : _configuration.TempFolderPath; var regex = new Regex(@"Content-Disposition=.*filename=['""]?([^'""\s]+)['""]?$"); @@ -128,18 +128,18 @@ namespace Org.OpenAPITools.Client if (type.Name.StartsWith("System.Nullable`1[[System.DateTime")) // return a datetime object { - return DateTime.Parse(response.Content.ReadAsStringAsync().GetAwaiter().GetResult(), null, System.Globalization.DateTimeStyles.RoundtripKind); + return DateTime.Parse(await response.Content.ReadAsStringAsync(), null, System.Globalization.DateTimeStyles.RoundtripKind); } - if (type == typeof(String) || type.Name.StartsWith("System.Nullable")) // return primitive type + if (type == typeof(string) || type.Name.StartsWith("System.Nullable")) // return primitive type { - return Convert.ChangeType(response.Content.ReadAsStringAsync().GetAwaiter().GetResult(), type); + return Convert.ChangeType(await response.Content.ReadAsStringAsync(), type); } // at this point, it must be a model (json) try { - return JsonConvert.DeserializeObject(response.Content.ReadAsStringAsync().GetAwaiter().GetResult(), type, _serializerSettings); + return JsonConvert.DeserializeObject(await response.Content.ReadAsStringAsync(), type, _serializerSettings); } catch (Exception e) { @@ -166,7 +166,7 @@ namespace Org.OpenAPITools.Client /// public partial class ApiClient : IDisposable, ISynchronousClient, IAsynchronousClient { - private readonly String _baseUrl; + private readonly string _baseUrl; private readonly HttpClientHandler _httpClientHandler; private readonly HttpClient _httpClient; @@ -206,7 +206,7 @@ namespace Org.OpenAPITools.Client /// /// The target service's base path in URL format. /// - public ApiClient(String basePath) + public ApiClient(string basePath) { if (string.IsNullOrEmpty(basePath)) throw new ArgumentException("basePath cannot be empty"); @@ -243,7 +243,7 @@ namespace Org.OpenAPITools.Client /// Some configuration settings will not be applied without passing an HttpClientHandler. /// The features affected are: Setting and Retrieving Cookies, Client Certificates, Proxy settings. /// - public ApiClient(HttpClient client, String basePath, HttpClientHandler handler = null) + public ApiClient(HttpClient client, string basePath, HttpClientHandler handler = null) { if (client == null) throw new ArgumentNullException("client cannot be null"); if (string.IsNullOrEmpty(basePath)) throw new ArgumentException("basePath cannot be empty"); @@ -277,12 +277,10 @@ namespace Org.OpenAPITools.Client { foreach (var fileParam in options.FileParameters) { - var fileStream = fileParam.Value as FileStream; - var fileStreamName = fileStream != null ? System.IO.Path.GetFileName(fileStream.Name) : null; - var content = new StreamContent(fileParam.Value); + var content = new StreamContent(fileParam.Value.Content); content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); multipartContent.Add(content, fileParam.Key, - fileStreamName ?? "no_file_name_provided"); + fileParam.Value.Name); } } return multipartContent; @@ -302,7 +300,7 @@ namespace Org.OpenAPITools.Client /// private HttpRequestMessage NewRequest( HttpMethod method, - String path, + string path, RequestOptions options, IReadableConfiguration configuration) { @@ -314,11 +312,7 @@ namespace Org.OpenAPITools.Client builder.AddPathParameters(options.PathParameters); - // In case of POST or PUT pass query parameters in request body - if (method != HttpMethod.Post && method != HttpMethod.Put) - { - builder.AddQueryParameters(options.QueryParameters); - } + builder.AddQueryParameters(options.QueryParameters); HttpRequestMessage request = new HttpRequestMessage(method, builder.GetFullUri()); @@ -368,11 +362,11 @@ namespace Org.OpenAPITools.Client { if (options.Data != null) { - if (options.Data is Stream s) + if (options.Data is FileParameter fp) { contentType = contentType ?? "application/octet-stream"; - var streamContent = new StreamContent(s); + var streamContent = new StreamContent(fp.Content); streamContent.Headers.ContentType = new MediaTypeHeaderValue(contentType); request.Content = streamContent; } @@ -510,7 +504,7 @@ namespace Org.OpenAPITools.Client return await ToApiResponse(response, default(T), req.RequestUri); } - object responseData = deserializer.Deserialize(response); + object responseData = await deserializer.Deserialize(response); // if the response type is oneOf/anyOf, call FromJSON to deserialize the data if (typeof(Org.OpenAPITools.Model.AbstractOpenAPISchema).IsAssignableFrom(typeof(T))) diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Client/ApiResponse.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Client/ApiResponse.cs index 1b7d787c84b..ca2de833a5a 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Client/ApiResponse.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Client/ApiResponse.cs @@ -44,7 +44,7 @@ namespace Org.OpenAPITools.Client /// /// Gets or sets any error text defined by the calling client. /// - String ErrorText { get; set; } + string ErrorText { get; set; } /// /// Gets or sets any cookies passed along on the response. @@ -85,7 +85,7 @@ namespace Org.OpenAPITools.Client /// /// Gets or sets any error text defined by the calling client. /// - public String ErrorText { get; set; } + public string ErrorText { get; set; } /// /// Gets or sets any cookies passed along on the response. diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Client/ClientUtils.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Client/ClientUtils.cs index 2b6e52d6065..3d038d5ce69 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Client/ClientUtils.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Client/ClientUtils.cs @@ -124,7 +124,7 @@ namespace Org.OpenAPITools.Client /// URL encode a string /// Credit/Ref: https://github.com/restsharp/RestSharp/blob/master/RestSharp/Extensions/StringExtensions.cs#L50 /// - /// String to be URL encoded + /// string to be URL encoded /// Byte array public static string UrlEncode(string input) { @@ -158,7 +158,7 @@ namespace Org.OpenAPITools.Client /// /// Encode string in base64 format. /// - /// String to be encoded. + /// string to be encoded. /// Encoded string. public static string Base64Encode(string text) { @@ -186,7 +186,7 @@ namespace Org.OpenAPITools.Client /// /// The Content-Type array to select from. /// The Content-Type header to use. - public static String SelectHeaderContentType(String[] contentTypes) + public static string SelectHeaderContentType(string[] contentTypes) { if (contentTypes.Length == 0) return null; @@ -207,7 +207,7 @@ namespace Org.OpenAPITools.Client /// /// The accepts array to select from. /// The Accept header to use. - public static String SelectHeaderAccept(String[] accepts) + public static string SelectHeaderAccept(string[] accepts) { if (accepts.Length == 0) return null; @@ -215,7 +215,7 @@ namespace Org.OpenAPITools.Client if (accepts.Contains("application/json", StringComparer.OrdinalIgnoreCase)) return "application/json"; - return String.Join(",", accepts); + return string.Join(",", accepts); } /// @@ -233,9 +233,9 @@ namespace Org.OpenAPITools.Client /// /// MIME /// Returns True if MIME type is json. - public static bool IsJsonMime(String mime) + public static bool IsJsonMime(string mime) { - if (String.IsNullOrWhiteSpace(mime)) return false; + if (string.IsNullOrWhiteSpace(mime)) return false; return JsonRegex.IsMatch(mime) || mime.Equals("application/json-patch+json"); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Client/Configuration.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Client/Configuration.cs index bca7db624cd..06154ad382c 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Client/Configuration.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Client/Configuration.cs @@ -67,7 +67,7 @@ namespace Org.OpenAPITools.Client /// Defines the base path of the target API server. /// Example: http://localhost:3000/v1/ /// - private String _basePath; + private string _basePath; /// /// Gets or sets the API key based on the authentication name. @@ -511,9 +511,9 @@ namespace Org.OpenAPITools.Client /// /// Returns a string with essential information for debugging. /// - public static String ToDebugReport() + public static string ToDebugReport() { - String report = "C# SDK (Org.OpenAPITools) Debug Report:\n"; + 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"; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Client/FileParameter.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Client/FileParameter.cs new file mode 100644 index 00000000000..4a83ada8588 --- /dev/null +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Client/FileParameter.cs @@ -0,0 +1,62 @@ +/* + * 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.IO; + +namespace Org.OpenAPITools.Client +{ + + /// + /// Represents a File passed to the API as a Parameter, allows using different backends for files + /// + public class FileParameter + { + /// + /// The filename + /// + public string Name { get; set; } = "no_name_provided"; + + /// + /// The content of the file + /// + public Stream Content { get; set; } + + /// + /// Construct a FileParameter just from the contents, will extract the filename from a filestream + /// + /// The file content + public FileParameter(Stream content) + { + if (content is FileStream fs) + { + Name = fs.Name; + } + Content = content; + } + + /// + /// Construct a FileParameter from name and content + /// + /// The filename + /// The file content + public FileParameter(string filename, Stream content) + { + Name = filename; + Content = content; + } + + /// + /// Implicit conversion of stream to file parameter. Useful for backwards compatibility. + /// + /// Stream to convert + /// FileParameter + public static implicit operator FileParameter(Stream s) => new FileParameter(s); + } +} \ No newline at end of file diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Client/HttpSigningConfiguration.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Client/HttpSigningConfiguration.cs index 1b9f9b7a99f..1d2d0019cae 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Client/HttpSigningConfiguration.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Client/HttpSigningConfiguration.cs @@ -120,7 +120,7 @@ namespace Org.OpenAPITools.Client } } - var httpValues = HttpUtility.ParseQueryString(String.Empty); + var httpValues = HttpUtility.ParseQueryString(string.Empty); foreach (var parameter in requestOptions.QueryParameters) { #if (NETCOREAPP) @@ -153,7 +153,7 @@ namespace Org.OpenAPITools.Client uriBuilder.Query = httpValues.ToString().Replace("+", "%20"); var dateTime = DateTime.Now; - String Digest = String.Empty; + string Digest = string.Empty; //get the body string requestBody = string.Empty; @@ -230,7 +230,7 @@ namespace Org.OpenAPITools.Client } } - var headersKeysString = String.Join(" ", HttpSignatureHeader.Keys); + var headersKeysString = string.Join(" ", HttpSignatureHeader.Keys); var headerValuesList = new List(); foreach (var keyVal in HttpSignatureHeader) @@ -411,10 +411,10 @@ namespace Org.OpenAPITools.Client return derBytes.ToArray(); } - private RSACryptoServiceProvider GetRSAProviderFromPemFile(String pemfile, SecureString keyPassPharse = null) + private RSACryptoServiceProvider GetRSAProviderFromPemFile(string pemfile, SecureString keyPassPharse = null) { - const String pempubheader = "-----BEGIN PUBLIC KEY-----"; - const String pempubfooter = "-----END PUBLIC KEY-----"; + const string pempubheader = "-----BEGIN PUBLIC KEY-----"; + const string pempubfooter = "-----END PUBLIC KEY-----"; bool isPrivateKeyFile = true; byte[] pemkey = null; @@ -441,11 +441,11 @@ namespace Org.OpenAPITools.Client return null; } - private byte[] ConvertPrivateKeyToBytes(String instr, SecureString keyPassPharse = null) + private byte[] ConvertPrivateKeyToBytes(string instr, SecureString keyPassPharse = null) { - const String pemprivheader = "-----BEGIN RSA PRIVATE KEY-----"; - const String pemprivfooter = "-----END RSA PRIVATE KEY-----"; - String pemstr = instr.Trim(); + 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)) @@ -456,7 +456,7 @@ namespace Org.OpenAPITools.Client StringBuilder sb = new StringBuilder(pemstr); sb.Replace(pemprivheader, ""); sb.Replace(pemprivfooter, ""); - String pvkstr = sb.ToString().Trim(); + string pvkstr = sb.ToString().Trim(); try { // if there are no PEM encryption info lines, this is an UNencrypted PEM private key @@ -472,12 +472,12 @@ namespace Org.OpenAPITools.Client { return null; } - String saltline = str.ReadLine(); + string saltline = str.ReadLine(); if (!saltline.StartsWith("DEK-Info: DES-EDE3-CBC,")) { return null; } - String saltstr = saltline.Substring(saltline.IndexOf(",") + 1).Trim(); + 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); @@ -487,7 +487,7 @@ namespace Org.OpenAPITools.Client } //------ remaining b64 data is encrypted RSA key ---- - String encryptedstr = str.ReadToEnd(); + string encryptedstr = str.ReadToEnd(); try { //should have b64 encrypted RSA key now diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Client/IApiAccessor.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Client/IApiAccessor.cs index 59465ae8e90..2bd76416004 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Client/IApiAccessor.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Client/IApiAccessor.cs @@ -27,7 +27,7 @@ namespace Org.OpenAPITools.Client /// Gets the base path of the API client. /// /// The base path - String GetBasePath(); + string GetBasePath(); /// /// Provides a factory method hook for the creation of exceptions. diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Client/IAsynchronousClient.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Client/IAsynchronousClient.cs index 8a6f726678a..601e86d561c 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Client/IAsynchronousClient.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Client/IAsynchronousClient.cs @@ -29,7 +29,7 @@ namespace Org.OpenAPITools.Client /// 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)); + 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. @@ -40,7 +40,7 @@ namespace Org.OpenAPITools.Client /// 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)); + 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. @@ -51,7 +51,7 @@ namespace Org.OpenAPITools.Client /// 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)); + 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. @@ -62,7 +62,7 @@ namespace Org.OpenAPITools.Client /// 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)); + 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. @@ -73,7 +73,7 @@ namespace Org.OpenAPITools.Client /// 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)); + 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. @@ -84,7 +84,7 @@ namespace Org.OpenAPITools.Client /// 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)); + 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. @@ -95,6 +95,6 @@ namespace Org.OpenAPITools.Client /// 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)); + Task> PatchAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Client/ISynchronousClient.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Client/ISynchronousClient.cs index d27f01a588b..0e0a7fedacf 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Client/ISynchronousClient.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Client/ISynchronousClient.cs @@ -28,7 +28,7 @@ namespace Org.OpenAPITools.Client /// Per-request configurable settings. /// The return type. /// The response data, decorated with - ApiResponse Get(String path, RequestOptions options, IReadableConfiguration configuration = null); + ApiResponse Get(string path, RequestOptions options, IReadableConfiguration configuration = null); /// /// Executes a blocking call to some using the POST http verb. @@ -38,7 +38,7 @@ namespace Org.OpenAPITools.Client /// Per-request configurable settings. /// The return type. /// The response data, decorated with - ApiResponse Post(String path, RequestOptions options, IReadableConfiguration configuration = null); + ApiResponse Post(string path, RequestOptions options, IReadableConfiguration configuration = null); /// /// Executes a blocking call to some using the PUT http verb. @@ -48,7 +48,7 @@ namespace Org.OpenAPITools.Client /// Per-request configurable settings. /// The return type. /// The response data, decorated with - ApiResponse Put(String path, RequestOptions options, IReadableConfiguration configuration = null); + ApiResponse Put(string path, RequestOptions options, IReadableConfiguration configuration = null); /// /// Executes a blocking call to some using the DELETE http verb. @@ -58,7 +58,7 @@ namespace Org.OpenAPITools.Client /// Per-request configurable settings. /// The return type. /// The response data, decorated with - ApiResponse Delete(String path, RequestOptions options, IReadableConfiguration configuration = null); + ApiResponse Delete(string path, RequestOptions options, IReadableConfiguration configuration = null); /// /// Executes a blocking call to some using the HEAD http verb. @@ -68,7 +68,7 @@ namespace Org.OpenAPITools.Client /// Per-request configurable settings. /// The return type. /// The response data, decorated with - ApiResponse Head(String path, RequestOptions options, IReadableConfiguration configuration = null); + ApiResponse Head(string path, RequestOptions options, IReadableConfiguration configuration = null); /// /// Executes a blocking call to some using the OPTIONS http verb. @@ -78,7 +78,7 @@ namespace Org.OpenAPITools.Client /// Per-request configurable settings. /// The return type. /// The response data, decorated with - ApiResponse Options(String path, RequestOptions options, IReadableConfiguration configuration = null); + ApiResponse Options(string path, RequestOptions options, IReadableConfiguration configuration = null); /// /// Executes a blocking call to some using the PATCH http verb. @@ -88,6 +88,6 @@ namespace Org.OpenAPITools.Client /// Per-request configurable settings. /// The return type. /// The response data, decorated with - ApiResponse Patch(String path, RequestOptions options, IReadableConfiguration configuration = null); + ApiResponse Patch(string path, RequestOptions options, IReadableConfiguration configuration = null); } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Client/RequestOptions.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Client/RequestOptions.cs index d8da585db9c..91a5fbf28f3 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Client/RequestOptions.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Client/RequestOptions.cs @@ -24,29 +24,29 @@ namespace Org.OpenAPITools.Client /// /// Parameters to be bound to path parts of the Request's URL /// - public Dictionary PathParameters { get; set; } + 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; } + public Multimap QueryParameters { get; set; } /// /// Header parameters to be applied to to the request. /// Keys may have 1 or more values associated. /// - public Multimap HeaderParameters { get; set; } + public Multimap HeaderParameters { get; set; } /// /// Form parameters to be sent along with the request. /// - public Dictionary FormParameters { get; set; } + public Dictionary FormParameters { get; set; } /// /// File parameters to be sent along with the request. /// - public Dictionary FileParameters { get; set; } + public Dictionary FileParameters { get; set; } /// /// Cookies to be sent along with the request. @@ -67,8 +67,8 @@ namespace Org.OpenAPITools.Client QueryParameters = new Multimap(); HeaderParameters = new Multimap(); FormParameters = new Dictionary(); - FileParameters = new Dictionary(); + FileParameters = new Dictionary(); Cookies = new List(); } } -} \ No newline at end of file +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/AdditionalPropertiesClass.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/AdditionalPropertiesClass.cs index 5f212ec734f..5c88c5a5ce9 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/AdditionalPropertiesClass.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/AdditionalPropertiesClass.cs @@ -21,6 +21,7 @@ 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; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Animal.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Animal.cs index 95c79122ad7..c39799127da 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Animal.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Animal.cs @@ -22,6 +22,7 @@ using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using JsonSubTypes; using System.ComponentModel.DataAnnotations; +using FileParameter = Org.OpenAPITools.Client.FileParameter; using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ApiResponse.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ApiResponse.cs index c9a0a78efa7..5a990e9f881 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ApiResponse.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ApiResponse.cs @@ -21,6 +21,7 @@ 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; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Apple.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Apple.cs index b414d3021a6..d52db06ca2e 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Apple.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Apple.cs @@ -21,6 +21,7 @@ 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; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/AppleReq.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/AppleReq.cs index a1203358492..3354d6a5932 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/AppleReq.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/AppleReq.cs @@ -21,6 +21,7 @@ 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; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ArrayOfArrayOfNumberOnly.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ArrayOfArrayOfNumberOnly.cs index bf2c8663ff6..52f424010d5 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ArrayOfArrayOfNumberOnly.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ArrayOfArrayOfNumberOnly.cs @@ -21,6 +21,7 @@ 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; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ArrayOfNumberOnly.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ArrayOfNumberOnly.cs index 09a9bbb8850..da6a1f50200 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ArrayOfNumberOnly.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ArrayOfNumberOnly.cs @@ -21,6 +21,7 @@ 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; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ArrayTest.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ArrayTest.cs index 4406ffb33ea..3b9b986b9ae 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ArrayTest.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ArrayTest.cs @@ -21,6 +21,7 @@ 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; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Banana.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Banana.cs index a7513bb453a..630ae7ecf0d 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Banana.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Banana.cs @@ -21,6 +21,7 @@ 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; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/BananaReq.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/BananaReq.cs index 4a52e918a46..0a22d500b13 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/BananaReq.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/BananaReq.cs @@ -21,6 +21,7 @@ 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; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/BasquePig.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/BasquePig.cs index 5c6f9a0e83d..ade2a65ef24 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/BasquePig.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/BasquePig.cs @@ -21,6 +21,7 @@ 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; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Capitalization.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Capitalization.cs index a4ab27bd898..1ca2387e23c 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Capitalization.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Capitalization.cs @@ -21,6 +21,7 @@ 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; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Cat.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Cat.cs index 3fd19648bb9..e62e22180fe 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Cat.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Cat.cs @@ -22,6 +22,7 @@ using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using JsonSubTypes; using System.ComponentModel.DataAnnotations; +using FileParameter = Org.OpenAPITools.Client.FileParameter; using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/CatAllOf.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/CatAllOf.cs index 8d61cf77b64..c47a05d16c2 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/CatAllOf.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/CatAllOf.cs @@ -21,6 +21,7 @@ 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; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Category.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Category.cs index 581a23ef2a5..35dd2674695 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Category.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Category.cs @@ -21,6 +21,7 @@ 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; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ChildCat.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ChildCat.cs index e883d3d20bb..66e6c4ec0ee 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ChildCat.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ChildCat.cs @@ -22,6 +22,7 @@ using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using JsonSubTypes; using System.ComponentModel.DataAnnotations; +using FileParameter = Org.OpenAPITools.Client.FileParameter; using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ChildCatAllOf.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ChildCatAllOf.cs index 36268a8093a..5c28c73530c 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ChildCatAllOf.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ChildCatAllOf.cs @@ -21,6 +21,7 @@ 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; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ClassModel.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ClassModel.cs index bb2121cd517..52cedf0979d 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ClassModel.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ClassModel.cs @@ -21,6 +21,7 @@ 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; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ComplexQuadrilateral.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ComplexQuadrilateral.cs index 78f3c6c03e3..cccb856a650 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ComplexQuadrilateral.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ComplexQuadrilateral.cs @@ -21,6 +21,7 @@ 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; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/DanishPig.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/DanishPig.cs index dd2de1d038a..68bf604b95f 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/DanishPig.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/DanishPig.cs @@ -21,6 +21,7 @@ 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; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Dog.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Dog.cs index 1ff9ab1624d..5abe5bc73b3 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Dog.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Dog.cs @@ -22,6 +22,7 @@ using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using JsonSubTypes; using System.ComponentModel.DataAnnotations; +using FileParameter = Org.OpenAPITools.Client.FileParameter; using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/DogAllOf.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/DogAllOf.cs index cd2f1a0eeec..b33fdf12c68 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/DogAllOf.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/DogAllOf.cs @@ -21,6 +21,7 @@ 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; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Drawing.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Drawing.cs index 28e2ea55693..7240327f31e 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Drawing.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Drawing.cs @@ -21,6 +21,7 @@ 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; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/EnumArrays.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/EnumArrays.cs index be9b0c5e801..ca4515c95da 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/EnumArrays.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/EnumArrays.cs @@ -21,6 +21,7 @@ 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; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/EnumClass.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/EnumClass.cs index 48b3d7d0e7e..324fb5fba89 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/EnumClass.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/EnumClass.cs @@ -21,6 +21,7 @@ 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; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/EnumTest.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/EnumTest.cs index c9c56e18386..a5135a7f39a 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/EnumTest.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/EnumTest.cs @@ -21,6 +21,7 @@ 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; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/EquilateralTriangle.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/EquilateralTriangle.cs index ed443f68cf7..751b3b8a99a 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/EquilateralTriangle.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/EquilateralTriangle.cs @@ -21,6 +21,7 @@ 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; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/File.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/File.cs index af4a38ae023..81bd9c7fbef 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/File.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/File.cs @@ -21,6 +21,7 @@ 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; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/FileSchemaTestClass.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/FileSchemaTestClass.cs index cc6b3e34c5d..1195e665650 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/FileSchemaTestClass.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/FileSchemaTestClass.cs @@ -21,6 +21,7 @@ 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; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Foo.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Foo.cs index 83637468119..b1fa5a8fa43 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Foo.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Foo.cs @@ -21,6 +21,7 @@ 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; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/FormatTest.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/FormatTest.cs index 9e7466bb502..c2dd5cc4d71 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/FormatTest.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/FormatTest.cs @@ -21,6 +21,7 @@ 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; @@ -59,7 +60,7 @@ namespace Org.OpenAPITools.Model /// password (required). /// 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.. - public FormatTest(int integer = default(int), int int32 = default(int), long int64 = default(long), decimal number = default(decimal), float _float = default(float), double _double = default(double), decimal _decimal = default(decimal), string _string = default(string), byte[] _byte = 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)) + public FormatTest(int integer = default(int), int int32 = default(int), long int64 = default(long), decimal number = default(decimal), float _float = default(float), double _double = default(double), decimal _decimal = default(decimal), string _string = default(string), byte[] _byte = default(byte[]), FileParameter binary = default(FileParameter), DateTime date = default(DateTime), DateTime dateTime = default(DateTime), Guid uuid = default(Guid), string password = default(string), string patternWithDigits = default(string), string patternWithDigitsAndDelimiter = default(string)) { this.Number = number; // to ensure "_byte" is required (not null) @@ -140,7 +141,7 @@ namespace Org.OpenAPITools.Model /// Gets or Sets Binary /// [DataMember(Name = "binary", EmitDefaultValue = false)] - public System.IO.Stream Binary { get; set; } + public FileParameter Binary { get; set; } /// /// Gets or Sets Date diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Fruit.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Fruit.cs index 132be5b4d3b..6c0b8d06cfa 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Fruit.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Fruit.cs @@ -21,6 +21,7 @@ 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; using System.Reflection; @@ -162,7 +163,7 @@ namespace Org.OpenAPITools.Model catch (Exception exception) { // deserialization failed, try the next one - System.Diagnostics.Debug.WriteLine(String.Format("Failed to deserialize `{0}` into Apple: {1}", jsonString, exception.ToString())); + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into Apple: {1}", jsonString, exception.ToString())); } try @@ -182,7 +183,7 @@ namespace Org.OpenAPITools.Model catch (Exception exception) { // deserialization failed, try the next one - System.Diagnostics.Debug.WriteLine(String.Format("Failed to deserialize `{0}` into Banana: {1}", jsonString, exception.ToString())); + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into Banana: {1}", jsonString, exception.ToString())); } if (match == 0) @@ -257,7 +258,7 @@ namespace Org.OpenAPITools.Model /// JSON Serializer public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { - writer.WriteRawValue((String)(typeof(Fruit).GetMethod("ToJson").Invoke(value, null))); + writer.WriteRawValue((string)(typeof(Fruit).GetMethod("ToJson").Invoke(value, null))); } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/FruitReq.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/FruitReq.cs index 380896933df..207a851e23f 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/FruitReq.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/FruitReq.cs @@ -21,6 +21,7 @@ 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; using System.Reflection; @@ -171,7 +172,7 @@ namespace Org.OpenAPITools.Model catch (Exception exception) { // deserialization failed, try the next one - System.Diagnostics.Debug.WriteLine(String.Format("Failed to deserialize `{0}` into AppleReq: {1}", jsonString, exception.ToString())); + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into AppleReq: {1}", jsonString, exception.ToString())); } try @@ -191,7 +192,7 @@ namespace Org.OpenAPITools.Model catch (Exception exception) { // deserialization failed, try the next one - System.Diagnostics.Debug.WriteLine(String.Format("Failed to deserialize `{0}` into BananaReq: {1}", jsonString, exception.ToString())); + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into BananaReq: {1}", jsonString, exception.ToString())); } if (match == 0) @@ -266,7 +267,7 @@ namespace Org.OpenAPITools.Model /// JSON Serializer public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { - writer.WriteRawValue((String)(typeof(FruitReq).GetMethod("ToJson").Invoke(value, null))); + writer.WriteRawValue((string)(typeof(FruitReq).GetMethod("ToJson").Invoke(value, null))); } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/GmFruit.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/GmFruit.cs index c168aa41d4c..49a39c4747e 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/GmFruit.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/GmFruit.cs @@ -21,6 +21,7 @@ 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; @@ -151,7 +152,7 @@ namespace Org.OpenAPITools.Model catch (Exception exception) { // deserialization failed, try the next one - System.Diagnostics.Debug.WriteLine(String.Format("Failed to deserialize `{0}` into Apple: {1}", jsonString, exception.ToString())); + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into Apple: {1}", jsonString, exception.ToString())); } try @@ -163,7 +164,7 @@ namespace Org.OpenAPITools.Model catch (Exception exception) { // deserialization failed, try the next one - System.Diagnostics.Debug.WriteLine(String.Format("Failed to deserialize `{0}` into Banana: {1}", jsonString, exception.ToString())); + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into Banana: {1}", jsonString, exception.ToString())); } // no match found, throw an exception @@ -229,7 +230,7 @@ namespace Org.OpenAPITools.Model /// JSON Serializer public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { - writer.WriteRawValue((String)(typeof(GmFruit).GetMethod("ToJson").Invoke(value, null))); + writer.WriteRawValue((string)(typeof(GmFruit).GetMethod("ToJson").Invoke(value, null))); } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/GrandparentAnimal.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/GrandparentAnimal.cs index 9352d27022f..129aae28554 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/GrandparentAnimal.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/GrandparentAnimal.cs @@ -22,6 +22,7 @@ using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using JsonSubTypes; using System.ComponentModel.DataAnnotations; +using FileParameter = Org.OpenAPITools.Client.FileParameter; using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/HasOnlyReadOnly.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/HasOnlyReadOnly.cs index 3a2c3d26a92..c212df1374a 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/HasOnlyReadOnly.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/HasOnlyReadOnly.cs @@ -21,6 +21,7 @@ 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; @@ -55,7 +56,6 @@ namespace Org.OpenAPITools.Model { return false; } - /// /// Gets or Sets Foo /// @@ -70,7 +70,6 @@ namespace Org.OpenAPITools.Model { return false; } - /// /// Gets or Sets additional properties /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/HealthCheckResult.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/HealthCheckResult.cs index 1cd90560cbe..e6b4399e926 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/HealthCheckResult.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/HealthCheckResult.cs @@ -21,6 +21,7 @@ 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; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/InlineResponseDefault.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/InlineResponseDefault.cs index 5f4b24acafa..0352d11ac24 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/InlineResponseDefault.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/InlineResponseDefault.cs @@ -21,6 +21,7 @@ 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; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/IsoscelesTriangle.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/IsoscelesTriangle.cs index 46963173f71..a7416acf77b 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/IsoscelesTriangle.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/IsoscelesTriangle.cs @@ -21,6 +21,7 @@ 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; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/List.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/List.cs index ecf4e8ff00e..10cd9420a74 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/List.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/List.cs @@ -21,6 +21,7 @@ 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; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Mammal.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Mammal.cs index 2e847a10eb6..fb62820cbd2 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Mammal.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Mammal.cs @@ -22,6 +22,7 @@ using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using JsonSubTypes; using System.ComponentModel.DataAnnotations; +using FileParameter = Org.OpenAPITools.Client.FileParameter; using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; using System.Reflection; @@ -183,7 +184,7 @@ namespace Org.OpenAPITools.Model newMammal = new Mammal(JsonConvert.DeserializeObject(jsonString, Mammal.AdditionalPropertiesSerializerSettings)); return newMammal; default: - System.Diagnostics.Debug.WriteLine(String.Format("Failed to lookup discriminator value `{0}` for Mammal. Possible values: Pig whale zebra", discriminatorValue)); + System.Diagnostics.Debug.WriteLine(string.Format("Failed to lookup discriminator value `{0}` for Mammal. Possible values: Pig whale zebra", discriminatorValue)); break; } @@ -207,7 +208,7 @@ namespace Org.OpenAPITools.Model catch (Exception exception) { // deserialization failed, try the next one - System.Diagnostics.Debug.WriteLine(String.Format("Failed to deserialize `{0}` into Pig: {1}", jsonString, exception.ToString())); + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into Pig: {1}", jsonString, exception.ToString())); } try @@ -227,7 +228,7 @@ namespace Org.OpenAPITools.Model catch (Exception exception) { // deserialization failed, try the next one - System.Diagnostics.Debug.WriteLine(String.Format("Failed to deserialize `{0}` into Whale: {1}", jsonString, exception.ToString())); + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into Whale: {1}", jsonString, exception.ToString())); } try @@ -247,7 +248,7 @@ namespace Org.OpenAPITools.Model catch (Exception exception) { // deserialization failed, try the next one - System.Diagnostics.Debug.WriteLine(String.Format("Failed to deserialize `{0}` into Zebra: {1}", jsonString, exception.ToString())); + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into Zebra: {1}", jsonString, exception.ToString())); } if (match == 0) @@ -322,7 +323,7 @@ namespace Org.OpenAPITools.Model /// JSON Serializer public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { - writer.WriteRawValue((String)(typeof(Mammal).GetMethod("ToJson").Invoke(value, null))); + writer.WriteRawValue((string)(typeof(Mammal).GetMethod("ToJson").Invoke(value, null))); } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/MapTest.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/MapTest.cs index b88cfef72c1..76f2c995a93 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/MapTest.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/MapTest.cs @@ -21,6 +21,7 @@ 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; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/MixedPropertiesAndAdditionalPropertiesClass.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/MixedPropertiesAndAdditionalPropertiesClass.cs index dc3d45a080a..88d8e6493d9 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/MixedPropertiesAndAdditionalPropertiesClass.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/MixedPropertiesAndAdditionalPropertiesClass.cs @@ -21,6 +21,7 @@ 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; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Model200Response.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Model200Response.cs index b1e76d25081..50eb434c96d 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Model200Response.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Model200Response.cs @@ -21,6 +21,7 @@ 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; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ModelClient.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ModelClient.cs index 4ee431a9b2f..744bda61564 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ModelClient.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ModelClient.cs @@ -21,6 +21,7 @@ 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; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Name.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Name.cs index a6a01dd4ed3..020b46d015b 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Name.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Name.cs @@ -21,6 +21,7 @@ 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; @@ -72,7 +73,6 @@ namespace Org.OpenAPITools.Model { return false; } - /// /// Gets or Sets Property /// @@ -93,7 +93,6 @@ namespace Org.OpenAPITools.Model { return false; } - /// /// Gets or Sets additional properties /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/NullableClass.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/NullableClass.cs index 4ceaab61bc6..f3fdf07243c 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/NullableClass.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/NullableClass.cs @@ -21,6 +21,7 @@ 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; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/NullableShape.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/NullableShape.cs index 80339ebf79b..bb16eee3501 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/NullableShape.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/NullableShape.cs @@ -22,6 +22,7 @@ using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using JsonSubTypes; using System.ComponentModel.DataAnnotations; +using FileParameter = Org.OpenAPITools.Client.FileParameter; using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; using System.Reflection; @@ -163,7 +164,7 @@ namespace Org.OpenAPITools.Model newNullableShape = new NullableShape(JsonConvert.DeserializeObject(jsonString, NullableShape.AdditionalPropertiesSerializerSettings)); return newNullableShape; default: - System.Diagnostics.Debug.WriteLine(String.Format("Failed to lookup discriminator value `{0}` for NullableShape. Possible values: Quadrilateral Triangle", discriminatorValue)); + System.Diagnostics.Debug.WriteLine(string.Format("Failed to lookup discriminator value `{0}` for NullableShape. Possible values: Quadrilateral Triangle", discriminatorValue)); break; } @@ -187,7 +188,7 @@ namespace Org.OpenAPITools.Model catch (Exception exception) { // deserialization failed, try the next one - System.Diagnostics.Debug.WriteLine(String.Format("Failed to deserialize `{0}` into Quadrilateral: {1}", jsonString, exception.ToString())); + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into Quadrilateral: {1}", jsonString, exception.ToString())); } try @@ -207,7 +208,7 @@ namespace Org.OpenAPITools.Model catch (Exception exception) { // deserialization failed, try the next one - System.Diagnostics.Debug.WriteLine(String.Format("Failed to deserialize `{0}` into Triangle: {1}", jsonString, exception.ToString())); + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into Triangle: {1}", jsonString, exception.ToString())); } if (match == 0) @@ -282,7 +283,7 @@ namespace Org.OpenAPITools.Model /// JSON Serializer public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { - writer.WriteRawValue((String)(typeof(NullableShape).GetMethod("ToJson").Invoke(value, null))); + writer.WriteRawValue((string)(typeof(NullableShape).GetMethod("ToJson").Invoke(value, null))); } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/NumberOnly.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/NumberOnly.cs index e9b006094cf..3932b5404ee 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/NumberOnly.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/NumberOnly.cs @@ -21,6 +21,7 @@ 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; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Order.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Order.cs index 4f327640915..d7a06f4eef8 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Order.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Order.cs @@ -21,6 +21,7 @@ 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; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/OuterComposite.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/OuterComposite.cs index 1e4e03993e0..c9d3dd0b595 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/OuterComposite.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/OuterComposite.cs @@ -21,6 +21,7 @@ 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; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/OuterEnum.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/OuterEnum.cs index 2aa496a2e07..f3ee68510aa 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/OuterEnum.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/OuterEnum.cs @@ -21,6 +21,7 @@ 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; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/OuterEnumDefaultValue.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/OuterEnumDefaultValue.cs index dd79c7010d6..60fb98c58dc 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/OuterEnumDefaultValue.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/OuterEnumDefaultValue.cs @@ -21,6 +21,7 @@ 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; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/OuterEnumInteger.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/OuterEnumInteger.cs index 44dc91c700a..8624155f745 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/OuterEnumInteger.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/OuterEnumInteger.cs @@ -21,6 +21,7 @@ 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; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/OuterEnumIntegerDefaultValue.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/OuterEnumIntegerDefaultValue.cs index b927507cf97..5d6d21bf800 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/OuterEnumIntegerDefaultValue.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/OuterEnumIntegerDefaultValue.cs @@ -21,6 +21,7 @@ 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; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ParentPet.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ParentPet.cs index a205b59b6d0..c2c91753d7c 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ParentPet.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ParentPet.cs @@ -22,6 +22,7 @@ using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using JsonSubTypes; using System.ComponentModel.DataAnnotations; +using FileParameter = Org.OpenAPITools.Client.FileParameter; using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Pet.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Pet.cs index db3cdd72606..88c2fb08970 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Pet.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Pet.cs @@ -21,6 +21,7 @@ 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; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Pig.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Pig.cs index d8605861e63..715aeb7327f 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Pig.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Pig.cs @@ -22,6 +22,7 @@ using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using JsonSubTypes; using System.ComponentModel.DataAnnotations; +using FileParameter = Org.OpenAPITools.Client.FileParameter; using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; using System.Reflection; @@ -154,7 +155,7 @@ namespace Org.OpenAPITools.Model newPig = new Pig(JsonConvert.DeserializeObject(jsonString, Pig.AdditionalPropertiesSerializerSettings)); return newPig; default: - System.Diagnostics.Debug.WriteLine(String.Format("Failed to lookup discriminator value `{0}` for Pig. Possible values: BasquePig DanishPig", discriminatorValue)); + System.Diagnostics.Debug.WriteLine(string.Format("Failed to lookup discriminator value `{0}` for Pig. Possible values: BasquePig DanishPig", discriminatorValue)); break; } @@ -178,7 +179,7 @@ namespace Org.OpenAPITools.Model catch (Exception exception) { // deserialization failed, try the next one - System.Diagnostics.Debug.WriteLine(String.Format("Failed to deserialize `{0}` into BasquePig: {1}", jsonString, exception.ToString())); + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into BasquePig: {1}", jsonString, exception.ToString())); } try @@ -198,7 +199,7 @@ namespace Org.OpenAPITools.Model catch (Exception exception) { // deserialization failed, try the next one - System.Diagnostics.Debug.WriteLine(String.Format("Failed to deserialize `{0}` into DanishPig: {1}", jsonString, exception.ToString())); + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into DanishPig: {1}", jsonString, exception.ToString())); } if (match == 0) @@ -273,7 +274,7 @@ namespace Org.OpenAPITools.Model /// JSON Serializer public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { - writer.WriteRawValue((String)(typeof(Pig).GetMethod("ToJson").Invoke(value, null))); + writer.WriteRawValue((string)(typeof(Pig).GetMethod("ToJson").Invoke(value, null))); } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Quadrilateral.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Quadrilateral.cs index 17463ca09a4..7a2c6e8c98e 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Quadrilateral.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Quadrilateral.cs @@ -22,6 +22,7 @@ using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using JsonSubTypes; using System.ComponentModel.DataAnnotations; +using FileParameter = Org.OpenAPITools.Client.FileParameter; using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; using System.Reflection; @@ -154,7 +155,7 @@ namespace Org.OpenAPITools.Model newQuadrilateral = new Quadrilateral(JsonConvert.DeserializeObject(jsonString, Quadrilateral.AdditionalPropertiesSerializerSettings)); return newQuadrilateral; default: - System.Diagnostics.Debug.WriteLine(String.Format("Failed to lookup discriminator value `{0}` for Quadrilateral. Possible values: ComplexQuadrilateral SimpleQuadrilateral", discriminatorValue)); + System.Diagnostics.Debug.WriteLine(string.Format("Failed to lookup discriminator value `{0}` for Quadrilateral. Possible values: ComplexQuadrilateral SimpleQuadrilateral", discriminatorValue)); break; } @@ -178,7 +179,7 @@ namespace Org.OpenAPITools.Model catch (Exception exception) { // deserialization failed, try the next one - System.Diagnostics.Debug.WriteLine(String.Format("Failed to deserialize `{0}` into ComplexQuadrilateral: {1}", jsonString, exception.ToString())); + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into ComplexQuadrilateral: {1}", jsonString, exception.ToString())); } try @@ -198,7 +199,7 @@ namespace Org.OpenAPITools.Model catch (Exception exception) { // deserialization failed, try the next one - System.Diagnostics.Debug.WriteLine(String.Format("Failed to deserialize `{0}` into SimpleQuadrilateral: {1}", jsonString, exception.ToString())); + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into SimpleQuadrilateral: {1}", jsonString, exception.ToString())); } if (match == 0) @@ -273,7 +274,7 @@ namespace Org.OpenAPITools.Model /// JSON Serializer public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { - writer.WriteRawValue((String)(typeof(Quadrilateral).GetMethod("ToJson").Invoke(value, null))); + writer.WriteRawValue((string)(typeof(Quadrilateral).GetMethod("ToJson").Invoke(value, null))); } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/QuadrilateralInterface.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/QuadrilateralInterface.cs index e7727cf856c..555fb636825 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/QuadrilateralInterface.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/QuadrilateralInterface.cs @@ -21,6 +21,7 @@ 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; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ReadOnlyFirst.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ReadOnlyFirst.cs index 4ab8f7d5c6a..93efaf44bf1 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ReadOnlyFirst.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ReadOnlyFirst.cs @@ -21,6 +21,7 @@ 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; @@ -56,7 +57,6 @@ namespace Org.OpenAPITools.Model { return false; } - /// /// Gets or Sets Baz /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Return.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Return.cs index 75e7f1f2530..18802e2b7f1 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Return.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Return.cs @@ -21,6 +21,7 @@ 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; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ScaleneTriangle.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ScaleneTriangle.cs index c539590907c..527bcfab54c 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ScaleneTriangle.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ScaleneTriangle.cs @@ -21,6 +21,7 @@ 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; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Shape.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Shape.cs index e75e0e8b167..9afe7ae6564 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Shape.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Shape.cs @@ -22,6 +22,7 @@ using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using JsonSubTypes; using System.ComponentModel.DataAnnotations; +using FileParameter = Org.OpenAPITools.Client.FileParameter; using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; using System.Reflection; @@ -154,7 +155,7 @@ namespace Org.OpenAPITools.Model newShape = new Shape(JsonConvert.DeserializeObject(jsonString, Shape.AdditionalPropertiesSerializerSettings)); return newShape; default: - System.Diagnostics.Debug.WriteLine(String.Format("Failed to lookup discriminator value `{0}` for Shape. Possible values: Quadrilateral Triangle", discriminatorValue)); + System.Diagnostics.Debug.WriteLine(string.Format("Failed to lookup discriminator value `{0}` for Shape. Possible values: Quadrilateral Triangle", discriminatorValue)); break; } @@ -178,7 +179,7 @@ namespace Org.OpenAPITools.Model catch (Exception exception) { // deserialization failed, try the next one - System.Diagnostics.Debug.WriteLine(String.Format("Failed to deserialize `{0}` into Quadrilateral: {1}", jsonString, exception.ToString())); + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into Quadrilateral: {1}", jsonString, exception.ToString())); } try @@ -198,7 +199,7 @@ namespace Org.OpenAPITools.Model catch (Exception exception) { // deserialization failed, try the next one - System.Diagnostics.Debug.WriteLine(String.Format("Failed to deserialize `{0}` into Triangle: {1}", jsonString, exception.ToString())); + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into Triangle: {1}", jsonString, exception.ToString())); } if (match == 0) @@ -273,7 +274,7 @@ namespace Org.OpenAPITools.Model /// JSON Serializer public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { - writer.WriteRawValue((String)(typeof(Shape).GetMethod("ToJson").Invoke(value, null))); + writer.WriteRawValue((string)(typeof(Shape).GetMethod("ToJson").Invoke(value, null))); } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ShapeInterface.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ShapeInterface.cs index 051100b4e6c..6d2208e202f 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ShapeInterface.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ShapeInterface.cs @@ -21,6 +21,7 @@ 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; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ShapeOrNull.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ShapeOrNull.cs index 7471bafb379..b39f95e0be1 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ShapeOrNull.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ShapeOrNull.cs @@ -22,6 +22,7 @@ using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using JsonSubTypes; using System.ComponentModel.DataAnnotations; +using FileParameter = Org.OpenAPITools.Client.FileParameter; using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; using System.Reflection; @@ -163,7 +164,7 @@ namespace Org.OpenAPITools.Model newShapeOrNull = new ShapeOrNull(JsonConvert.DeserializeObject(jsonString, ShapeOrNull.AdditionalPropertiesSerializerSettings)); return newShapeOrNull; default: - System.Diagnostics.Debug.WriteLine(String.Format("Failed to lookup discriminator value `{0}` for ShapeOrNull. Possible values: Quadrilateral Triangle", discriminatorValue)); + System.Diagnostics.Debug.WriteLine(string.Format("Failed to lookup discriminator value `{0}` for ShapeOrNull. Possible values: Quadrilateral Triangle", discriminatorValue)); break; } @@ -187,7 +188,7 @@ namespace Org.OpenAPITools.Model catch (Exception exception) { // deserialization failed, try the next one - System.Diagnostics.Debug.WriteLine(String.Format("Failed to deserialize `{0}` into Quadrilateral: {1}", jsonString, exception.ToString())); + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into Quadrilateral: {1}", jsonString, exception.ToString())); } try @@ -207,7 +208,7 @@ namespace Org.OpenAPITools.Model catch (Exception exception) { // deserialization failed, try the next one - System.Diagnostics.Debug.WriteLine(String.Format("Failed to deserialize `{0}` into Triangle: {1}", jsonString, exception.ToString())); + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into Triangle: {1}", jsonString, exception.ToString())); } if (match == 0) @@ -282,7 +283,7 @@ namespace Org.OpenAPITools.Model /// JSON Serializer public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { - writer.WriteRawValue((String)(typeof(ShapeOrNull).GetMethod("ToJson").Invoke(value, null))); + writer.WriteRawValue((string)(typeof(ShapeOrNull).GetMethod("ToJson").Invoke(value, null))); } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/SimpleQuadrilateral.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/SimpleQuadrilateral.cs index 5280a0c308a..33787f755a7 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/SimpleQuadrilateral.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/SimpleQuadrilateral.cs @@ -21,6 +21,7 @@ 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; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/SpecialModelName.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/SpecialModelName.cs index 26861d98d34..1023ae9a402 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/SpecialModelName.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/SpecialModelName.cs @@ -21,6 +21,7 @@ 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; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Tag.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Tag.cs index aba43e338be..dce80a7cbc3 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Tag.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Tag.cs @@ -21,6 +21,7 @@ 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; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Triangle.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Triangle.cs index cccaa79a8ff..df5cae1e14f 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Triangle.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Triangle.cs @@ -22,6 +22,7 @@ using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using JsonSubTypes; using System.ComponentModel.DataAnnotations; +using FileParameter = Org.OpenAPITools.Client.FileParameter; using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; using System.Reflection; @@ -183,7 +184,7 @@ namespace Org.OpenAPITools.Model newTriangle = new Triangle(JsonConvert.DeserializeObject(jsonString, Triangle.AdditionalPropertiesSerializerSettings)); return newTriangle; default: - System.Diagnostics.Debug.WriteLine(String.Format("Failed to lookup discriminator value `{0}` for Triangle. Possible values: EquilateralTriangle IsoscelesTriangle ScaleneTriangle", discriminatorValue)); + System.Diagnostics.Debug.WriteLine(string.Format("Failed to lookup discriminator value `{0}` for Triangle. Possible values: EquilateralTriangle IsoscelesTriangle ScaleneTriangle", discriminatorValue)); break; } @@ -207,7 +208,7 @@ namespace Org.OpenAPITools.Model catch (Exception exception) { // deserialization failed, try the next one - System.Diagnostics.Debug.WriteLine(String.Format("Failed to deserialize `{0}` into EquilateralTriangle: {1}", jsonString, exception.ToString())); + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into EquilateralTriangle: {1}", jsonString, exception.ToString())); } try @@ -227,7 +228,7 @@ namespace Org.OpenAPITools.Model catch (Exception exception) { // deserialization failed, try the next one - System.Diagnostics.Debug.WriteLine(String.Format("Failed to deserialize `{0}` into IsoscelesTriangle: {1}", jsonString, exception.ToString())); + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into IsoscelesTriangle: {1}", jsonString, exception.ToString())); } try @@ -247,7 +248,7 @@ namespace Org.OpenAPITools.Model catch (Exception exception) { // deserialization failed, try the next one - System.Diagnostics.Debug.WriteLine(String.Format("Failed to deserialize `{0}` into ScaleneTriangle: {1}", jsonString, exception.ToString())); + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into ScaleneTriangle: {1}", jsonString, exception.ToString())); } if (match == 0) @@ -322,7 +323,7 @@ namespace Org.OpenAPITools.Model /// JSON Serializer public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { - writer.WriteRawValue((String)(typeof(Triangle).GetMethod("ToJson").Invoke(value, null))); + writer.WriteRawValue((string)(typeof(Triangle).GetMethod("ToJson").Invoke(value, null))); } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/TriangleInterface.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/TriangleInterface.cs index 4b7274465ce..66f49d7c2de 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/TriangleInterface.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/TriangleInterface.cs @@ -21,6 +21,7 @@ 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; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/User.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/User.cs index ea24f093e14..532f743af53 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/User.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/User.cs @@ -21,6 +21,7 @@ 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; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Whale.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Whale.cs index 80fbf9c368c..2abe262ebbd 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Whale.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Whale.cs @@ -21,6 +21,7 @@ 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; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Zebra.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Zebra.cs index cfa92d1b708..91dce88b923 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Zebra.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Zebra.cs @@ -21,6 +21,7 @@ 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; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/.openapi-generator/VERSION b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/.openapi-generator/VERSION +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Api/AnotherFakeApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Api/AnotherFakeApi.cs index 94d8b854b0d..ad48306e00c 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Api/AnotherFakeApi.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Api/AnotherFakeApi.cs @@ -109,7 +109,7 @@ namespace Org.OpenAPITools.Api /// Initializes a new instance of the class. /// /// - public AnotherFakeApi(String basePath) + public AnotherFakeApi(string basePath) { this.Configuration = Org.OpenAPITools.Client.Configuration.MergeConfigurations( Org.OpenAPITools.Client.GlobalConfiguration.Instance, @@ -172,7 +172,7 @@ namespace Org.OpenAPITools.Api /// Gets the base path of the API client. /// /// The base path - public String GetBasePath() + public string GetBasePath() { return this.Configuration.BasePath; } @@ -225,12 +225,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/json" }; @@ -284,12 +284,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/json" }; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Api/DefaultApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Api/DefaultApi.cs index 27789c4533a..8844aca4ab7 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Api/DefaultApi.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Api/DefaultApi.cs @@ -102,7 +102,7 @@ namespace Org.OpenAPITools.Api /// Initializes a new instance of the class. /// /// - public DefaultApi(String basePath) + public DefaultApi(string basePath) { this.Configuration = Org.OpenAPITools.Client.Configuration.MergeConfigurations( Org.OpenAPITools.Client.GlobalConfiguration.Instance, @@ -165,7 +165,7 @@ namespace Org.OpenAPITools.Api /// Gets the base path of the API client. /// /// The base path - public String GetBasePath() + public string GetBasePath() { return this.Configuration.BasePath; } @@ -212,11 +212,11 @@ namespace Org.OpenAPITools.Api { Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/json" }; @@ -263,11 +263,11 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/json" }; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Api/FakeApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Api/FakeApi.cs index d7749151314..fe862283f1e 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Api/FakeApi.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Api/FakeApi.cs @@ -826,7 +826,7 @@ namespace Org.OpenAPITools.Api /// Initializes a new instance of the class. /// /// - public FakeApi(String basePath) + public FakeApi(string basePath) { this.Configuration = Org.OpenAPITools.Client.Configuration.MergeConfigurations( Org.OpenAPITools.Client.GlobalConfiguration.Instance, @@ -889,7 +889,7 @@ namespace Org.OpenAPITools.Api /// Gets the base path of the API client. /// /// The base path - public String GetBasePath() + public string GetBasePath() { return this.Configuration.BasePath; } @@ -936,11 +936,11 @@ namespace Org.OpenAPITools.Api { Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/json" }; @@ -987,11 +987,11 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/json" }; @@ -1039,12 +1039,12 @@ namespace Org.OpenAPITools.Api { Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "*/*" }; @@ -1094,12 +1094,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "*/*" }; @@ -1148,12 +1148,12 @@ namespace Org.OpenAPITools.Api { Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "*/*" }; @@ -1203,12 +1203,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "*/*" }; @@ -1257,12 +1257,12 @@ namespace Org.OpenAPITools.Api { Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "*/*" }; @@ -1312,12 +1312,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "*/*" }; @@ -1366,12 +1366,12 @@ namespace Org.OpenAPITools.Api { Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "*/*" }; @@ -1421,12 +1421,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "*/*" }; @@ -1473,11 +1473,11 @@ namespace Org.OpenAPITools.Api { Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/json" }; @@ -1524,11 +1524,11 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/json" }; @@ -1579,12 +1579,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); @@ -1636,12 +1636,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; @@ -1698,12 +1698,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); @@ -1762,12 +1762,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; @@ -1820,12 +1820,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/json" }; @@ -1879,12 +1879,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/json" }; @@ -1966,12 +1966,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/x-www-form-urlencoded" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); @@ -2027,7 +2027,7 @@ namespace Org.OpenAPITools.Api // authentication (http_basic_test) required // http basic authentication required - if (!String.IsNullOrEmpty(this.Configuration.Username) || !String.IsNullOrEmpty(this.Configuration.Password)) + if (!string.IsNullOrEmpty(this.Configuration.Username) || !string.IsNullOrEmpty(this.Configuration.Password)) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Basic " + Org.OpenAPITools.Client.ClientUtils.Base64Encode(this.Configuration.Username + ":" + this.Configuration.Password)); } @@ -2102,12 +2102,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/x-www-form-urlencoded" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; @@ -2164,7 +2164,7 @@ namespace Org.OpenAPITools.Api // authentication (http_basic_test) required // http basic authentication required - if (!String.IsNullOrEmpty(this.Configuration.Username) || !String.IsNullOrEmpty(this.Configuration.Password)) + if (!string.IsNullOrEmpty(this.Configuration.Username) || !string.IsNullOrEmpty(this.Configuration.Password)) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Basic " + Org.OpenAPITools.Client.ClientUtils.Base64Encode(this.Configuration.Username + ":" + this.Configuration.Password)); } @@ -2217,12 +2217,12 @@ namespace Org.OpenAPITools.Api { Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/x-www-form-urlencoded" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); @@ -2315,12 +2315,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/x-www-form-urlencoded" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; @@ -2408,11 +2408,11 @@ namespace Org.OpenAPITools.Api { Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); @@ -2439,7 +2439,7 @@ namespace Org.OpenAPITools.Api // authentication (bearer_test) required // bearer authentication required - if (!String.IsNullOrEmpty(this.Configuration.AccessToken)) + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); } @@ -2490,11 +2490,11 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; @@ -2522,7 +2522,7 @@ namespace Org.OpenAPITools.Api // authentication (bearer_test) required // bearer authentication required - if (!String.IsNullOrEmpty(this.Configuration.AccessToken)) + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); } @@ -2565,12 +2565,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); @@ -2622,12 +2622,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; @@ -2684,12 +2684,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/x-www-form-urlencoded" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); @@ -2748,12 +2748,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/x-www-form-urlencoded" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; @@ -2829,11 +2829,11 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); @@ -2913,11 +2913,11 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Api/FakeClassnameTags123Api.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Api/FakeClassnameTags123Api.cs index 56ebdf5fd10..d4fbb5868ad 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Api/FakeClassnameTags123Api.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Api/FakeClassnameTags123Api.cs @@ -109,7 +109,7 @@ namespace Org.OpenAPITools.Api /// Initializes a new instance of the class. /// /// - public FakeClassnameTags123Api(String basePath) + public FakeClassnameTags123Api(string basePath) { this.Configuration = Org.OpenAPITools.Client.Configuration.MergeConfigurations( Org.OpenAPITools.Client.GlobalConfiguration.Instance, @@ -172,7 +172,7 @@ namespace Org.OpenAPITools.Api /// Gets the base path of the API client. /// /// The base path - public String GetBasePath() + public string GetBasePath() { return this.Configuration.BasePath; } @@ -225,12 +225,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/json" }; @@ -243,7 +243,7 @@ namespace Org.OpenAPITools.Api localVarRequestOptions.Data = modelClient; // authentication (api_key_query) required - if (!String.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("api_key_query"))) + 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"))); } @@ -289,12 +289,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/json" }; @@ -308,7 +308,7 @@ namespace Org.OpenAPITools.Api localVarRequestOptions.Data = modelClient; // authentication (api_key_query) required - if (!String.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("api_key_query"))) + 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"))); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Api/PetApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Api/PetApi.cs index 61759145f12..2bf19af1b1a 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Api/PetApi.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Api/PetApi.cs @@ -471,7 +471,7 @@ namespace Org.OpenAPITools.Api /// Initializes a new instance of the class. /// /// - public PetApi(String basePath) + public PetApi(string basePath) { this.Configuration = Org.OpenAPITools.Client.Configuration.MergeConfigurations( Org.OpenAPITools.Client.GlobalConfiguration.Instance, @@ -534,7 +534,7 @@ namespace Org.OpenAPITools.Api /// Gets the base path of the API client. /// /// The base path - public String GetBasePath() + public string GetBasePath() { return this.Configuration.BasePath; } @@ -586,13 +586,13 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json", "application/xml" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); @@ -621,7 +621,7 @@ namespace Org.OpenAPITools.Api } // authentication (petstore_auth) required // oauth required - if (!String.IsNullOrEmpty(this.Configuration.AccessToken)) + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); } @@ -666,13 +666,13 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json", "application/xml" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; @@ -702,7 +702,7 @@ namespace Org.OpenAPITools.Api } // authentication (petstore_auth) required // oauth required - if (!String.IsNullOrEmpty(this.Configuration.AccessToken)) + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); } @@ -743,11 +743,11 @@ namespace Org.OpenAPITools.Api { Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); @@ -764,7 +764,7 @@ namespace Org.OpenAPITools.Api // authentication (petstore_auth) required // oauth required - if (!String.IsNullOrEmpty(this.Configuration.AccessToken)) + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); } @@ -807,11 +807,11 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; @@ -829,7 +829,7 @@ namespace Org.OpenAPITools.Api // authentication (petstore_auth) required // oauth required - if (!String.IsNullOrEmpty(this.Configuration.AccessToken)) + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); } @@ -873,11 +873,11 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/xml", "application/json" }; @@ -908,7 +908,7 @@ namespace Org.OpenAPITools.Api } // authentication (petstore_auth) required // oauth required - if (!String.IsNullOrEmpty(this.Configuration.AccessToken)) + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); } @@ -954,11 +954,11 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/xml", "application/json" }; @@ -990,7 +990,7 @@ namespace Org.OpenAPITools.Api } // authentication (petstore_auth) required // oauth required - if (!String.IsNullOrEmpty(this.Configuration.AccessToken)) + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); } @@ -1034,11 +1034,11 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/xml", "application/json" }; @@ -1069,7 +1069,7 @@ namespace Org.OpenAPITools.Api } // authentication (petstore_auth) required // oauth required - if (!String.IsNullOrEmpty(this.Configuration.AccessToken)) + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); } @@ -1115,11 +1115,11 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/xml", "application/json" }; @@ -1151,7 +1151,7 @@ namespace Org.OpenAPITools.Api } // authentication (petstore_auth) required // oauth required - if (!String.IsNullOrEmpty(this.Configuration.AccessToken)) + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); } @@ -1191,11 +1191,11 @@ namespace Org.OpenAPITools.Api { Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/xml", "application/json" }; @@ -1209,7 +1209,7 @@ namespace Org.OpenAPITools.Api localVarRequestOptions.PathParameters.Add("petId", Org.OpenAPITools.Client.ClientUtils.ParameterToString(petId)); // path parameter // authentication (api_key) required - if (!String.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("api_key"))) + if (!string.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("api_key"))) { localVarRequestOptions.HeaderParameters.Add("api_key", this.Configuration.GetApiKeyWithPrefix("api_key")); } @@ -1251,11 +1251,11 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/xml", "application/json" }; @@ -1270,7 +1270,7 @@ namespace Org.OpenAPITools.Api localVarRequestOptions.PathParameters.Add("petId", Org.OpenAPITools.Client.ClientUtils.ParameterToString(petId)); // path parameter // authentication (api_key) required - if (!String.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("api_key"))) + if (!string.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("api_key"))) { localVarRequestOptions.HeaderParameters.Add("api_key", this.Configuration.GetApiKeyWithPrefix("api_key")); } @@ -1313,13 +1313,13 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json", "application/xml" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); @@ -1348,7 +1348,7 @@ namespace Org.OpenAPITools.Api } // authentication (petstore_auth) required // oauth required - if (!String.IsNullOrEmpty(this.Configuration.AccessToken)) + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); } @@ -1393,13 +1393,13 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json", "application/xml" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; @@ -1429,7 +1429,7 @@ namespace Org.OpenAPITools.Api } // authentication (petstore_auth) required // oauth required - if (!String.IsNullOrEmpty(this.Configuration.AccessToken)) + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); } @@ -1472,12 +1472,12 @@ namespace Org.OpenAPITools.Api { Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/x-www-form-urlencoded" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); @@ -1498,7 +1498,7 @@ namespace Org.OpenAPITools.Api // authentication (petstore_auth) required // oauth required - if (!String.IsNullOrEmpty(this.Configuration.AccessToken)) + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); } @@ -1543,12 +1543,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/x-www-form-urlencoded" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; @@ -1570,7 +1570,7 @@ namespace Org.OpenAPITools.Api // authentication (petstore_auth) required // oauth required - if (!String.IsNullOrEmpty(this.Configuration.AccessToken)) + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); } @@ -1614,12 +1614,12 @@ namespace Org.OpenAPITools.Api { Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "multipart/form-data" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/json" }; @@ -1641,7 +1641,7 @@ namespace Org.OpenAPITools.Api // authentication (petstore_auth) required // oauth required - if (!String.IsNullOrEmpty(this.Configuration.AccessToken)) + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); } @@ -1687,12 +1687,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "multipart/form-data" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/json" }; @@ -1715,7 +1715,7 @@ namespace Org.OpenAPITools.Api // authentication (petstore_auth) required // oauth required - if (!String.IsNullOrEmpty(this.Configuration.AccessToken)) + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); } @@ -1763,12 +1763,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "multipart/form-data" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/json" }; @@ -1787,7 +1787,7 @@ namespace Org.OpenAPITools.Api // authentication (petstore_auth) required // oauth required - if (!String.IsNullOrEmpty(this.Configuration.AccessToken)) + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); } @@ -1837,12 +1837,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "multipart/form-data" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/json" }; @@ -1862,7 +1862,7 @@ namespace Org.OpenAPITools.Api // authentication (petstore_auth) required // oauth required - if (!String.IsNullOrEmpty(this.Configuration.AccessToken)) + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Api/StoreApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Api/StoreApi.cs index 6ab56c9e9bf..ad7387db705 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Api/StoreApi.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Api/StoreApi.cs @@ -234,7 +234,7 @@ namespace Org.OpenAPITools.Api /// Initializes a new instance of the class. /// /// - public StoreApi(String basePath) + public StoreApi(string basePath) { this.Configuration = Org.OpenAPITools.Client.Configuration.MergeConfigurations( Org.OpenAPITools.Client.GlobalConfiguration.Instance, @@ -297,7 +297,7 @@ namespace Org.OpenAPITools.Api /// Gets the base path of the API client. /// /// The base path - public String GetBasePath() + public string GetBasePath() { return this.Configuration.BasePath; } @@ -349,11 +349,11 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); @@ -405,11 +405,11 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; @@ -455,11 +455,11 @@ namespace Org.OpenAPITools.Api { Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/json" }; @@ -471,7 +471,7 @@ namespace Org.OpenAPITools.Api // authentication (api_key) required - if (!String.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("api_key"))) + if (!string.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("api_key"))) { localVarRequestOptions.HeaderParameters.Add("api_key", this.Configuration.GetApiKeyWithPrefix("api_key")); } @@ -511,11 +511,11 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/json" }; @@ -528,7 +528,7 @@ namespace Org.OpenAPITools.Api // authentication (api_key) required - if (!String.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("api_key"))) + if (!string.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("api_key"))) { localVarRequestOptions.HeaderParameters.Add("api_key", this.Configuration.GetApiKeyWithPrefix("api_key")); } @@ -568,11 +568,11 @@ namespace Org.OpenAPITools.Api { Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/xml", "application/json" }; @@ -623,11 +623,11 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/xml", "application/json" }; @@ -681,12 +681,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/xml", "application/json" }; @@ -741,12 +741,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/xml", "application/json" }; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Api/UserApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Api/UserApi.cs index 80436c9b433..a2f2598c8ac 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Api/UserApi.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Api/UserApi.cs @@ -406,7 +406,7 @@ namespace Org.OpenAPITools.Api /// Initializes a new instance of the class. /// /// - public UserApi(String basePath) + public UserApi(string basePath) { this.Configuration = Org.OpenAPITools.Client.Configuration.MergeConfigurations( Org.OpenAPITools.Client.GlobalConfiguration.Instance, @@ -469,7 +469,7 @@ namespace Org.OpenAPITools.Api /// Gets the base path of the API client. /// /// The base path - public String GetBasePath() + public string GetBasePath() { return this.Configuration.BasePath; } @@ -521,12 +521,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); @@ -578,12 +578,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; @@ -634,12 +634,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); @@ -691,12 +691,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; @@ -747,12 +747,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); @@ -804,12 +804,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; @@ -860,11 +860,11 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); @@ -916,11 +916,11 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; @@ -972,11 +972,11 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/xml", "application/json" }; @@ -1031,11 +1031,11 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/xml", "application/json" }; @@ -1095,11 +1095,11 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/xml", "application/json" }; @@ -1161,11 +1161,11 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/xml", "application/json" }; @@ -1213,11 +1213,11 @@ namespace Org.OpenAPITools.Api { Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); @@ -1262,11 +1262,11 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; @@ -1322,12 +1322,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); @@ -1386,12 +1386,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Client/ApiClient.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Client/ApiClient.cs index db5a263b639..0a6db477bbc 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Client/ApiClient.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Client/ApiClient.cs @@ -107,7 +107,7 @@ namespace Org.OpenAPITools.Client var bytes = response.RawBytes; if (response.Headers != null) { - var filePath = String.IsNullOrEmpty(_configuration.TempFolderPath) + var filePath = string.IsNullOrEmpty(_configuration.TempFolderPath) ? Path.GetTempPath() : _configuration.TempFolderPath; var regex = new Regex(@"Content-Disposition=.*filename=['""]?([^'""\s]+)['""]?$"); @@ -131,7 +131,7 @@ namespace Org.OpenAPITools.Client return DateTime.Parse(response.Content, null, System.Globalization.DateTimeStyles.RoundtripKind); } - if (type == typeof(String) || type.Name.StartsWith("System.Nullable")) // return primitive type + if (type == typeof(string) || type.Name.StartsWith("System.Nullable")) // return primitive type { return Convert.ChangeType(response.Content, type); } @@ -163,7 +163,7 @@ namespace Org.OpenAPITools.Client /// public partial class ApiClient : ISynchronousClient, IAsynchronousClient { - private readonly String _baseUrl; + private readonly string _baseUrl; /// /// Specifies the settings on a object. @@ -208,7 +208,7 @@ namespace Org.OpenAPITools.Client /// /// The target service's base path in URL format. /// - public ApiClient(String basePath) + public ApiClient(string basePath) { if (string.IsNullOrEmpty(basePath)) throw new ArgumentException("basePath cannot be empty"); @@ -269,7 +269,7 @@ namespace Org.OpenAPITools.Client /// private RestRequest NewRequest( HttpMethod method, - String path, + string path, RequestOptions options, IReadableConfiguration configuration) { @@ -592,7 +592,7 @@ namespace Org.OpenAPITools.Client if (RetryConfiguration.AsyncRetryPolicy != null) { var policy = RetryConfiguration.AsyncRetryPolicy; - var policyResult = await policy.ExecuteAndCaptureAsync(() => client.ExecuteAsync(req, cancellationToken)).ConfigureAwait(false); + var policyResult = await policy.ExecuteAndCaptureAsync((ct) => client.ExecuteAsync(req, ct), cancellationToken).ConfigureAwait(false); response = (policyResult.Outcome == OutcomeType.Successful) ? client.Deserialize(policyResult.Result) : new RestResponse { Request = req, diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Client/ApiResponse.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Client/ApiResponse.cs index 1b7d787c84b..ca2de833a5a 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Client/ApiResponse.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Client/ApiResponse.cs @@ -44,7 +44,7 @@ namespace Org.OpenAPITools.Client /// /// Gets or sets any error text defined by the calling client. /// - String ErrorText { get; set; } + string ErrorText { get; set; } /// /// Gets or sets any cookies passed along on the response. @@ -85,7 +85,7 @@ namespace Org.OpenAPITools.Client /// /// Gets or sets any error text defined by the calling client. /// - public String ErrorText { get; set; } + public string ErrorText { get; set; } /// /// Gets or sets any cookies passed along on the response. diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Client/ClientUtils.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Client/ClientUtils.cs index 2b6e52d6065..3d038d5ce69 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Client/ClientUtils.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Client/ClientUtils.cs @@ -124,7 +124,7 @@ namespace Org.OpenAPITools.Client /// URL encode a string /// Credit/Ref: https://github.com/restsharp/RestSharp/blob/master/RestSharp/Extensions/StringExtensions.cs#L50 /// - /// String to be URL encoded + /// string to be URL encoded /// Byte array public static string UrlEncode(string input) { @@ -158,7 +158,7 @@ namespace Org.OpenAPITools.Client /// /// Encode string in base64 format. /// - /// String to be encoded. + /// string to be encoded. /// Encoded string. public static string Base64Encode(string text) { @@ -186,7 +186,7 @@ namespace Org.OpenAPITools.Client /// /// The Content-Type array to select from. /// The Content-Type header to use. - public static String SelectHeaderContentType(String[] contentTypes) + public static string SelectHeaderContentType(string[] contentTypes) { if (contentTypes.Length == 0) return null; @@ -207,7 +207,7 @@ namespace Org.OpenAPITools.Client /// /// The accepts array to select from. /// The Accept header to use. - public static String SelectHeaderAccept(String[] accepts) + public static string SelectHeaderAccept(string[] accepts) { if (accepts.Length == 0) return null; @@ -215,7 +215,7 @@ namespace Org.OpenAPITools.Client if (accepts.Contains("application/json", StringComparer.OrdinalIgnoreCase)) return "application/json"; - return String.Join(",", accepts); + return string.Join(",", accepts); } /// @@ -233,9 +233,9 @@ namespace Org.OpenAPITools.Client /// /// MIME /// Returns True if MIME type is json. - public static bool IsJsonMime(String mime) + public static bool IsJsonMime(string mime) { - if (String.IsNullOrWhiteSpace(mime)) return false; + if (string.IsNullOrWhiteSpace(mime)) return false; return JsonRegex.IsMatch(mime) || mime.Equals("application/json-patch+json"); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Client/Configuration.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Client/Configuration.cs index 154091fc731..1b80ca62fad 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Client/Configuration.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Client/Configuration.cs @@ -72,7 +72,7 @@ namespace Org.OpenAPITools.Client /// Defines the base path of the target API server. /// Example: http://localhost:3000/v1/ /// - private String _basePath; + private string _basePath; /// /// Gets or sets the API key based on the authentication name. @@ -516,9 +516,9 @@ namespace Org.OpenAPITools.Client /// /// Returns a string with essential information for debugging. /// - public static String ToDebugReport() + public static string ToDebugReport() { - String report = "C# SDK (Org.OpenAPITools) Debug Report:\n"; + 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"; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Client/HttpSigningConfiguration.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Client/HttpSigningConfiguration.cs index 1b9f9b7a99f..1d2d0019cae 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Client/HttpSigningConfiguration.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Client/HttpSigningConfiguration.cs @@ -120,7 +120,7 @@ namespace Org.OpenAPITools.Client } } - var httpValues = HttpUtility.ParseQueryString(String.Empty); + var httpValues = HttpUtility.ParseQueryString(string.Empty); foreach (var parameter in requestOptions.QueryParameters) { #if (NETCOREAPP) @@ -153,7 +153,7 @@ namespace Org.OpenAPITools.Client uriBuilder.Query = httpValues.ToString().Replace("+", "%20"); var dateTime = DateTime.Now; - String Digest = String.Empty; + string Digest = string.Empty; //get the body string requestBody = string.Empty; @@ -230,7 +230,7 @@ namespace Org.OpenAPITools.Client } } - var headersKeysString = String.Join(" ", HttpSignatureHeader.Keys); + var headersKeysString = string.Join(" ", HttpSignatureHeader.Keys); var headerValuesList = new List(); foreach (var keyVal in HttpSignatureHeader) @@ -411,10 +411,10 @@ namespace Org.OpenAPITools.Client return derBytes.ToArray(); } - private RSACryptoServiceProvider GetRSAProviderFromPemFile(String pemfile, SecureString keyPassPharse = null) + private RSACryptoServiceProvider GetRSAProviderFromPemFile(string pemfile, SecureString keyPassPharse = null) { - const String pempubheader = "-----BEGIN PUBLIC KEY-----"; - const String pempubfooter = "-----END PUBLIC KEY-----"; + const string pempubheader = "-----BEGIN PUBLIC KEY-----"; + const string pempubfooter = "-----END PUBLIC KEY-----"; bool isPrivateKeyFile = true; byte[] pemkey = null; @@ -441,11 +441,11 @@ namespace Org.OpenAPITools.Client return null; } - private byte[] ConvertPrivateKeyToBytes(String instr, SecureString keyPassPharse = null) + private byte[] ConvertPrivateKeyToBytes(string instr, SecureString keyPassPharse = null) { - const String pemprivheader = "-----BEGIN RSA PRIVATE KEY-----"; - const String pemprivfooter = "-----END RSA PRIVATE KEY-----"; - String pemstr = instr.Trim(); + 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)) @@ -456,7 +456,7 @@ namespace Org.OpenAPITools.Client StringBuilder sb = new StringBuilder(pemstr); sb.Replace(pemprivheader, ""); sb.Replace(pemprivfooter, ""); - String pvkstr = sb.ToString().Trim(); + string pvkstr = sb.ToString().Trim(); try { // if there are no PEM encryption info lines, this is an UNencrypted PEM private key @@ -472,12 +472,12 @@ namespace Org.OpenAPITools.Client { return null; } - String saltline = str.ReadLine(); + string saltline = str.ReadLine(); if (!saltline.StartsWith("DEK-Info: DES-EDE3-CBC,")) { return null; } - String saltstr = saltline.Substring(saltline.IndexOf(",") + 1).Trim(); + 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); @@ -487,7 +487,7 @@ namespace Org.OpenAPITools.Client } //------ remaining b64 data is encrypted RSA key ---- - String encryptedstr = str.ReadToEnd(); + string encryptedstr = str.ReadToEnd(); try { //should have b64 encrypted RSA key now diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Client/IApiAccessor.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Client/IApiAccessor.cs index 59465ae8e90..2bd76416004 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Client/IApiAccessor.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Client/IApiAccessor.cs @@ -27,7 +27,7 @@ namespace Org.OpenAPITools.Client /// Gets the base path of the API client. /// /// The base path - String GetBasePath(); + string GetBasePath(); /// /// Provides a factory method hook for the creation of exceptions. diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Client/IAsynchronousClient.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Client/IAsynchronousClient.cs index 8a6f726678a..601e86d561c 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Client/IAsynchronousClient.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Client/IAsynchronousClient.cs @@ -29,7 +29,7 @@ namespace Org.OpenAPITools.Client /// 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)); + 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. @@ -40,7 +40,7 @@ namespace Org.OpenAPITools.Client /// 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)); + 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. @@ -51,7 +51,7 @@ namespace Org.OpenAPITools.Client /// 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)); + 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. @@ -62,7 +62,7 @@ namespace Org.OpenAPITools.Client /// 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)); + 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. @@ -73,7 +73,7 @@ namespace Org.OpenAPITools.Client /// 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)); + 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. @@ -84,7 +84,7 @@ namespace Org.OpenAPITools.Client /// 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)); + 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. @@ -95,6 +95,6 @@ namespace Org.OpenAPITools.Client /// 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)); + Task> PatchAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Client/ISynchronousClient.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Client/ISynchronousClient.cs index d27f01a588b..0e0a7fedacf 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Client/ISynchronousClient.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Client/ISynchronousClient.cs @@ -28,7 +28,7 @@ namespace Org.OpenAPITools.Client /// Per-request configurable settings. /// The return type. /// The response data, decorated with - ApiResponse Get(String path, RequestOptions options, IReadableConfiguration configuration = null); + ApiResponse Get(string path, RequestOptions options, IReadableConfiguration configuration = null); /// /// Executes a blocking call to some using the POST http verb. @@ -38,7 +38,7 @@ namespace Org.OpenAPITools.Client /// Per-request configurable settings. /// The return type. /// The response data, decorated with - ApiResponse Post(String path, RequestOptions options, IReadableConfiguration configuration = null); + ApiResponse Post(string path, RequestOptions options, IReadableConfiguration configuration = null); /// /// Executes a blocking call to some using the PUT http verb. @@ -48,7 +48,7 @@ namespace Org.OpenAPITools.Client /// Per-request configurable settings. /// The return type. /// The response data, decorated with - ApiResponse Put(String path, RequestOptions options, IReadableConfiguration configuration = null); + ApiResponse Put(string path, RequestOptions options, IReadableConfiguration configuration = null); /// /// Executes a blocking call to some using the DELETE http verb. @@ -58,7 +58,7 @@ namespace Org.OpenAPITools.Client /// Per-request configurable settings. /// The return type. /// The response data, decorated with - ApiResponse Delete(String path, RequestOptions options, IReadableConfiguration configuration = null); + ApiResponse Delete(string path, RequestOptions options, IReadableConfiguration configuration = null); /// /// Executes a blocking call to some using the HEAD http verb. @@ -68,7 +68,7 @@ namespace Org.OpenAPITools.Client /// Per-request configurable settings. /// The return type. /// The response data, decorated with - ApiResponse Head(String path, RequestOptions options, IReadableConfiguration configuration = null); + ApiResponse Head(string path, RequestOptions options, IReadableConfiguration configuration = null); /// /// Executes a blocking call to some using the OPTIONS http verb. @@ -78,7 +78,7 @@ namespace Org.OpenAPITools.Client /// Per-request configurable settings. /// The return type. /// The response data, decorated with - ApiResponse Options(String path, RequestOptions options, IReadableConfiguration configuration = null); + ApiResponse Options(string path, RequestOptions options, IReadableConfiguration configuration = null); /// /// Executes a blocking call to some using the PATCH http verb. @@ -88,6 +88,6 @@ namespace Org.OpenAPITools.Client /// Per-request configurable settings. /// The return type. /// The response data, decorated with - ApiResponse Patch(String path, RequestOptions options, IReadableConfiguration configuration = null); + ApiResponse Patch(string path, RequestOptions options, IReadableConfiguration configuration = null); } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Client/RequestOptions.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Client/RequestOptions.cs index d8da585db9c..7a1d5b97a88 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Client/RequestOptions.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Client/RequestOptions.cs @@ -24,29 +24,29 @@ namespace Org.OpenAPITools.Client /// /// Parameters to be bound to path parts of the Request's URL /// - public Dictionary PathParameters { get; set; } + 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; } + public Multimap QueryParameters { get; set; } /// /// Header parameters to be applied to to the request. /// Keys may have 1 or more values associated. /// - public Multimap HeaderParameters { get; set; } + public Multimap HeaderParameters { get; set; } /// /// Form parameters to be sent along with the request. /// - public Dictionary FormParameters { get; set; } + public Dictionary FormParameters { get; set; } /// /// File parameters to be sent along with the request. /// - public Dictionary FileParameters { get; set; } + public Dictionary FileParameters { get; set; } /// /// Cookies to be sent along with the request. @@ -67,8 +67,8 @@ namespace Org.OpenAPITools.Client QueryParameters = new Multimap(); HeaderParameters = new Multimap(); FormParameters = new Dictionary(); - FileParameters = new Dictionary(); + FileParameters = new Dictionary(); Cookies = new List(); } } -} \ No newline at end of file +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/Fruit.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/Fruit.cs index 132be5b4d3b..66de6a1c6f1 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/Fruit.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/Fruit.cs @@ -162,7 +162,7 @@ namespace Org.OpenAPITools.Model catch (Exception exception) { // deserialization failed, try the next one - System.Diagnostics.Debug.WriteLine(String.Format("Failed to deserialize `{0}` into Apple: {1}", jsonString, exception.ToString())); + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into Apple: {1}", jsonString, exception.ToString())); } try @@ -182,7 +182,7 @@ namespace Org.OpenAPITools.Model catch (Exception exception) { // deserialization failed, try the next one - System.Diagnostics.Debug.WriteLine(String.Format("Failed to deserialize `{0}` into Banana: {1}", jsonString, exception.ToString())); + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into Banana: {1}", jsonString, exception.ToString())); } if (match == 0) @@ -257,7 +257,7 @@ namespace Org.OpenAPITools.Model /// JSON Serializer public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { - writer.WriteRawValue((String)(typeof(Fruit).GetMethod("ToJson").Invoke(value, null))); + writer.WriteRawValue((string)(typeof(Fruit).GetMethod("ToJson").Invoke(value, null))); } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/FruitReq.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/FruitReq.cs index 380896933df..488c489d73a 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/FruitReq.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/FruitReq.cs @@ -171,7 +171,7 @@ namespace Org.OpenAPITools.Model catch (Exception exception) { // deserialization failed, try the next one - System.Diagnostics.Debug.WriteLine(String.Format("Failed to deserialize `{0}` into AppleReq: {1}", jsonString, exception.ToString())); + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into AppleReq: {1}", jsonString, exception.ToString())); } try @@ -191,7 +191,7 @@ namespace Org.OpenAPITools.Model catch (Exception exception) { // deserialization failed, try the next one - System.Diagnostics.Debug.WriteLine(String.Format("Failed to deserialize `{0}` into BananaReq: {1}", jsonString, exception.ToString())); + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into BananaReq: {1}", jsonString, exception.ToString())); } if (match == 0) @@ -266,7 +266,7 @@ namespace Org.OpenAPITools.Model /// JSON Serializer public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { - writer.WriteRawValue((String)(typeof(FruitReq).GetMethod("ToJson").Invoke(value, null))); + writer.WriteRawValue((string)(typeof(FruitReq).GetMethod("ToJson").Invoke(value, null))); } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/GmFruit.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/GmFruit.cs index c168aa41d4c..1aaa59d3f8b 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/GmFruit.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/GmFruit.cs @@ -151,7 +151,7 @@ namespace Org.OpenAPITools.Model catch (Exception exception) { // deserialization failed, try the next one - System.Diagnostics.Debug.WriteLine(String.Format("Failed to deserialize `{0}` into Apple: {1}", jsonString, exception.ToString())); + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into Apple: {1}", jsonString, exception.ToString())); } try @@ -163,7 +163,7 @@ namespace Org.OpenAPITools.Model catch (Exception exception) { // deserialization failed, try the next one - System.Diagnostics.Debug.WriteLine(String.Format("Failed to deserialize `{0}` into Banana: {1}", jsonString, exception.ToString())); + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into Banana: {1}", jsonString, exception.ToString())); } // no match found, throw an exception @@ -229,7 +229,7 @@ namespace Org.OpenAPITools.Model /// JSON Serializer public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { - writer.WriteRawValue((String)(typeof(GmFruit).GetMethod("ToJson").Invoke(value, null))); + writer.WriteRawValue((string)(typeof(GmFruit).GetMethod("ToJson").Invoke(value, null))); } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/HasOnlyReadOnly.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/HasOnlyReadOnly.cs index 3a2c3d26a92..fecd58bf6e8 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/HasOnlyReadOnly.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/HasOnlyReadOnly.cs @@ -55,7 +55,6 @@ namespace Org.OpenAPITools.Model { return false; } - /// /// Gets or Sets Foo /// @@ -70,7 +69,6 @@ namespace Org.OpenAPITools.Model { return false; } - /// /// Gets or Sets additional properties /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/Mammal.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/Mammal.cs index 2e847a10eb6..ed940d7ab6f 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/Mammal.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/Mammal.cs @@ -183,7 +183,7 @@ namespace Org.OpenAPITools.Model newMammal = new Mammal(JsonConvert.DeserializeObject(jsonString, Mammal.AdditionalPropertiesSerializerSettings)); return newMammal; default: - System.Diagnostics.Debug.WriteLine(String.Format("Failed to lookup discriminator value `{0}` for Mammal. Possible values: Pig whale zebra", discriminatorValue)); + System.Diagnostics.Debug.WriteLine(string.Format("Failed to lookup discriminator value `{0}` for Mammal. Possible values: Pig whale zebra", discriminatorValue)); break; } @@ -207,7 +207,7 @@ namespace Org.OpenAPITools.Model catch (Exception exception) { // deserialization failed, try the next one - System.Diagnostics.Debug.WriteLine(String.Format("Failed to deserialize `{0}` into Pig: {1}", jsonString, exception.ToString())); + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into Pig: {1}", jsonString, exception.ToString())); } try @@ -227,7 +227,7 @@ namespace Org.OpenAPITools.Model catch (Exception exception) { // deserialization failed, try the next one - System.Diagnostics.Debug.WriteLine(String.Format("Failed to deserialize `{0}` into Whale: {1}", jsonString, exception.ToString())); + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into Whale: {1}", jsonString, exception.ToString())); } try @@ -247,7 +247,7 @@ namespace Org.OpenAPITools.Model catch (Exception exception) { // deserialization failed, try the next one - System.Diagnostics.Debug.WriteLine(String.Format("Failed to deserialize `{0}` into Zebra: {1}", jsonString, exception.ToString())); + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into Zebra: {1}", jsonString, exception.ToString())); } if (match == 0) @@ -322,7 +322,7 @@ namespace Org.OpenAPITools.Model /// JSON Serializer public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { - writer.WriteRawValue((String)(typeof(Mammal).GetMethod("ToJson").Invoke(value, null))); + writer.WriteRawValue((string)(typeof(Mammal).GetMethod("ToJson").Invoke(value, null))); } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/Name.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/Name.cs index a6a01dd4ed3..0f5da18eafa 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/Name.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/Name.cs @@ -72,7 +72,6 @@ namespace Org.OpenAPITools.Model { return false; } - /// /// Gets or Sets Property /// @@ -93,7 +92,6 @@ namespace Org.OpenAPITools.Model { return false; } - /// /// Gets or Sets additional properties /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/NullableShape.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/NullableShape.cs index 80339ebf79b..20be30e5b89 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/NullableShape.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/NullableShape.cs @@ -163,7 +163,7 @@ namespace Org.OpenAPITools.Model newNullableShape = new NullableShape(JsonConvert.DeserializeObject(jsonString, NullableShape.AdditionalPropertiesSerializerSettings)); return newNullableShape; default: - System.Diagnostics.Debug.WriteLine(String.Format("Failed to lookup discriminator value `{0}` for NullableShape. Possible values: Quadrilateral Triangle", discriminatorValue)); + System.Diagnostics.Debug.WriteLine(string.Format("Failed to lookup discriminator value `{0}` for NullableShape. Possible values: Quadrilateral Triangle", discriminatorValue)); break; } @@ -187,7 +187,7 @@ namespace Org.OpenAPITools.Model catch (Exception exception) { // deserialization failed, try the next one - System.Diagnostics.Debug.WriteLine(String.Format("Failed to deserialize `{0}` into Quadrilateral: {1}", jsonString, exception.ToString())); + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into Quadrilateral: {1}", jsonString, exception.ToString())); } try @@ -207,7 +207,7 @@ namespace Org.OpenAPITools.Model catch (Exception exception) { // deserialization failed, try the next one - System.Diagnostics.Debug.WriteLine(String.Format("Failed to deserialize `{0}` into Triangle: {1}", jsonString, exception.ToString())); + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into Triangle: {1}", jsonString, exception.ToString())); } if (match == 0) @@ -282,7 +282,7 @@ namespace Org.OpenAPITools.Model /// JSON Serializer public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { - writer.WriteRawValue((String)(typeof(NullableShape).GetMethod("ToJson").Invoke(value, null))); + writer.WriteRawValue((string)(typeof(NullableShape).GetMethod("ToJson").Invoke(value, null))); } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/Pig.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/Pig.cs index d8605861e63..967d2139a0a 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/Pig.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/Pig.cs @@ -154,7 +154,7 @@ namespace Org.OpenAPITools.Model newPig = new Pig(JsonConvert.DeserializeObject(jsonString, Pig.AdditionalPropertiesSerializerSettings)); return newPig; default: - System.Diagnostics.Debug.WriteLine(String.Format("Failed to lookup discriminator value `{0}` for Pig. Possible values: BasquePig DanishPig", discriminatorValue)); + System.Diagnostics.Debug.WriteLine(string.Format("Failed to lookup discriminator value `{0}` for Pig. Possible values: BasquePig DanishPig", discriminatorValue)); break; } @@ -178,7 +178,7 @@ namespace Org.OpenAPITools.Model catch (Exception exception) { // deserialization failed, try the next one - System.Diagnostics.Debug.WriteLine(String.Format("Failed to deserialize `{0}` into BasquePig: {1}", jsonString, exception.ToString())); + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into BasquePig: {1}", jsonString, exception.ToString())); } try @@ -198,7 +198,7 @@ namespace Org.OpenAPITools.Model catch (Exception exception) { // deserialization failed, try the next one - System.Diagnostics.Debug.WriteLine(String.Format("Failed to deserialize `{0}` into DanishPig: {1}", jsonString, exception.ToString())); + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into DanishPig: {1}", jsonString, exception.ToString())); } if (match == 0) @@ -273,7 +273,7 @@ namespace Org.OpenAPITools.Model /// JSON Serializer public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { - writer.WriteRawValue((String)(typeof(Pig).GetMethod("ToJson").Invoke(value, null))); + writer.WriteRawValue((string)(typeof(Pig).GetMethod("ToJson").Invoke(value, null))); } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/Quadrilateral.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/Quadrilateral.cs index 17463ca09a4..19bc98ed2ec 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/Quadrilateral.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/Quadrilateral.cs @@ -154,7 +154,7 @@ namespace Org.OpenAPITools.Model newQuadrilateral = new Quadrilateral(JsonConvert.DeserializeObject(jsonString, Quadrilateral.AdditionalPropertiesSerializerSettings)); return newQuadrilateral; default: - System.Diagnostics.Debug.WriteLine(String.Format("Failed to lookup discriminator value `{0}` for Quadrilateral. Possible values: ComplexQuadrilateral SimpleQuadrilateral", discriminatorValue)); + System.Diagnostics.Debug.WriteLine(string.Format("Failed to lookup discriminator value `{0}` for Quadrilateral. Possible values: ComplexQuadrilateral SimpleQuadrilateral", discriminatorValue)); break; } @@ -178,7 +178,7 @@ namespace Org.OpenAPITools.Model catch (Exception exception) { // deserialization failed, try the next one - System.Diagnostics.Debug.WriteLine(String.Format("Failed to deserialize `{0}` into ComplexQuadrilateral: {1}", jsonString, exception.ToString())); + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into ComplexQuadrilateral: {1}", jsonString, exception.ToString())); } try @@ -198,7 +198,7 @@ namespace Org.OpenAPITools.Model catch (Exception exception) { // deserialization failed, try the next one - System.Diagnostics.Debug.WriteLine(String.Format("Failed to deserialize `{0}` into SimpleQuadrilateral: {1}", jsonString, exception.ToString())); + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into SimpleQuadrilateral: {1}", jsonString, exception.ToString())); } if (match == 0) @@ -273,7 +273,7 @@ namespace Org.OpenAPITools.Model /// JSON Serializer public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { - writer.WriteRawValue((String)(typeof(Quadrilateral).GetMethod("ToJson").Invoke(value, null))); + writer.WriteRawValue((string)(typeof(Quadrilateral).GetMethod("ToJson").Invoke(value, null))); } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/ReadOnlyFirst.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/ReadOnlyFirst.cs index 4ab8f7d5c6a..20483c31cdc 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/ReadOnlyFirst.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/ReadOnlyFirst.cs @@ -56,7 +56,6 @@ namespace Org.OpenAPITools.Model { return false; } - /// /// Gets or Sets Baz /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/Shape.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/Shape.cs index e75e0e8b167..f17c4d9a8f5 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/Shape.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/Shape.cs @@ -154,7 +154,7 @@ namespace Org.OpenAPITools.Model newShape = new Shape(JsonConvert.DeserializeObject(jsonString, Shape.AdditionalPropertiesSerializerSettings)); return newShape; default: - System.Diagnostics.Debug.WriteLine(String.Format("Failed to lookup discriminator value `{0}` for Shape. Possible values: Quadrilateral Triangle", discriminatorValue)); + System.Diagnostics.Debug.WriteLine(string.Format("Failed to lookup discriminator value `{0}` for Shape. Possible values: Quadrilateral Triangle", discriminatorValue)); break; } @@ -178,7 +178,7 @@ namespace Org.OpenAPITools.Model catch (Exception exception) { // deserialization failed, try the next one - System.Diagnostics.Debug.WriteLine(String.Format("Failed to deserialize `{0}` into Quadrilateral: {1}", jsonString, exception.ToString())); + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into Quadrilateral: {1}", jsonString, exception.ToString())); } try @@ -198,7 +198,7 @@ namespace Org.OpenAPITools.Model catch (Exception exception) { // deserialization failed, try the next one - System.Diagnostics.Debug.WriteLine(String.Format("Failed to deserialize `{0}` into Triangle: {1}", jsonString, exception.ToString())); + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into Triangle: {1}", jsonString, exception.ToString())); } if (match == 0) @@ -273,7 +273,7 @@ namespace Org.OpenAPITools.Model /// JSON Serializer public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { - writer.WriteRawValue((String)(typeof(Shape).GetMethod("ToJson").Invoke(value, null))); + writer.WriteRawValue((string)(typeof(Shape).GetMethod("ToJson").Invoke(value, null))); } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/ShapeOrNull.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/ShapeOrNull.cs index 7471bafb379..df321dc9e81 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/ShapeOrNull.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/ShapeOrNull.cs @@ -163,7 +163,7 @@ namespace Org.OpenAPITools.Model newShapeOrNull = new ShapeOrNull(JsonConvert.DeserializeObject(jsonString, ShapeOrNull.AdditionalPropertiesSerializerSettings)); return newShapeOrNull; default: - System.Diagnostics.Debug.WriteLine(String.Format("Failed to lookup discriminator value `{0}` for ShapeOrNull. Possible values: Quadrilateral Triangle", discriminatorValue)); + System.Diagnostics.Debug.WriteLine(string.Format("Failed to lookup discriminator value `{0}` for ShapeOrNull. Possible values: Quadrilateral Triangle", discriminatorValue)); break; } @@ -187,7 +187,7 @@ namespace Org.OpenAPITools.Model catch (Exception exception) { // deserialization failed, try the next one - System.Diagnostics.Debug.WriteLine(String.Format("Failed to deserialize `{0}` into Quadrilateral: {1}", jsonString, exception.ToString())); + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into Quadrilateral: {1}", jsonString, exception.ToString())); } try @@ -207,7 +207,7 @@ namespace Org.OpenAPITools.Model catch (Exception exception) { // deserialization failed, try the next one - System.Diagnostics.Debug.WriteLine(String.Format("Failed to deserialize `{0}` into Triangle: {1}", jsonString, exception.ToString())); + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into Triangle: {1}", jsonString, exception.ToString())); } if (match == 0) @@ -282,7 +282,7 @@ namespace Org.OpenAPITools.Model /// JSON Serializer public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { - writer.WriteRawValue((String)(typeof(ShapeOrNull).GetMethod("ToJson").Invoke(value, null))); + writer.WriteRawValue((string)(typeof(ShapeOrNull).GetMethod("ToJson").Invoke(value, null))); } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/Triangle.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/Triangle.cs index cccaa79a8ff..6f33859a898 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/Triangle.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/Triangle.cs @@ -183,7 +183,7 @@ namespace Org.OpenAPITools.Model newTriangle = new Triangle(JsonConvert.DeserializeObject(jsonString, Triangle.AdditionalPropertiesSerializerSettings)); return newTriangle; default: - System.Diagnostics.Debug.WriteLine(String.Format("Failed to lookup discriminator value `{0}` for Triangle. Possible values: EquilateralTriangle IsoscelesTriangle ScaleneTriangle", discriminatorValue)); + System.Diagnostics.Debug.WriteLine(string.Format("Failed to lookup discriminator value `{0}` for Triangle. Possible values: EquilateralTriangle IsoscelesTriangle ScaleneTriangle", discriminatorValue)); break; } @@ -207,7 +207,7 @@ namespace Org.OpenAPITools.Model catch (Exception exception) { // deserialization failed, try the next one - System.Diagnostics.Debug.WriteLine(String.Format("Failed to deserialize `{0}` into EquilateralTriangle: {1}", jsonString, exception.ToString())); + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into EquilateralTriangle: {1}", jsonString, exception.ToString())); } try @@ -227,7 +227,7 @@ namespace Org.OpenAPITools.Model catch (Exception exception) { // deserialization failed, try the next one - System.Diagnostics.Debug.WriteLine(String.Format("Failed to deserialize `{0}` into IsoscelesTriangle: {1}", jsonString, exception.ToString())); + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into IsoscelesTriangle: {1}", jsonString, exception.ToString())); } try @@ -247,7 +247,7 @@ namespace Org.OpenAPITools.Model catch (Exception exception) { // deserialization failed, try the next one - System.Diagnostics.Debug.WriteLine(String.Format("Failed to deserialize `{0}` into ScaleneTriangle: {1}", jsonString, exception.ToString())); + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into ScaleneTriangle: {1}", jsonString, exception.ToString())); } if (match == 0) @@ -322,7 +322,7 @@ namespace Org.OpenAPITools.Model /// JSON Serializer public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { - writer.WriteRawValue((String)(typeof(Triangle).GetMethod("ToJson").Invoke(value, null))); + writer.WriteRawValue((string)(typeof(Triangle).GetMethod("ToJson").Invoke(value, null))); } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/.openapi-generator/VERSION b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/.openapi-generator/VERSION +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Api/AnotherFakeApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Api/AnotherFakeApi.cs index 94d8b854b0d..ad48306e00c 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Api/AnotherFakeApi.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Api/AnotherFakeApi.cs @@ -109,7 +109,7 @@ namespace Org.OpenAPITools.Api /// Initializes a new instance of the class. /// /// - public AnotherFakeApi(String basePath) + public AnotherFakeApi(string basePath) { this.Configuration = Org.OpenAPITools.Client.Configuration.MergeConfigurations( Org.OpenAPITools.Client.GlobalConfiguration.Instance, @@ -172,7 +172,7 @@ namespace Org.OpenAPITools.Api /// Gets the base path of the API client. /// /// The base path - public String GetBasePath() + public string GetBasePath() { return this.Configuration.BasePath; } @@ -225,12 +225,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/json" }; @@ -284,12 +284,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/json" }; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Api/DefaultApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Api/DefaultApi.cs index 27789c4533a..8844aca4ab7 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Api/DefaultApi.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Api/DefaultApi.cs @@ -102,7 +102,7 @@ namespace Org.OpenAPITools.Api /// Initializes a new instance of the class. /// /// - public DefaultApi(String basePath) + public DefaultApi(string basePath) { this.Configuration = Org.OpenAPITools.Client.Configuration.MergeConfigurations( Org.OpenAPITools.Client.GlobalConfiguration.Instance, @@ -165,7 +165,7 @@ namespace Org.OpenAPITools.Api /// Gets the base path of the API client. /// /// The base path - public String GetBasePath() + public string GetBasePath() { return this.Configuration.BasePath; } @@ -212,11 +212,11 @@ namespace Org.OpenAPITools.Api { Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/json" }; @@ -263,11 +263,11 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/json" }; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Api/FakeApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Api/FakeApi.cs index d7749151314..fe862283f1e 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Api/FakeApi.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Api/FakeApi.cs @@ -826,7 +826,7 @@ namespace Org.OpenAPITools.Api /// Initializes a new instance of the class. /// /// - public FakeApi(String basePath) + public FakeApi(string basePath) { this.Configuration = Org.OpenAPITools.Client.Configuration.MergeConfigurations( Org.OpenAPITools.Client.GlobalConfiguration.Instance, @@ -889,7 +889,7 @@ namespace Org.OpenAPITools.Api /// Gets the base path of the API client. /// /// The base path - public String GetBasePath() + public string GetBasePath() { return this.Configuration.BasePath; } @@ -936,11 +936,11 @@ namespace Org.OpenAPITools.Api { Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/json" }; @@ -987,11 +987,11 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/json" }; @@ -1039,12 +1039,12 @@ namespace Org.OpenAPITools.Api { Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "*/*" }; @@ -1094,12 +1094,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "*/*" }; @@ -1148,12 +1148,12 @@ namespace Org.OpenAPITools.Api { Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "*/*" }; @@ -1203,12 +1203,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "*/*" }; @@ -1257,12 +1257,12 @@ namespace Org.OpenAPITools.Api { Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "*/*" }; @@ -1312,12 +1312,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "*/*" }; @@ -1366,12 +1366,12 @@ namespace Org.OpenAPITools.Api { Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "*/*" }; @@ -1421,12 +1421,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "*/*" }; @@ -1473,11 +1473,11 @@ namespace Org.OpenAPITools.Api { Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/json" }; @@ -1524,11 +1524,11 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/json" }; @@ -1579,12 +1579,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); @@ -1636,12 +1636,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; @@ -1698,12 +1698,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); @@ -1762,12 +1762,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; @@ -1820,12 +1820,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/json" }; @@ -1879,12 +1879,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/json" }; @@ -1966,12 +1966,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/x-www-form-urlencoded" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); @@ -2027,7 +2027,7 @@ namespace Org.OpenAPITools.Api // authentication (http_basic_test) required // http basic authentication required - if (!String.IsNullOrEmpty(this.Configuration.Username) || !String.IsNullOrEmpty(this.Configuration.Password)) + if (!string.IsNullOrEmpty(this.Configuration.Username) || !string.IsNullOrEmpty(this.Configuration.Password)) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Basic " + Org.OpenAPITools.Client.ClientUtils.Base64Encode(this.Configuration.Username + ":" + this.Configuration.Password)); } @@ -2102,12 +2102,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/x-www-form-urlencoded" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; @@ -2164,7 +2164,7 @@ namespace Org.OpenAPITools.Api // authentication (http_basic_test) required // http basic authentication required - if (!String.IsNullOrEmpty(this.Configuration.Username) || !String.IsNullOrEmpty(this.Configuration.Password)) + if (!string.IsNullOrEmpty(this.Configuration.Username) || !string.IsNullOrEmpty(this.Configuration.Password)) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Basic " + Org.OpenAPITools.Client.ClientUtils.Base64Encode(this.Configuration.Username + ":" + this.Configuration.Password)); } @@ -2217,12 +2217,12 @@ namespace Org.OpenAPITools.Api { Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/x-www-form-urlencoded" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); @@ -2315,12 +2315,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/x-www-form-urlencoded" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; @@ -2408,11 +2408,11 @@ namespace Org.OpenAPITools.Api { Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); @@ -2439,7 +2439,7 @@ namespace Org.OpenAPITools.Api // authentication (bearer_test) required // bearer authentication required - if (!String.IsNullOrEmpty(this.Configuration.AccessToken)) + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); } @@ -2490,11 +2490,11 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; @@ -2522,7 +2522,7 @@ namespace Org.OpenAPITools.Api // authentication (bearer_test) required // bearer authentication required - if (!String.IsNullOrEmpty(this.Configuration.AccessToken)) + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); } @@ -2565,12 +2565,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); @@ -2622,12 +2622,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; @@ -2684,12 +2684,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/x-www-form-urlencoded" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); @@ -2748,12 +2748,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/x-www-form-urlencoded" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; @@ -2829,11 +2829,11 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); @@ -2913,11 +2913,11 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Api/FakeClassnameTags123Api.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Api/FakeClassnameTags123Api.cs index 56ebdf5fd10..d4fbb5868ad 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Api/FakeClassnameTags123Api.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Api/FakeClassnameTags123Api.cs @@ -109,7 +109,7 @@ namespace Org.OpenAPITools.Api /// Initializes a new instance of the class. /// /// - public FakeClassnameTags123Api(String basePath) + public FakeClassnameTags123Api(string basePath) { this.Configuration = Org.OpenAPITools.Client.Configuration.MergeConfigurations( Org.OpenAPITools.Client.GlobalConfiguration.Instance, @@ -172,7 +172,7 @@ namespace Org.OpenAPITools.Api /// Gets the base path of the API client. /// /// The base path - public String GetBasePath() + public string GetBasePath() { return this.Configuration.BasePath; } @@ -225,12 +225,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/json" }; @@ -243,7 +243,7 @@ namespace Org.OpenAPITools.Api localVarRequestOptions.Data = modelClient; // authentication (api_key_query) required - if (!String.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("api_key_query"))) + 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"))); } @@ -289,12 +289,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/json" }; @@ -308,7 +308,7 @@ namespace Org.OpenAPITools.Api localVarRequestOptions.Data = modelClient; // authentication (api_key_query) required - if (!String.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("api_key_query"))) + 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"))); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Api/PetApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Api/PetApi.cs index 61759145f12..2bf19af1b1a 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Api/PetApi.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Api/PetApi.cs @@ -471,7 +471,7 @@ namespace Org.OpenAPITools.Api /// Initializes a new instance of the class. /// /// - public PetApi(String basePath) + public PetApi(string basePath) { this.Configuration = Org.OpenAPITools.Client.Configuration.MergeConfigurations( Org.OpenAPITools.Client.GlobalConfiguration.Instance, @@ -534,7 +534,7 @@ namespace Org.OpenAPITools.Api /// Gets the base path of the API client. /// /// The base path - public String GetBasePath() + public string GetBasePath() { return this.Configuration.BasePath; } @@ -586,13 +586,13 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json", "application/xml" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); @@ -621,7 +621,7 @@ namespace Org.OpenAPITools.Api } // authentication (petstore_auth) required // oauth required - if (!String.IsNullOrEmpty(this.Configuration.AccessToken)) + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); } @@ -666,13 +666,13 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json", "application/xml" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; @@ -702,7 +702,7 @@ namespace Org.OpenAPITools.Api } // authentication (petstore_auth) required // oauth required - if (!String.IsNullOrEmpty(this.Configuration.AccessToken)) + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); } @@ -743,11 +743,11 @@ namespace Org.OpenAPITools.Api { Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); @@ -764,7 +764,7 @@ namespace Org.OpenAPITools.Api // authentication (petstore_auth) required // oauth required - if (!String.IsNullOrEmpty(this.Configuration.AccessToken)) + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); } @@ -807,11 +807,11 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; @@ -829,7 +829,7 @@ namespace Org.OpenAPITools.Api // authentication (petstore_auth) required // oauth required - if (!String.IsNullOrEmpty(this.Configuration.AccessToken)) + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); } @@ -873,11 +873,11 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/xml", "application/json" }; @@ -908,7 +908,7 @@ namespace Org.OpenAPITools.Api } // authentication (petstore_auth) required // oauth required - if (!String.IsNullOrEmpty(this.Configuration.AccessToken)) + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); } @@ -954,11 +954,11 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/xml", "application/json" }; @@ -990,7 +990,7 @@ namespace Org.OpenAPITools.Api } // authentication (petstore_auth) required // oauth required - if (!String.IsNullOrEmpty(this.Configuration.AccessToken)) + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); } @@ -1034,11 +1034,11 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/xml", "application/json" }; @@ -1069,7 +1069,7 @@ namespace Org.OpenAPITools.Api } // authentication (petstore_auth) required // oauth required - if (!String.IsNullOrEmpty(this.Configuration.AccessToken)) + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); } @@ -1115,11 +1115,11 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/xml", "application/json" }; @@ -1151,7 +1151,7 @@ namespace Org.OpenAPITools.Api } // authentication (petstore_auth) required // oauth required - if (!String.IsNullOrEmpty(this.Configuration.AccessToken)) + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); } @@ -1191,11 +1191,11 @@ namespace Org.OpenAPITools.Api { Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/xml", "application/json" }; @@ -1209,7 +1209,7 @@ namespace Org.OpenAPITools.Api localVarRequestOptions.PathParameters.Add("petId", Org.OpenAPITools.Client.ClientUtils.ParameterToString(petId)); // path parameter // authentication (api_key) required - if (!String.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("api_key"))) + if (!string.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("api_key"))) { localVarRequestOptions.HeaderParameters.Add("api_key", this.Configuration.GetApiKeyWithPrefix("api_key")); } @@ -1251,11 +1251,11 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/xml", "application/json" }; @@ -1270,7 +1270,7 @@ namespace Org.OpenAPITools.Api localVarRequestOptions.PathParameters.Add("petId", Org.OpenAPITools.Client.ClientUtils.ParameterToString(petId)); // path parameter // authentication (api_key) required - if (!String.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("api_key"))) + if (!string.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("api_key"))) { localVarRequestOptions.HeaderParameters.Add("api_key", this.Configuration.GetApiKeyWithPrefix("api_key")); } @@ -1313,13 +1313,13 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json", "application/xml" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); @@ -1348,7 +1348,7 @@ namespace Org.OpenAPITools.Api } // authentication (petstore_auth) required // oauth required - if (!String.IsNullOrEmpty(this.Configuration.AccessToken)) + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); } @@ -1393,13 +1393,13 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json", "application/xml" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; @@ -1429,7 +1429,7 @@ namespace Org.OpenAPITools.Api } // authentication (petstore_auth) required // oauth required - if (!String.IsNullOrEmpty(this.Configuration.AccessToken)) + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); } @@ -1472,12 +1472,12 @@ namespace Org.OpenAPITools.Api { Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/x-www-form-urlencoded" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); @@ -1498,7 +1498,7 @@ namespace Org.OpenAPITools.Api // authentication (petstore_auth) required // oauth required - if (!String.IsNullOrEmpty(this.Configuration.AccessToken)) + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); } @@ -1543,12 +1543,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/x-www-form-urlencoded" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; @@ -1570,7 +1570,7 @@ namespace Org.OpenAPITools.Api // authentication (petstore_auth) required // oauth required - if (!String.IsNullOrEmpty(this.Configuration.AccessToken)) + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); } @@ -1614,12 +1614,12 @@ namespace Org.OpenAPITools.Api { Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "multipart/form-data" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/json" }; @@ -1641,7 +1641,7 @@ namespace Org.OpenAPITools.Api // authentication (petstore_auth) required // oauth required - if (!String.IsNullOrEmpty(this.Configuration.AccessToken)) + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); } @@ -1687,12 +1687,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "multipart/form-data" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/json" }; @@ -1715,7 +1715,7 @@ namespace Org.OpenAPITools.Api // authentication (petstore_auth) required // oauth required - if (!String.IsNullOrEmpty(this.Configuration.AccessToken)) + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); } @@ -1763,12 +1763,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "multipart/form-data" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/json" }; @@ -1787,7 +1787,7 @@ namespace Org.OpenAPITools.Api // authentication (petstore_auth) required // oauth required - if (!String.IsNullOrEmpty(this.Configuration.AccessToken)) + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); } @@ -1837,12 +1837,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "multipart/form-data" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/json" }; @@ -1862,7 +1862,7 @@ namespace Org.OpenAPITools.Api // authentication (petstore_auth) required // oauth required - if (!String.IsNullOrEmpty(this.Configuration.AccessToken)) + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Api/StoreApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Api/StoreApi.cs index 6ab56c9e9bf..ad7387db705 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Api/StoreApi.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Api/StoreApi.cs @@ -234,7 +234,7 @@ namespace Org.OpenAPITools.Api /// Initializes a new instance of the class. /// /// - public StoreApi(String basePath) + public StoreApi(string basePath) { this.Configuration = Org.OpenAPITools.Client.Configuration.MergeConfigurations( Org.OpenAPITools.Client.GlobalConfiguration.Instance, @@ -297,7 +297,7 @@ namespace Org.OpenAPITools.Api /// Gets the base path of the API client. /// /// The base path - public String GetBasePath() + public string GetBasePath() { return this.Configuration.BasePath; } @@ -349,11 +349,11 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); @@ -405,11 +405,11 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; @@ -455,11 +455,11 @@ namespace Org.OpenAPITools.Api { Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/json" }; @@ -471,7 +471,7 @@ namespace Org.OpenAPITools.Api // authentication (api_key) required - if (!String.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("api_key"))) + if (!string.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("api_key"))) { localVarRequestOptions.HeaderParameters.Add("api_key", this.Configuration.GetApiKeyWithPrefix("api_key")); } @@ -511,11 +511,11 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/json" }; @@ -528,7 +528,7 @@ namespace Org.OpenAPITools.Api // authentication (api_key) required - if (!String.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("api_key"))) + if (!string.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("api_key"))) { localVarRequestOptions.HeaderParameters.Add("api_key", this.Configuration.GetApiKeyWithPrefix("api_key")); } @@ -568,11 +568,11 @@ namespace Org.OpenAPITools.Api { Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/xml", "application/json" }; @@ -623,11 +623,11 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/xml", "application/json" }; @@ -681,12 +681,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/xml", "application/json" }; @@ -741,12 +741,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/xml", "application/json" }; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Api/UserApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Api/UserApi.cs index 80436c9b433..a2f2598c8ac 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Api/UserApi.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Api/UserApi.cs @@ -406,7 +406,7 @@ namespace Org.OpenAPITools.Api /// Initializes a new instance of the class. /// /// - public UserApi(String basePath) + public UserApi(string basePath) { this.Configuration = Org.OpenAPITools.Client.Configuration.MergeConfigurations( Org.OpenAPITools.Client.GlobalConfiguration.Instance, @@ -469,7 +469,7 @@ namespace Org.OpenAPITools.Api /// Gets the base path of the API client. /// /// The base path - public String GetBasePath() + public string GetBasePath() { return this.Configuration.BasePath; } @@ -521,12 +521,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); @@ -578,12 +578,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; @@ -634,12 +634,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); @@ -691,12 +691,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; @@ -747,12 +747,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); @@ -804,12 +804,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; @@ -860,11 +860,11 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); @@ -916,11 +916,11 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; @@ -972,11 +972,11 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/xml", "application/json" }; @@ -1031,11 +1031,11 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/xml", "application/json" }; @@ -1095,11 +1095,11 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/xml", "application/json" }; @@ -1161,11 +1161,11 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/xml", "application/json" }; @@ -1213,11 +1213,11 @@ namespace Org.OpenAPITools.Api { Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); @@ -1262,11 +1262,11 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; @@ -1322,12 +1322,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); @@ -1386,12 +1386,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Client/ApiClient.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Client/ApiClient.cs index db5a263b639..0a6db477bbc 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Client/ApiClient.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Client/ApiClient.cs @@ -107,7 +107,7 @@ namespace Org.OpenAPITools.Client var bytes = response.RawBytes; if (response.Headers != null) { - var filePath = String.IsNullOrEmpty(_configuration.TempFolderPath) + var filePath = string.IsNullOrEmpty(_configuration.TempFolderPath) ? Path.GetTempPath() : _configuration.TempFolderPath; var regex = new Regex(@"Content-Disposition=.*filename=['""]?([^'""\s]+)['""]?$"); @@ -131,7 +131,7 @@ namespace Org.OpenAPITools.Client return DateTime.Parse(response.Content, null, System.Globalization.DateTimeStyles.RoundtripKind); } - if (type == typeof(String) || type.Name.StartsWith("System.Nullable")) // return primitive type + if (type == typeof(string) || type.Name.StartsWith("System.Nullable")) // return primitive type { return Convert.ChangeType(response.Content, type); } @@ -163,7 +163,7 @@ namespace Org.OpenAPITools.Client /// public partial class ApiClient : ISynchronousClient, IAsynchronousClient { - private readonly String _baseUrl; + private readonly string _baseUrl; /// /// Specifies the settings on a object. @@ -208,7 +208,7 @@ namespace Org.OpenAPITools.Client /// /// The target service's base path in URL format. /// - public ApiClient(String basePath) + public ApiClient(string basePath) { if (string.IsNullOrEmpty(basePath)) throw new ArgumentException("basePath cannot be empty"); @@ -269,7 +269,7 @@ namespace Org.OpenAPITools.Client /// private RestRequest NewRequest( HttpMethod method, - String path, + string path, RequestOptions options, IReadableConfiguration configuration) { @@ -592,7 +592,7 @@ namespace Org.OpenAPITools.Client if (RetryConfiguration.AsyncRetryPolicy != null) { var policy = RetryConfiguration.AsyncRetryPolicy; - var policyResult = await policy.ExecuteAndCaptureAsync(() => client.ExecuteAsync(req, cancellationToken)).ConfigureAwait(false); + var policyResult = await policy.ExecuteAndCaptureAsync((ct) => client.ExecuteAsync(req, ct), cancellationToken).ConfigureAwait(false); response = (policyResult.Outcome == OutcomeType.Successful) ? client.Deserialize(policyResult.Result) : new RestResponse { Request = req, diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Client/ApiResponse.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Client/ApiResponse.cs index 1b7d787c84b..ca2de833a5a 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Client/ApiResponse.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Client/ApiResponse.cs @@ -44,7 +44,7 @@ namespace Org.OpenAPITools.Client /// /// Gets or sets any error text defined by the calling client. /// - String ErrorText { get; set; } + string ErrorText { get; set; } /// /// Gets or sets any cookies passed along on the response. @@ -85,7 +85,7 @@ namespace Org.OpenAPITools.Client /// /// Gets or sets any error text defined by the calling client. /// - public String ErrorText { get; set; } + public string ErrorText { get; set; } /// /// Gets or sets any cookies passed along on the response. diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Client/ClientUtils.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Client/ClientUtils.cs index 2b6e52d6065..3d038d5ce69 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Client/ClientUtils.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Client/ClientUtils.cs @@ -124,7 +124,7 @@ namespace Org.OpenAPITools.Client /// URL encode a string /// Credit/Ref: https://github.com/restsharp/RestSharp/blob/master/RestSharp/Extensions/StringExtensions.cs#L50 /// - /// String to be URL encoded + /// string to be URL encoded /// Byte array public static string UrlEncode(string input) { @@ -158,7 +158,7 @@ namespace Org.OpenAPITools.Client /// /// Encode string in base64 format. /// - /// String to be encoded. + /// string to be encoded. /// Encoded string. public static string Base64Encode(string text) { @@ -186,7 +186,7 @@ namespace Org.OpenAPITools.Client /// /// The Content-Type array to select from. /// The Content-Type header to use. - public static String SelectHeaderContentType(String[] contentTypes) + public static string SelectHeaderContentType(string[] contentTypes) { if (contentTypes.Length == 0) return null; @@ -207,7 +207,7 @@ namespace Org.OpenAPITools.Client /// /// The accepts array to select from. /// The Accept header to use. - public static String SelectHeaderAccept(String[] accepts) + public static string SelectHeaderAccept(string[] accepts) { if (accepts.Length == 0) return null; @@ -215,7 +215,7 @@ namespace Org.OpenAPITools.Client if (accepts.Contains("application/json", StringComparer.OrdinalIgnoreCase)) return "application/json"; - return String.Join(",", accepts); + return string.Join(",", accepts); } /// @@ -233,9 +233,9 @@ namespace Org.OpenAPITools.Client /// /// MIME /// Returns True if MIME type is json. - public static bool IsJsonMime(String mime) + public static bool IsJsonMime(string mime) { - if (String.IsNullOrWhiteSpace(mime)) return false; + if (string.IsNullOrWhiteSpace(mime)) return false; return JsonRegex.IsMatch(mime) || mime.Equals("application/json-patch+json"); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Client/Configuration.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Client/Configuration.cs index 154091fc731..1b80ca62fad 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Client/Configuration.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Client/Configuration.cs @@ -72,7 +72,7 @@ namespace Org.OpenAPITools.Client /// Defines the base path of the target API server. /// Example: http://localhost:3000/v1/ /// - private String _basePath; + private string _basePath; /// /// Gets or sets the API key based on the authentication name. @@ -516,9 +516,9 @@ namespace Org.OpenAPITools.Client /// /// Returns a string with essential information for debugging. /// - public static String ToDebugReport() + public static string ToDebugReport() { - String report = "C# SDK (Org.OpenAPITools) Debug Report:\n"; + 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"; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Client/HttpSigningConfiguration.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Client/HttpSigningConfiguration.cs index 1b9f9b7a99f..1d2d0019cae 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Client/HttpSigningConfiguration.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Client/HttpSigningConfiguration.cs @@ -120,7 +120,7 @@ namespace Org.OpenAPITools.Client } } - var httpValues = HttpUtility.ParseQueryString(String.Empty); + var httpValues = HttpUtility.ParseQueryString(string.Empty); foreach (var parameter in requestOptions.QueryParameters) { #if (NETCOREAPP) @@ -153,7 +153,7 @@ namespace Org.OpenAPITools.Client uriBuilder.Query = httpValues.ToString().Replace("+", "%20"); var dateTime = DateTime.Now; - String Digest = String.Empty; + string Digest = string.Empty; //get the body string requestBody = string.Empty; @@ -230,7 +230,7 @@ namespace Org.OpenAPITools.Client } } - var headersKeysString = String.Join(" ", HttpSignatureHeader.Keys); + var headersKeysString = string.Join(" ", HttpSignatureHeader.Keys); var headerValuesList = new List(); foreach (var keyVal in HttpSignatureHeader) @@ -411,10 +411,10 @@ namespace Org.OpenAPITools.Client return derBytes.ToArray(); } - private RSACryptoServiceProvider GetRSAProviderFromPemFile(String pemfile, SecureString keyPassPharse = null) + private RSACryptoServiceProvider GetRSAProviderFromPemFile(string pemfile, SecureString keyPassPharse = null) { - const String pempubheader = "-----BEGIN PUBLIC KEY-----"; - const String pempubfooter = "-----END PUBLIC KEY-----"; + const string pempubheader = "-----BEGIN PUBLIC KEY-----"; + const string pempubfooter = "-----END PUBLIC KEY-----"; bool isPrivateKeyFile = true; byte[] pemkey = null; @@ -441,11 +441,11 @@ namespace Org.OpenAPITools.Client return null; } - private byte[] ConvertPrivateKeyToBytes(String instr, SecureString keyPassPharse = null) + private byte[] ConvertPrivateKeyToBytes(string instr, SecureString keyPassPharse = null) { - const String pemprivheader = "-----BEGIN RSA PRIVATE KEY-----"; - const String pemprivfooter = "-----END RSA PRIVATE KEY-----"; - String pemstr = instr.Trim(); + 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)) @@ -456,7 +456,7 @@ namespace Org.OpenAPITools.Client StringBuilder sb = new StringBuilder(pemstr); sb.Replace(pemprivheader, ""); sb.Replace(pemprivfooter, ""); - String pvkstr = sb.ToString().Trim(); + string pvkstr = sb.ToString().Trim(); try { // if there are no PEM encryption info lines, this is an UNencrypted PEM private key @@ -472,12 +472,12 @@ namespace Org.OpenAPITools.Client { return null; } - String saltline = str.ReadLine(); + string saltline = str.ReadLine(); if (!saltline.StartsWith("DEK-Info: DES-EDE3-CBC,")) { return null; } - String saltstr = saltline.Substring(saltline.IndexOf(",") + 1).Trim(); + 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); @@ -487,7 +487,7 @@ namespace Org.OpenAPITools.Client } //------ remaining b64 data is encrypted RSA key ---- - String encryptedstr = str.ReadToEnd(); + string encryptedstr = str.ReadToEnd(); try { //should have b64 encrypted RSA key now diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Client/IApiAccessor.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Client/IApiAccessor.cs index 59465ae8e90..2bd76416004 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Client/IApiAccessor.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Client/IApiAccessor.cs @@ -27,7 +27,7 @@ namespace Org.OpenAPITools.Client /// Gets the base path of the API client. /// /// The base path - String GetBasePath(); + string GetBasePath(); /// /// Provides a factory method hook for the creation of exceptions. diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Client/IAsynchronousClient.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Client/IAsynchronousClient.cs index 8a6f726678a..601e86d561c 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Client/IAsynchronousClient.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Client/IAsynchronousClient.cs @@ -29,7 +29,7 @@ namespace Org.OpenAPITools.Client /// 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)); + 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. @@ -40,7 +40,7 @@ namespace Org.OpenAPITools.Client /// 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)); + 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. @@ -51,7 +51,7 @@ namespace Org.OpenAPITools.Client /// 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)); + 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. @@ -62,7 +62,7 @@ namespace Org.OpenAPITools.Client /// 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)); + 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. @@ -73,7 +73,7 @@ namespace Org.OpenAPITools.Client /// 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)); + 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. @@ -84,7 +84,7 @@ namespace Org.OpenAPITools.Client /// 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)); + 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. @@ -95,6 +95,6 @@ namespace Org.OpenAPITools.Client /// 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)); + Task> PatchAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Client/ISynchronousClient.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Client/ISynchronousClient.cs index d27f01a588b..0e0a7fedacf 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Client/ISynchronousClient.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Client/ISynchronousClient.cs @@ -28,7 +28,7 @@ namespace Org.OpenAPITools.Client /// Per-request configurable settings. /// The return type. /// The response data, decorated with - ApiResponse Get(String path, RequestOptions options, IReadableConfiguration configuration = null); + ApiResponse Get(string path, RequestOptions options, IReadableConfiguration configuration = null); /// /// Executes a blocking call to some using the POST http verb. @@ -38,7 +38,7 @@ namespace Org.OpenAPITools.Client /// Per-request configurable settings. /// The return type. /// The response data, decorated with - ApiResponse Post(String path, RequestOptions options, IReadableConfiguration configuration = null); + ApiResponse Post(string path, RequestOptions options, IReadableConfiguration configuration = null); /// /// Executes a blocking call to some using the PUT http verb. @@ -48,7 +48,7 @@ namespace Org.OpenAPITools.Client /// Per-request configurable settings. /// The return type. /// The response data, decorated with - ApiResponse Put(String path, RequestOptions options, IReadableConfiguration configuration = null); + ApiResponse Put(string path, RequestOptions options, IReadableConfiguration configuration = null); /// /// Executes a blocking call to some using the DELETE http verb. @@ -58,7 +58,7 @@ namespace Org.OpenAPITools.Client /// Per-request configurable settings. /// The return type. /// The response data, decorated with - ApiResponse Delete(String path, RequestOptions options, IReadableConfiguration configuration = null); + ApiResponse Delete(string path, RequestOptions options, IReadableConfiguration configuration = null); /// /// Executes a blocking call to some using the HEAD http verb. @@ -68,7 +68,7 @@ namespace Org.OpenAPITools.Client /// Per-request configurable settings. /// The return type. /// The response data, decorated with - ApiResponse Head(String path, RequestOptions options, IReadableConfiguration configuration = null); + ApiResponse Head(string path, RequestOptions options, IReadableConfiguration configuration = null); /// /// Executes a blocking call to some using the OPTIONS http verb. @@ -78,7 +78,7 @@ namespace Org.OpenAPITools.Client /// Per-request configurable settings. /// The return type. /// The response data, decorated with - ApiResponse Options(String path, RequestOptions options, IReadableConfiguration configuration = null); + ApiResponse Options(string path, RequestOptions options, IReadableConfiguration configuration = null); /// /// Executes a blocking call to some using the PATCH http verb. @@ -88,6 +88,6 @@ namespace Org.OpenAPITools.Client /// Per-request configurable settings. /// The return type. /// The response data, decorated with - ApiResponse Patch(String path, RequestOptions options, IReadableConfiguration configuration = null); + ApiResponse Patch(string path, RequestOptions options, IReadableConfiguration configuration = null); } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Client/RequestOptions.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Client/RequestOptions.cs index d8da585db9c..7a1d5b97a88 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Client/RequestOptions.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Client/RequestOptions.cs @@ -24,29 +24,29 @@ namespace Org.OpenAPITools.Client /// /// Parameters to be bound to path parts of the Request's URL /// - public Dictionary PathParameters { get; set; } + 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; } + public Multimap QueryParameters { get; set; } /// /// Header parameters to be applied to to the request. /// Keys may have 1 or more values associated. /// - public Multimap HeaderParameters { get; set; } + public Multimap HeaderParameters { get; set; } /// /// Form parameters to be sent along with the request. /// - public Dictionary FormParameters { get; set; } + public Dictionary FormParameters { get; set; } /// /// File parameters to be sent along with the request. /// - public Dictionary FileParameters { get; set; } + public Dictionary FileParameters { get; set; } /// /// Cookies to be sent along with the request. @@ -67,8 +67,8 @@ namespace Org.OpenAPITools.Client QueryParameters = new Multimap(); HeaderParameters = new Multimap(); FormParameters = new Dictionary(); - FileParameters = new Dictionary(); + FileParameters = new Dictionary(); Cookies = new List(); } } -} \ No newline at end of file +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Fruit.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Fruit.cs index 132be5b4d3b..66de6a1c6f1 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Fruit.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Fruit.cs @@ -162,7 +162,7 @@ namespace Org.OpenAPITools.Model catch (Exception exception) { // deserialization failed, try the next one - System.Diagnostics.Debug.WriteLine(String.Format("Failed to deserialize `{0}` into Apple: {1}", jsonString, exception.ToString())); + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into Apple: {1}", jsonString, exception.ToString())); } try @@ -182,7 +182,7 @@ namespace Org.OpenAPITools.Model catch (Exception exception) { // deserialization failed, try the next one - System.Diagnostics.Debug.WriteLine(String.Format("Failed to deserialize `{0}` into Banana: {1}", jsonString, exception.ToString())); + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into Banana: {1}", jsonString, exception.ToString())); } if (match == 0) @@ -257,7 +257,7 @@ namespace Org.OpenAPITools.Model /// JSON Serializer public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { - writer.WriteRawValue((String)(typeof(Fruit).GetMethod("ToJson").Invoke(value, null))); + writer.WriteRawValue((string)(typeof(Fruit).GetMethod("ToJson").Invoke(value, null))); } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/FruitReq.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/FruitReq.cs index 380896933df..488c489d73a 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/FruitReq.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/FruitReq.cs @@ -171,7 +171,7 @@ namespace Org.OpenAPITools.Model catch (Exception exception) { // deserialization failed, try the next one - System.Diagnostics.Debug.WriteLine(String.Format("Failed to deserialize `{0}` into AppleReq: {1}", jsonString, exception.ToString())); + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into AppleReq: {1}", jsonString, exception.ToString())); } try @@ -191,7 +191,7 @@ namespace Org.OpenAPITools.Model catch (Exception exception) { // deserialization failed, try the next one - System.Diagnostics.Debug.WriteLine(String.Format("Failed to deserialize `{0}` into BananaReq: {1}", jsonString, exception.ToString())); + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into BananaReq: {1}", jsonString, exception.ToString())); } if (match == 0) @@ -266,7 +266,7 @@ namespace Org.OpenAPITools.Model /// JSON Serializer public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { - writer.WriteRawValue((String)(typeof(FruitReq).GetMethod("ToJson").Invoke(value, null))); + writer.WriteRawValue((string)(typeof(FruitReq).GetMethod("ToJson").Invoke(value, null))); } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/GmFruit.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/GmFruit.cs index c168aa41d4c..1aaa59d3f8b 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/GmFruit.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/GmFruit.cs @@ -151,7 +151,7 @@ namespace Org.OpenAPITools.Model catch (Exception exception) { // deserialization failed, try the next one - System.Diagnostics.Debug.WriteLine(String.Format("Failed to deserialize `{0}` into Apple: {1}", jsonString, exception.ToString())); + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into Apple: {1}", jsonString, exception.ToString())); } try @@ -163,7 +163,7 @@ namespace Org.OpenAPITools.Model catch (Exception exception) { // deserialization failed, try the next one - System.Diagnostics.Debug.WriteLine(String.Format("Failed to deserialize `{0}` into Banana: {1}", jsonString, exception.ToString())); + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into Banana: {1}", jsonString, exception.ToString())); } // no match found, throw an exception @@ -229,7 +229,7 @@ namespace Org.OpenAPITools.Model /// JSON Serializer public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { - writer.WriteRawValue((String)(typeof(GmFruit).GetMethod("ToJson").Invoke(value, null))); + writer.WriteRawValue((string)(typeof(GmFruit).GetMethod("ToJson").Invoke(value, null))); } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/HasOnlyReadOnly.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/HasOnlyReadOnly.cs index 3a2c3d26a92..fecd58bf6e8 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/HasOnlyReadOnly.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/HasOnlyReadOnly.cs @@ -55,7 +55,6 @@ namespace Org.OpenAPITools.Model { return false; } - /// /// Gets or Sets Foo /// @@ -70,7 +69,6 @@ namespace Org.OpenAPITools.Model { return false; } - /// /// Gets or Sets additional properties /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Mammal.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Mammal.cs index 2e847a10eb6..ed940d7ab6f 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Mammal.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Mammal.cs @@ -183,7 +183,7 @@ namespace Org.OpenAPITools.Model newMammal = new Mammal(JsonConvert.DeserializeObject(jsonString, Mammal.AdditionalPropertiesSerializerSettings)); return newMammal; default: - System.Diagnostics.Debug.WriteLine(String.Format("Failed to lookup discriminator value `{0}` for Mammal. Possible values: Pig whale zebra", discriminatorValue)); + System.Diagnostics.Debug.WriteLine(string.Format("Failed to lookup discriminator value `{0}` for Mammal. Possible values: Pig whale zebra", discriminatorValue)); break; } @@ -207,7 +207,7 @@ namespace Org.OpenAPITools.Model catch (Exception exception) { // deserialization failed, try the next one - System.Diagnostics.Debug.WriteLine(String.Format("Failed to deserialize `{0}` into Pig: {1}", jsonString, exception.ToString())); + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into Pig: {1}", jsonString, exception.ToString())); } try @@ -227,7 +227,7 @@ namespace Org.OpenAPITools.Model catch (Exception exception) { // deserialization failed, try the next one - System.Diagnostics.Debug.WriteLine(String.Format("Failed to deserialize `{0}` into Whale: {1}", jsonString, exception.ToString())); + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into Whale: {1}", jsonString, exception.ToString())); } try @@ -247,7 +247,7 @@ namespace Org.OpenAPITools.Model catch (Exception exception) { // deserialization failed, try the next one - System.Diagnostics.Debug.WriteLine(String.Format("Failed to deserialize `{0}` into Zebra: {1}", jsonString, exception.ToString())); + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into Zebra: {1}", jsonString, exception.ToString())); } if (match == 0) @@ -322,7 +322,7 @@ namespace Org.OpenAPITools.Model /// JSON Serializer public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { - writer.WriteRawValue((String)(typeof(Mammal).GetMethod("ToJson").Invoke(value, null))); + writer.WriteRawValue((string)(typeof(Mammal).GetMethod("ToJson").Invoke(value, null))); } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Name.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Name.cs index a6a01dd4ed3..0f5da18eafa 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Name.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Name.cs @@ -72,7 +72,6 @@ namespace Org.OpenAPITools.Model { return false; } - /// /// Gets or Sets Property /// @@ -93,7 +92,6 @@ namespace Org.OpenAPITools.Model { return false; } - /// /// Gets or Sets additional properties /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/NullableShape.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/NullableShape.cs index 80339ebf79b..20be30e5b89 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/NullableShape.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/NullableShape.cs @@ -163,7 +163,7 @@ namespace Org.OpenAPITools.Model newNullableShape = new NullableShape(JsonConvert.DeserializeObject(jsonString, NullableShape.AdditionalPropertiesSerializerSettings)); return newNullableShape; default: - System.Diagnostics.Debug.WriteLine(String.Format("Failed to lookup discriminator value `{0}` for NullableShape. Possible values: Quadrilateral Triangle", discriminatorValue)); + System.Diagnostics.Debug.WriteLine(string.Format("Failed to lookup discriminator value `{0}` for NullableShape. Possible values: Quadrilateral Triangle", discriminatorValue)); break; } @@ -187,7 +187,7 @@ namespace Org.OpenAPITools.Model catch (Exception exception) { // deserialization failed, try the next one - System.Diagnostics.Debug.WriteLine(String.Format("Failed to deserialize `{0}` into Quadrilateral: {1}", jsonString, exception.ToString())); + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into Quadrilateral: {1}", jsonString, exception.ToString())); } try @@ -207,7 +207,7 @@ namespace Org.OpenAPITools.Model catch (Exception exception) { // deserialization failed, try the next one - System.Diagnostics.Debug.WriteLine(String.Format("Failed to deserialize `{0}` into Triangle: {1}", jsonString, exception.ToString())); + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into Triangle: {1}", jsonString, exception.ToString())); } if (match == 0) @@ -282,7 +282,7 @@ namespace Org.OpenAPITools.Model /// JSON Serializer public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { - writer.WriteRawValue((String)(typeof(NullableShape).GetMethod("ToJson").Invoke(value, null))); + writer.WriteRawValue((string)(typeof(NullableShape).GetMethod("ToJson").Invoke(value, null))); } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Pig.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Pig.cs index d8605861e63..967d2139a0a 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Pig.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Pig.cs @@ -154,7 +154,7 @@ namespace Org.OpenAPITools.Model newPig = new Pig(JsonConvert.DeserializeObject(jsonString, Pig.AdditionalPropertiesSerializerSettings)); return newPig; default: - System.Diagnostics.Debug.WriteLine(String.Format("Failed to lookup discriminator value `{0}` for Pig. Possible values: BasquePig DanishPig", discriminatorValue)); + System.Diagnostics.Debug.WriteLine(string.Format("Failed to lookup discriminator value `{0}` for Pig. Possible values: BasquePig DanishPig", discriminatorValue)); break; } @@ -178,7 +178,7 @@ namespace Org.OpenAPITools.Model catch (Exception exception) { // deserialization failed, try the next one - System.Diagnostics.Debug.WriteLine(String.Format("Failed to deserialize `{0}` into BasquePig: {1}", jsonString, exception.ToString())); + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into BasquePig: {1}", jsonString, exception.ToString())); } try @@ -198,7 +198,7 @@ namespace Org.OpenAPITools.Model catch (Exception exception) { // deserialization failed, try the next one - System.Diagnostics.Debug.WriteLine(String.Format("Failed to deserialize `{0}` into DanishPig: {1}", jsonString, exception.ToString())); + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into DanishPig: {1}", jsonString, exception.ToString())); } if (match == 0) @@ -273,7 +273,7 @@ namespace Org.OpenAPITools.Model /// JSON Serializer public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { - writer.WriteRawValue((String)(typeof(Pig).GetMethod("ToJson").Invoke(value, null))); + writer.WriteRawValue((string)(typeof(Pig).GetMethod("ToJson").Invoke(value, null))); } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Quadrilateral.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Quadrilateral.cs index 17463ca09a4..19bc98ed2ec 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Quadrilateral.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Quadrilateral.cs @@ -154,7 +154,7 @@ namespace Org.OpenAPITools.Model newQuadrilateral = new Quadrilateral(JsonConvert.DeserializeObject(jsonString, Quadrilateral.AdditionalPropertiesSerializerSettings)); return newQuadrilateral; default: - System.Diagnostics.Debug.WriteLine(String.Format("Failed to lookup discriminator value `{0}` for Quadrilateral. Possible values: ComplexQuadrilateral SimpleQuadrilateral", discriminatorValue)); + System.Diagnostics.Debug.WriteLine(string.Format("Failed to lookup discriminator value `{0}` for Quadrilateral. Possible values: ComplexQuadrilateral SimpleQuadrilateral", discriminatorValue)); break; } @@ -178,7 +178,7 @@ namespace Org.OpenAPITools.Model catch (Exception exception) { // deserialization failed, try the next one - System.Diagnostics.Debug.WriteLine(String.Format("Failed to deserialize `{0}` into ComplexQuadrilateral: {1}", jsonString, exception.ToString())); + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into ComplexQuadrilateral: {1}", jsonString, exception.ToString())); } try @@ -198,7 +198,7 @@ namespace Org.OpenAPITools.Model catch (Exception exception) { // deserialization failed, try the next one - System.Diagnostics.Debug.WriteLine(String.Format("Failed to deserialize `{0}` into SimpleQuadrilateral: {1}", jsonString, exception.ToString())); + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into SimpleQuadrilateral: {1}", jsonString, exception.ToString())); } if (match == 0) @@ -273,7 +273,7 @@ namespace Org.OpenAPITools.Model /// JSON Serializer public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { - writer.WriteRawValue((String)(typeof(Quadrilateral).GetMethod("ToJson").Invoke(value, null))); + writer.WriteRawValue((string)(typeof(Quadrilateral).GetMethod("ToJson").Invoke(value, null))); } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/ReadOnlyFirst.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/ReadOnlyFirst.cs index 4ab8f7d5c6a..20483c31cdc 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/ReadOnlyFirst.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/ReadOnlyFirst.cs @@ -56,7 +56,6 @@ namespace Org.OpenAPITools.Model { return false; } - /// /// Gets or Sets Baz /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Shape.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Shape.cs index e75e0e8b167..f17c4d9a8f5 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Shape.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Shape.cs @@ -154,7 +154,7 @@ namespace Org.OpenAPITools.Model newShape = new Shape(JsonConvert.DeserializeObject(jsonString, Shape.AdditionalPropertiesSerializerSettings)); return newShape; default: - System.Diagnostics.Debug.WriteLine(String.Format("Failed to lookup discriminator value `{0}` for Shape. Possible values: Quadrilateral Triangle", discriminatorValue)); + System.Diagnostics.Debug.WriteLine(string.Format("Failed to lookup discriminator value `{0}` for Shape. Possible values: Quadrilateral Triangle", discriminatorValue)); break; } @@ -178,7 +178,7 @@ namespace Org.OpenAPITools.Model catch (Exception exception) { // deserialization failed, try the next one - System.Diagnostics.Debug.WriteLine(String.Format("Failed to deserialize `{0}` into Quadrilateral: {1}", jsonString, exception.ToString())); + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into Quadrilateral: {1}", jsonString, exception.ToString())); } try @@ -198,7 +198,7 @@ namespace Org.OpenAPITools.Model catch (Exception exception) { // deserialization failed, try the next one - System.Diagnostics.Debug.WriteLine(String.Format("Failed to deserialize `{0}` into Triangle: {1}", jsonString, exception.ToString())); + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into Triangle: {1}", jsonString, exception.ToString())); } if (match == 0) @@ -273,7 +273,7 @@ namespace Org.OpenAPITools.Model /// JSON Serializer public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { - writer.WriteRawValue((String)(typeof(Shape).GetMethod("ToJson").Invoke(value, null))); + writer.WriteRawValue((string)(typeof(Shape).GetMethod("ToJson").Invoke(value, null))); } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/ShapeOrNull.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/ShapeOrNull.cs index 7471bafb379..df321dc9e81 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/ShapeOrNull.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/ShapeOrNull.cs @@ -163,7 +163,7 @@ namespace Org.OpenAPITools.Model newShapeOrNull = new ShapeOrNull(JsonConvert.DeserializeObject(jsonString, ShapeOrNull.AdditionalPropertiesSerializerSettings)); return newShapeOrNull; default: - System.Diagnostics.Debug.WriteLine(String.Format("Failed to lookup discriminator value `{0}` for ShapeOrNull. Possible values: Quadrilateral Triangle", discriminatorValue)); + System.Diagnostics.Debug.WriteLine(string.Format("Failed to lookup discriminator value `{0}` for ShapeOrNull. Possible values: Quadrilateral Triangle", discriminatorValue)); break; } @@ -187,7 +187,7 @@ namespace Org.OpenAPITools.Model catch (Exception exception) { // deserialization failed, try the next one - System.Diagnostics.Debug.WriteLine(String.Format("Failed to deserialize `{0}` into Quadrilateral: {1}", jsonString, exception.ToString())); + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into Quadrilateral: {1}", jsonString, exception.ToString())); } try @@ -207,7 +207,7 @@ namespace Org.OpenAPITools.Model catch (Exception exception) { // deserialization failed, try the next one - System.Diagnostics.Debug.WriteLine(String.Format("Failed to deserialize `{0}` into Triangle: {1}", jsonString, exception.ToString())); + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into Triangle: {1}", jsonString, exception.ToString())); } if (match == 0) @@ -282,7 +282,7 @@ namespace Org.OpenAPITools.Model /// JSON Serializer public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { - writer.WriteRawValue((String)(typeof(ShapeOrNull).GetMethod("ToJson").Invoke(value, null))); + writer.WriteRawValue((string)(typeof(ShapeOrNull).GetMethod("ToJson").Invoke(value, null))); } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Triangle.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Triangle.cs index cccaa79a8ff..6f33859a898 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Triangle.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Triangle.cs @@ -183,7 +183,7 @@ namespace Org.OpenAPITools.Model newTriangle = new Triangle(JsonConvert.DeserializeObject(jsonString, Triangle.AdditionalPropertiesSerializerSettings)); return newTriangle; default: - System.Diagnostics.Debug.WriteLine(String.Format("Failed to lookup discriminator value `{0}` for Triangle. Possible values: EquilateralTriangle IsoscelesTriangle ScaleneTriangle", discriminatorValue)); + System.Diagnostics.Debug.WriteLine(string.Format("Failed to lookup discriminator value `{0}` for Triangle. Possible values: EquilateralTriangle IsoscelesTriangle ScaleneTriangle", discriminatorValue)); break; } @@ -207,7 +207,7 @@ namespace Org.OpenAPITools.Model catch (Exception exception) { // deserialization failed, try the next one - System.Diagnostics.Debug.WriteLine(String.Format("Failed to deserialize `{0}` into EquilateralTriangle: {1}", jsonString, exception.ToString())); + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into EquilateralTriangle: {1}", jsonString, exception.ToString())); } try @@ -227,7 +227,7 @@ namespace Org.OpenAPITools.Model catch (Exception exception) { // deserialization failed, try the next one - System.Diagnostics.Debug.WriteLine(String.Format("Failed to deserialize `{0}` into IsoscelesTriangle: {1}", jsonString, exception.ToString())); + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into IsoscelesTriangle: {1}", jsonString, exception.ToString())); } try @@ -247,7 +247,7 @@ namespace Org.OpenAPITools.Model catch (Exception exception) { // deserialization failed, try the next one - System.Diagnostics.Debug.WriteLine(String.Format("Failed to deserialize `{0}` into ScaleneTriangle: {1}", jsonString, exception.ToString())); + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into ScaleneTriangle: {1}", jsonString, exception.ToString())); } if (match == 0) @@ -322,7 +322,7 @@ namespace Org.OpenAPITools.Model /// JSON Serializer public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { - writer.WriteRawValue((String)(typeof(Triangle).GetMethod("ToJson").Invoke(value, null))); + writer.WriteRawValue((string)(typeof(Triangle).GetMethod("ToJson").Invoke(value, null))); } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/.openapi-generator/VERSION b/samples/client/petstore/csharp-netcore/OpenAPIClient/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/.openapi-generator/VERSION +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Api/AnotherFakeApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Api/AnotherFakeApi.cs index 94d8b854b0d..ad48306e00c 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Api/AnotherFakeApi.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Api/AnotherFakeApi.cs @@ -109,7 +109,7 @@ namespace Org.OpenAPITools.Api /// Initializes a new instance of the class. /// /// - public AnotherFakeApi(String basePath) + public AnotherFakeApi(string basePath) { this.Configuration = Org.OpenAPITools.Client.Configuration.MergeConfigurations( Org.OpenAPITools.Client.GlobalConfiguration.Instance, @@ -172,7 +172,7 @@ namespace Org.OpenAPITools.Api /// Gets the base path of the API client. /// /// The base path - public String GetBasePath() + public string GetBasePath() { return this.Configuration.BasePath; } @@ -225,12 +225,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/json" }; @@ -284,12 +284,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/json" }; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Api/DefaultApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Api/DefaultApi.cs index 27789c4533a..8844aca4ab7 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Api/DefaultApi.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Api/DefaultApi.cs @@ -102,7 +102,7 @@ namespace Org.OpenAPITools.Api /// Initializes a new instance of the class. /// /// - public DefaultApi(String basePath) + public DefaultApi(string basePath) { this.Configuration = Org.OpenAPITools.Client.Configuration.MergeConfigurations( Org.OpenAPITools.Client.GlobalConfiguration.Instance, @@ -165,7 +165,7 @@ namespace Org.OpenAPITools.Api /// Gets the base path of the API client. /// /// The base path - public String GetBasePath() + public string GetBasePath() { return this.Configuration.BasePath; } @@ -212,11 +212,11 @@ namespace Org.OpenAPITools.Api { Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/json" }; @@ -263,11 +263,11 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/json" }; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Api/FakeApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Api/FakeApi.cs index d7749151314..fe862283f1e 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Api/FakeApi.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Api/FakeApi.cs @@ -826,7 +826,7 @@ namespace Org.OpenAPITools.Api /// Initializes a new instance of the class. /// /// - public FakeApi(String basePath) + public FakeApi(string basePath) { this.Configuration = Org.OpenAPITools.Client.Configuration.MergeConfigurations( Org.OpenAPITools.Client.GlobalConfiguration.Instance, @@ -889,7 +889,7 @@ namespace Org.OpenAPITools.Api /// Gets the base path of the API client. /// /// The base path - public String GetBasePath() + public string GetBasePath() { return this.Configuration.BasePath; } @@ -936,11 +936,11 @@ namespace Org.OpenAPITools.Api { Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/json" }; @@ -987,11 +987,11 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/json" }; @@ -1039,12 +1039,12 @@ namespace Org.OpenAPITools.Api { Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "*/*" }; @@ -1094,12 +1094,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "*/*" }; @@ -1148,12 +1148,12 @@ namespace Org.OpenAPITools.Api { Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "*/*" }; @@ -1203,12 +1203,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "*/*" }; @@ -1257,12 +1257,12 @@ namespace Org.OpenAPITools.Api { Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "*/*" }; @@ -1312,12 +1312,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "*/*" }; @@ -1366,12 +1366,12 @@ namespace Org.OpenAPITools.Api { Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "*/*" }; @@ -1421,12 +1421,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "*/*" }; @@ -1473,11 +1473,11 @@ namespace Org.OpenAPITools.Api { Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/json" }; @@ -1524,11 +1524,11 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/json" }; @@ -1579,12 +1579,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); @@ -1636,12 +1636,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; @@ -1698,12 +1698,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); @@ -1762,12 +1762,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; @@ -1820,12 +1820,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/json" }; @@ -1879,12 +1879,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/json" }; @@ -1966,12 +1966,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/x-www-form-urlencoded" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); @@ -2027,7 +2027,7 @@ namespace Org.OpenAPITools.Api // authentication (http_basic_test) required // http basic authentication required - if (!String.IsNullOrEmpty(this.Configuration.Username) || !String.IsNullOrEmpty(this.Configuration.Password)) + if (!string.IsNullOrEmpty(this.Configuration.Username) || !string.IsNullOrEmpty(this.Configuration.Password)) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Basic " + Org.OpenAPITools.Client.ClientUtils.Base64Encode(this.Configuration.Username + ":" + this.Configuration.Password)); } @@ -2102,12 +2102,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/x-www-form-urlencoded" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; @@ -2164,7 +2164,7 @@ namespace Org.OpenAPITools.Api // authentication (http_basic_test) required // http basic authentication required - if (!String.IsNullOrEmpty(this.Configuration.Username) || !String.IsNullOrEmpty(this.Configuration.Password)) + if (!string.IsNullOrEmpty(this.Configuration.Username) || !string.IsNullOrEmpty(this.Configuration.Password)) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Basic " + Org.OpenAPITools.Client.ClientUtils.Base64Encode(this.Configuration.Username + ":" + this.Configuration.Password)); } @@ -2217,12 +2217,12 @@ namespace Org.OpenAPITools.Api { Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/x-www-form-urlencoded" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); @@ -2315,12 +2315,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/x-www-form-urlencoded" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; @@ -2408,11 +2408,11 @@ namespace Org.OpenAPITools.Api { Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); @@ -2439,7 +2439,7 @@ namespace Org.OpenAPITools.Api // authentication (bearer_test) required // bearer authentication required - if (!String.IsNullOrEmpty(this.Configuration.AccessToken)) + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); } @@ -2490,11 +2490,11 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; @@ -2522,7 +2522,7 @@ namespace Org.OpenAPITools.Api // authentication (bearer_test) required // bearer authentication required - if (!String.IsNullOrEmpty(this.Configuration.AccessToken)) + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); } @@ -2565,12 +2565,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); @@ -2622,12 +2622,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; @@ -2684,12 +2684,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/x-www-form-urlencoded" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); @@ -2748,12 +2748,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/x-www-form-urlencoded" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; @@ -2829,11 +2829,11 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); @@ -2913,11 +2913,11 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Api/FakeClassnameTags123Api.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Api/FakeClassnameTags123Api.cs index 56ebdf5fd10..d4fbb5868ad 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Api/FakeClassnameTags123Api.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Api/FakeClassnameTags123Api.cs @@ -109,7 +109,7 @@ namespace Org.OpenAPITools.Api /// Initializes a new instance of the class. /// /// - public FakeClassnameTags123Api(String basePath) + public FakeClassnameTags123Api(string basePath) { this.Configuration = Org.OpenAPITools.Client.Configuration.MergeConfigurations( Org.OpenAPITools.Client.GlobalConfiguration.Instance, @@ -172,7 +172,7 @@ namespace Org.OpenAPITools.Api /// Gets the base path of the API client. /// /// The base path - public String GetBasePath() + public string GetBasePath() { return this.Configuration.BasePath; } @@ -225,12 +225,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/json" }; @@ -243,7 +243,7 @@ namespace Org.OpenAPITools.Api localVarRequestOptions.Data = modelClient; // authentication (api_key_query) required - if (!String.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("api_key_query"))) + 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"))); } @@ -289,12 +289,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/json" }; @@ -308,7 +308,7 @@ namespace Org.OpenAPITools.Api localVarRequestOptions.Data = modelClient; // authentication (api_key_query) required - if (!String.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("api_key_query"))) + 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"))); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Api/PetApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Api/PetApi.cs index 61759145f12..2bf19af1b1a 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Api/PetApi.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Api/PetApi.cs @@ -471,7 +471,7 @@ namespace Org.OpenAPITools.Api /// Initializes a new instance of the class. /// /// - public PetApi(String basePath) + public PetApi(string basePath) { this.Configuration = Org.OpenAPITools.Client.Configuration.MergeConfigurations( Org.OpenAPITools.Client.GlobalConfiguration.Instance, @@ -534,7 +534,7 @@ namespace Org.OpenAPITools.Api /// Gets the base path of the API client. /// /// The base path - public String GetBasePath() + public string GetBasePath() { return this.Configuration.BasePath; } @@ -586,13 +586,13 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json", "application/xml" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); @@ -621,7 +621,7 @@ namespace Org.OpenAPITools.Api } // authentication (petstore_auth) required // oauth required - if (!String.IsNullOrEmpty(this.Configuration.AccessToken)) + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); } @@ -666,13 +666,13 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json", "application/xml" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; @@ -702,7 +702,7 @@ namespace Org.OpenAPITools.Api } // authentication (petstore_auth) required // oauth required - if (!String.IsNullOrEmpty(this.Configuration.AccessToken)) + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); } @@ -743,11 +743,11 @@ namespace Org.OpenAPITools.Api { Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); @@ -764,7 +764,7 @@ namespace Org.OpenAPITools.Api // authentication (petstore_auth) required // oauth required - if (!String.IsNullOrEmpty(this.Configuration.AccessToken)) + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); } @@ -807,11 +807,11 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; @@ -829,7 +829,7 @@ namespace Org.OpenAPITools.Api // authentication (petstore_auth) required // oauth required - if (!String.IsNullOrEmpty(this.Configuration.AccessToken)) + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); } @@ -873,11 +873,11 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/xml", "application/json" }; @@ -908,7 +908,7 @@ namespace Org.OpenAPITools.Api } // authentication (petstore_auth) required // oauth required - if (!String.IsNullOrEmpty(this.Configuration.AccessToken)) + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); } @@ -954,11 +954,11 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/xml", "application/json" }; @@ -990,7 +990,7 @@ namespace Org.OpenAPITools.Api } // authentication (petstore_auth) required // oauth required - if (!String.IsNullOrEmpty(this.Configuration.AccessToken)) + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); } @@ -1034,11 +1034,11 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/xml", "application/json" }; @@ -1069,7 +1069,7 @@ namespace Org.OpenAPITools.Api } // authentication (petstore_auth) required // oauth required - if (!String.IsNullOrEmpty(this.Configuration.AccessToken)) + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); } @@ -1115,11 +1115,11 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/xml", "application/json" }; @@ -1151,7 +1151,7 @@ namespace Org.OpenAPITools.Api } // authentication (petstore_auth) required // oauth required - if (!String.IsNullOrEmpty(this.Configuration.AccessToken)) + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); } @@ -1191,11 +1191,11 @@ namespace Org.OpenAPITools.Api { Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/xml", "application/json" }; @@ -1209,7 +1209,7 @@ namespace Org.OpenAPITools.Api localVarRequestOptions.PathParameters.Add("petId", Org.OpenAPITools.Client.ClientUtils.ParameterToString(petId)); // path parameter // authentication (api_key) required - if (!String.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("api_key"))) + if (!string.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("api_key"))) { localVarRequestOptions.HeaderParameters.Add("api_key", this.Configuration.GetApiKeyWithPrefix("api_key")); } @@ -1251,11 +1251,11 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/xml", "application/json" }; @@ -1270,7 +1270,7 @@ namespace Org.OpenAPITools.Api localVarRequestOptions.PathParameters.Add("petId", Org.OpenAPITools.Client.ClientUtils.ParameterToString(petId)); // path parameter // authentication (api_key) required - if (!String.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("api_key"))) + if (!string.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("api_key"))) { localVarRequestOptions.HeaderParameters.Add("api_key", this.Configuration.GetApiKeyWithPrefix("api_key")); } @@ -1313,13 +1313,13 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json", "application/xml" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); @@ -1348,7 +1348,7 @@ namespace Org.OpenAPITools.Api } // authentication (petstore_auth) required // oauth required - if (!String.IsNullOrEmpty(this.Configuration.AccessToken)) + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); } @@ -1393,13 +1393,13 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json", "application/xml" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; @@ -1429,7 +1429,7 @@ namespace Org.OpenAPITools.Api } // authentication (petstore_auth) required // oauth required - if (!String.IsNullOrEmpty(this.Configuration.AccessToken)) + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); } @@ -1472,12 +1472,12 @@ namespace Org.OpenAPITools.Api { Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/x-www-form-urlencoded" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); @@ -1498,7 +1498,7 @@ namespace Org.OpenAPITools.Api // authentication (petstore_auth) required // oauth required - if (!String.IsNullOrEmpty(this.Configuration.AccessToken)) + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); } @@ -1543,12 +1543,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/x-www-form-urlencoded" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; @@ -1570,7 +1570,7 @@ namespace Org.OpenAPITools.Api // authentication (petstore_auth) required // oauth required - if (!String.IsNullOrEmpty(this.Configuration.AccessToken)) + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); } @@ -1614,12 +1614,12 @@ namespace Org.OpenAPITools.Api { Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "multipart/form-data" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/json" }; @@ -1641,7 +1641,7 @@ namespace Org.OpenAPITools.Api // authentication (petstore_auth) required // oauth required - if (!String.IsNullOrEmpty(this.Configuration.AccessToken)) + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); } @@ -1687,12 +1687,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "multipart/form-data" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/json" }; @@ -1715,7 +1715,7 @@ namespace Org.OpenAPITools.Api // authentication (petstore_auth) required // oauth required - if (!String.IsNullOrEmpty(this.Configuration.AccessToken)) + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); } @@ -1763,12 +1763,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "multipart/form-data" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/json" }; @@ -1787,7 +1787,7 @@ namespace Org.OpenAPITools.Api // authentication (petstore_auth) required // oauth required - if (!String.IsNullOrEmpty(this.Configuration.AccessToken)) + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); } @@ -1837,12 +1837,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "multipart/form-data" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/json" }; @@ -1862,7 +1862,7 @@ namespace Org.OpenAPITools.Api // authentication (petstore_auth) required // oauth required - if (!String.IsNullOrEmpty(this.Configuration.AccessToken)) + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Api/StoreApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Api/StoreApi.cs index 6ab56c9e9bf..ad7387db705 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Api/StoreApi.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Api/StoreApi.cs @@ -234,7 +234,7 @@ namespace Org.OpenAPITools.Api /// Initializes a new instance of the class. /// /// - public StoreApi(String basePath) + public StoreApi(string basePath) { this.Configuration = Org.OpenAPITools.Client.Configuration.MergeConfigurations( Org.OpenAPITools.Client.GlobalConfiguration.Instance, @@ -297,7 +297,7 @@ namespace Org.OpenAPITools.Api /// Gets the base path of the API client. /// /// The base path - public String GetBasePath() + public string GetBasePath() { return this.Configuration.BasePath; } @@ -349,11 +349,11 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); @@ -405,11 +405,11 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; @@ -455,11 +455,11 @@ namespace Org.OpenAPITools.Api { Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/json" }; @@ -471,7 +471,7 @@ namespace Org.OpenAPITools.Api // authentication (api_key) required - if (!String.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("api_key"))) + if (!string.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("api_key"))) { localVarRequestOptions.HeaderParameters.Add("api_key", this.Configuration.GetApiKeyWithPrefix("api_key")); } @@ -511,11 +511,11 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/json" }; @@ -528,7 +528,7 @@ namespace Org.OpenAPITools.Api // authentication (api_key) required - if (!String.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("api_key"))) + if (!string.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("api_key"))) { localVarRequestOptions.HeaderParameters.Add("api_key", this.Configuration.GetApiKeyWithPrefix("api_key")); } @@ -568,11 +568,11 @@ namespace Org.OpenAPITools.Api { Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/xml", "application/json" }; @@ -623,11 +623,11 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/xml", "application/json" }; @@ -681,12 +681,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/xml", "application/json" }; @@ -741,12 +741,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/xml", "application/json" }; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Api/UserApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Api/UserApi.cs index 80436c9b433..a2f2598c8ac 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Api/UserApi.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Api/UserApi.cs @@ -406,7 +406,7 @@ namespace Org.OpenAPITools.Api /// Initializes a new instance of the class. /// /// - public UserApi(String basePath) + public UserApi(string basePath) { this.Configuration = Org.OpenAPITools.Client.Configuration.MergeConfigurations( Org.OpenAPITools.Client.GlobalConfiguration.Instance, @@ -469,7 +469,7 @@ namespace Org.OpenAPITools.Api /// Gets the base path of the API client. /// /// The base path - public String GetBasePath() + public string GetBasePath() { return this.Configuration.BasePath; } @@ -521,12 +521,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); @@ -578,12 +578,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; @@ -634,12 +634,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); @@ -691,12 +691,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; @@ -747,12 +747,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); @@ -804,12 +804,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; @@ -860,11 +860,11 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); @@ -916,11 +916,11 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; @@ -972,11 +972,11 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/xml", "application/json" }; @@ -1031,11 +1031,11 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/xml", "application/json" }; @@ -1095,11 +1095,11 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/xml", "application/json" }; @@ -1161,11 +1161,11 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/xml", "application/json" }; @@ -1213,11 +1213,11 @@ namespace Org.OpenAPITools.Api { Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); @@ -1262,11 +1262,11 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; @@ -1322,12 +1322,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); @@ -1386,12 +1386,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Client/ApiClient.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Client/ApiClient.cs index c3d43b29bb4..e3647002317 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Client/ApiClient.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Client/ApiClient.cs @@ -106,7 +106,7 @@ namespace Org.OpenAPITools.Client var bytes = response.RawBytes; if (response.Headers != null) { - var filePath = String.IsNullOrEmpty(_configuration.TempFolderPath) + var filePath = string.IsNullOrEmpty(_configuration.TempFolderPath) ? Path.GetTempPath() : _configuration.TempFolderPath; var regex = new Regex(@"Content-Disposition=.*filename=['""]?([^'""\s]+)['""]?$"); @@ -130,7 +130,7 @@ namespace Org.OpenAPITools.Client return DateTime.Parse(response.Content, null, System.Globalization.DateTimeStyles.RoundtripKind); } - if (type == typeof(String) || type.Name.StartsWith("System.Nullable")) // return primitive type + if (type == typeof(string) || type.Name.StartsWith("System.Nullable")) // return primitive type { return Convert.ChangeType(response.Content, type); } @@ -162,7 +162,7 @@ namespace Org.OpenAPITools.Client /// public partial class ApiClient : ISynchronousClient, IAsynchronousClient { - private readonly String _baseUrl; + private readonly string _baseUrl; /// /// Specifies the settings on a object. @@ -207,7 +207,7 @@ namespace Org.OpenAPITools.Client /// /// The target service's base path in URL format. /// - public ApiClient(String basePath) + public ApiClient(string basePath) { if (string.IsNullOrEmpty(basePath)) throw new ArgumentException("basePath cannot be empty"); @@ -268,7 +268,7 @@ namespace Org.OpenAPITools.Client /// private RestRequest NewRequest( HttpMethod method, - String path, + string path, RequestOptions options, IReadableConfiguration configuration) { @@ -591,7 +591,7 @@ namespace Org.OpenAPITools.Client if (RetryConfiguration.AsyncRetryPolicy != null) { var policy = RetryConfiguration.AsyncRetryPolicy; - var policyResult = await policy.ExecuteAndCaptureAsync(() => client.ExecuteAsync(req, cancellationToken)).ConfigureAwait(false); + var policyResult = await policy.ExecuteAndCaptureAsync((ct) => client.ExecuteAsync(req, ct), cancellationToken).ConfigureAwait(false); response = (policyResult.Outcome == OutcomeType.Successful) ? client.Deserialize(policyResult.Result) : new RestResponse { Request = req, diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Client/ApiResponse.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Client/ApiResponse.cs index 1b7d787c84b..ca2de833a5a 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Client/ApiResponse.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Client/ApiResponse.cs @@ -44,7 +44,7 @@ namespace Org.OpenAPITools.Client /// /// Gets or sets any error text defined by the calling client. /// - String ErrorText { get; set; } + string ErrorText { get; set; } /// /// Gets or sets any cookies passed along on the response. @@ -85,7 +85,7 @@ namespace Org.OpenAPITools.Client /// /// Gets or sets any error text defined by the calling client. /// - public String ErrorText { get; set; } + public string ErrorText { get; set; } /// /// Gets or sets any cookies passed along on the response. diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Client/ClientUtils.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Client/ClientUtils.cs index 2b6e52d6065..3d038d5ce69 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Client/ClientUtils.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Client/ClientUtils.cs @@ -124,7 +124,7 @@ namespace Org.OpenAPITools.Client /// URL encode a string /// Credit/Ref: https://github.com/restsharp/RestSharp/blob/master/RestSharp/Extensions/StringExtensions.cs#L50 /// - /// String to be URL encoded + /// string to be URL encoded /// Byte array public static string UrlEncode(string input) { @@ -158,7 +158,7 @@ namespace Org.OpenAPITools.Client /// /// Encode string in base64 format. /// - /// String to be encoded. + /// string to be encoded. /// Encoded string. public static string Base64Encode(string text) { @@ -186,7 +186,7 @@ namespace Org.OpenAPITools.Client /// /// The Content-Type array to select from. /// The Content-Type header to use. - public static String SelectHeaderContentType(String[] contentTypes) + public static string SelectHeaderContentType(string[] contentTypes) { if (contentTypes.Length == 0) return null; @@ -207,7 +207,7 @@ namespace Org.OpenAPITools.Client /// /// The accepts array to select from. /// The Accept header to use. - public static String SelectHeaderAccept(String[] accepts) + public static string SelectHeaderAccept(string[] accepts) { if (accepts.Length == 0) return null; @@ -215,7 +215,7 @@ namespace Org.OpenAPITools.Client if (accepts.Contains("application/json", StringComparer.OrdinalIgnoreCase)) return "application/json"; - return String.Join(",", accepts); + return string.Join(",", accepts); } /// @@ -233,9 +233,9 @@ namespace Org.OpenAPITools.Client /// /// MIME /// Returns True if MIME type is json. - public static bool IsJsonMime(String mime) + public static bool IsJsonMime(string mime) { - if (String.IsNullOrWhiteSpace(mime)) return false; + if (string.IsNullOrWhiteSpace(mime)) return false; return JsonRegex.IsMatch(mime) || mime.Equals("application/json-patch+json"); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Client/Configuration.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Client/Configuration.cs index bca7db624cd..06154ad382c 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Client/Configuration.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Client/Configuration.cs @@ -67,7 +67,7 @@ namespace Org.OpenAPITools.Client /// Defines the base path of the target API server. /// Example: http://localhost:3000/v1/ /// - private String _basePath; + private string _basePath; /// /// Gets or sets the API key based on the authentication name. @@ -511,9 +511,9 @@ namespace Org.OpenAPITools.Client /// /// Returns a string with essential information for debugging. /// - public static String ToDebugReport() + public static string ToDebugReport() { - String report = "C# SDK (Org.OpenAPITools) Debug Report:\n"; + 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"; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Client/HttpSigningConfiguration.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Client/HttpSigningConfiguration.cs index 1b9f9b7a99f..1d2d0019cae 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Client/HttpSigningConfiguration.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Client/HttpSigningConfiguration.cs @@ -120,7 +120,7 @@ namespace Org.OpenAPITools.Client } } - var httpValues = HttpUtility.ParseQueryString(String.Empty); + var httpValues = HttpUtility.ParseQueryString(string.Empty); foreach (var parameter in requestOptions.QueryParameters) { #if (NETCOREAPP) @@ -153,7 +153,7 @@ namespace Org.OpenAPITools.Client uriBuilder.Query = httpValues.ToString().Replace("+", "%20"); var dateTime = DateTime.Now; - String Digest = String.Empty; + string Digest = string.Empty; //get the body string requestBody = string.Empty; @@ -230,7 +230,7 @@ namespace Org.OpenAPITools.Client } } - var headersKeysString = String.Join(" ", HttpSignatureHeader.Keys); + var headersKeysString = string.Join(" ", HttpSignatureHeader.Keys); var headerValuesList = new List(); foreach (var keyVal in HttpSignatureHeader) @@ -411,10 +411,10 @@ namespace Org.OpenAPITools.Client return derBytes.ToArray(); } - private RSACryptoServiceProvider GetRSAProviderFromPemFile(String pemfile, SecureString keyPassPharse = null) + private RSACryptoServiceProvider GetRSAProviderFromPemFile(string pemfile, SecureString keyPassPharse = null) { - const String pempubheader = "-----BEGIN PUBLIC KEY-----"; - const String pempubfooter = "-----END PUBLIC KEY-----"; + const string pempubheader = "-----BEGIN PUBLIC KEY-----"; + const string pempubfooter = "-----END PUBLIC KEY-----"; bool isPrivateKeyFile = true; byte[] pemkey = null; @@ -441,11 +441,11 @@ namespace Org.OpenAPITools.Client return null; } - private byte[] ConvertPrivateKeyToBytes(String instr, SecureString keyPassPharse = null) + private byte[] ConvertPrivateKeyToBytes(string instr, SecureString keyPassPharse = null) { - const String pemprivheader = "-----BEGIN RSA PRIVATE KEY-----"; - const String pemprivfooter = "-----END RSA PRIVATE KEY-----"; - String pemstr = instr.Trim(); + 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)) @@ -456,7 +456,7 @@ namespace Org.OpenAPITools.Client StringBuilder sb = new StringBuilder(pemstr); sb.Replace(pemprivheader, ""); sb.Replace(pemprivfooter, ""); - String pvkstr = sb.ToString().Trim(); + string pvkstr = sb.ToString().Trim(); try { // if there are no PEM encryption info lines, this is an UNencrypted PEM private key @@ -472,12 +472,12 @@ namespace Org.OpenAPITools.Client { return null; } - String saltline = str.ReadLine(); + string saltline = str.ReadLine(); if (!saltline.StartsWith("DEK-Info: DES-EDE3-CBC,")) { return null; } - String saltstr = saltline.Substring(saltline.IndexOf(",") + 1).Trim(); + 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); @@ -487,7 +487,7 @@ namespace Org.OpenAPITools.Client } //------ remaining b64 data is encrypted RSA key ---- - String encryptedstr = str.ReadToEnd(); + string encryptedstr = str.ReadToEnd(); try { //should have b64 encrypted RSA key now diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Client/IApiAccessor.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Client/IApiAccessor.cs index 59465ae8e90..2bd76416004 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Client/IApiAccessor.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Client/IApiAccessor.cs @@ -27,7 +27,7 @@ namespace Org.OpenAPITools.Client /// Gets the base path of the API client. /// /// The base path - String GetBasePath(); + string GetBasePath(); /// /// Provides a factory method hook for the creation of exceptions. diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Client/IAsynchronousClient.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Client/IAsynchronousClient.cs index 8a6f726678a..601e86d561c 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Client/IAsynchronousClient.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Client/IAsynchronousClient.cs @@ -29,7 +29,7 @@ namespace Org.OpenAPITools.Client /// 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)); + 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. @@ -40,7 +40,7 @@ namespace Org.OpenAPITools.Client /// 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)); + 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. @@ -51,7 +51,7 @@ namespace Org.OpenAPITools.Client /// 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)); + 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. @@ -62,7 +62,7 @@ namespace Org.OpenAPITools.Client /// 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)); + 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. @@ -73,7 +73,7 @@ namespace Org.OpenAPITools.Client /// 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)); + 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. @@ -84,7 +84,7 @@ namespace Org.OpenAPITools.Client /// 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)); + 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. @@ -95,6 +95,6 @@ namespace Org.OpenAPITools.Client /// 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)); + Task> PatchAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Client/ISynchronousClient.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Client/ISynchronousClient.cs index d27f01a588b..0e0a7fedacf 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Client/ISynchronousClient.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Client/ISynchronousClient.cs @@ -28,7 +28,7 @@ namespace Org.OpenAPITools.Client /// Per-request configurable settings. /// The return type. /// The response data, decorated with - ApiResponse Get(String path, RequestOptions options, IReadableConfiguration configuration = null); + ApiResponse Get(string path, RequestOptions options, IReadableConfiguration configuration = null); /// /// Executes a blocking call to some using the POST http verb. @@ -38,7 +38,7 @@ namespace Org.OpenAPITools.Client /// Per-request configurable settings. /// The return type. /// The response data, decorated with - ApiResponse Post(String path, RequestOptions options, IReadableConfiguration configuration = null); + ApiResponse Post(string path, RequestOptions options, IReadableConfiguration configuration = null); /// /// Executes a blocking call to some using the PUT http verb. @@ -48,7 +48,7 @@ namespace Org.OpenAPITools.Client /// Per-request configurable settings. /// The return type. /// The response data, decorated with - ApiResponse Put(String path, RequestOptions options, IReadableConfiguration configuration = null); + ApiResponse Put(string path, RequestOptions options, IReadableConfiguration configuration = null); /// /// Executes a blocking call to some using the DELETE http verb. @@ -58,7 +58,7 @@ namespace Org.OpenAPITools.Client /// Per-request configurable settings. /// The return type. /// The response data, decorated with - ApiResponse Delete(String path, RequestOptions options, IReadableConfiguration configuration = null); + ApiResponse Delete(string path, RequestOptions options, IReadableConfiguration configuration = null); /// /// Executes a blocking call to some using the HEAD http verb. @@ -68,7 +68,7 @@ namespace Org.OpenAPITools.Client /// Per-request configurable settings. /// The return type. /// The response data, decorated with - ApiResponse Head(String path, RequestOptions options, IReadableConfiguration configuration = null); + ApiResponse Head(string path, RequestOptions options, IReadableConfiguration configuration = null); /// /// Executes a blocking call to some using the OPTIONS http verb. @@ -78,7 +78,7 @@ namespace Org.OpenAPITools.Client /// Per-request configurable settings. /// The return type. /// The response data, decorated with - ApiResponse Options(String path, RequestOptions options, IReadableConfiguration configuration = null); + ApiResponse Options(string path, RequestOptions options, IReadableConfiguration configuration = null); /// /// Executes a blocking call to some using the PATCH http verb. @@ -88,6 +88,6 @@ namespace Org.OpenAPITools.Client /// Per-request configurable settings. /// The return type. /// The response data, decorated with - ApiResponse Patch(String path, RequestOptions options, IReadableConfiguration configuration = null); + ApiResponse Patch(string path, RequestOptions options, IReadableConfiguration configuration = null); } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Client/RequestOptions.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Client/RequestOptions.cs index d8da585db9c..7a1d5b97a88 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Client/RequestOptions.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Client/RequestOptions.cs @@ -24,29 +24,29 @@ namespace Org.OpenAPITools.Client /// /// Parameters to be bound to path parts of the Request's URL /// - public Dictionary PathParameters { get; set; } + 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; } + public Multimap QueryParameters { get; set; } /// /// Header parameters to be applied to to the request. /// Keys may have 1 or more values associated. /// - public Multimap HeaderParameters { get; set; } + public Multimap HeaderParameters { get; set; } /// /// Form parameters to be sent along with the request. /// - public Dictionary FormParameters { get; set; } + public Dictionary FormParameters { get; set; } /// /// File parameters to be sent along with the request. /// - public Dictionary FileParameters { get; set; } + public Dictionary FileParameters { get; set; } /// /// Cookies to be sent along with the request. @@ -67,8 +67,8 @@ namespace Org.OpenAPITools.Client QueryParameters = new Multimap(); HeaderParameters = new Multimap(); FormParameters = new Dictionary(); - FileParameters = new Dictionary(); + FileParameters = new Dictionary(); Cookies = new List(); } } -} \ No newline at end of file +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/Fruit.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/Fruit.cs index 132be5b4d3b..66de6a1c6f1 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/Fruit.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/Fruit.cs @@ -162,7 +162,7 @@ namespace Org.OpenAPITools.Model catch (Exception exception) { // deserialization failed, try the next one - System.Diagnostics.Debug.WriteLine(String.Format("Failed to deserialize `{0}` into Apple: {1}", jsonString, exception.ToString())); + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into Apple: {1}", jsonString, exception.ToString())); } try @@ -182,7 +182,7 @@ namespace Org.OpenAPITools.Model catch (Exception exception) { // deserialization failed, try the next one - System.Diagnostics.Debug.WriteLine(String.Format("Failed to deserialize `{0}` into Banana: {1}", jsonString, exception.ToString())); + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into Banana: {1}", jsonString, exception.ToString())); } if (match == 0) @@ -257,7 +257,7 @@ namespace Org.OpenAPITools.Model /// JSON Serializer public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { - writer.WriteRawValue((String)(typeof(Fruit).GetMethod("ToJson").Invoke(value, null))); + writer.WriteRawValue((string)(typeof(Fruit).GetMethod("ToJson").Invoke(value, null))); } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/FruitReq.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/FruitReq.cs index 380896933df..488c489d73a 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/FruitReq.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/FruitReq.cs @@ -171,7 +171,7 @@ namespace Org.OpenAPITools.Model catch (Exception exception) { // deserialization failed, try the next one - System.Diagnostics.Debug.WriteLine(String.Format("Failed to deserialize `{0}` into AppleReq: {1}", jsonString, exception.ToString())); + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into AppleReq: {1}", jsonString, exception.ToString())); } try @@ -191,7 +191,7 @@ namespace Org.OpenAPITools.Model catch (Exception exception) { // deserialization failed, try the next one - System.Diagnostics.Debug.WriteLine(String.Format("Failed to deserialize `{0}` into BananaReq: {1}", jsonString, exception.ToString())); + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into BananaReq: {1}", jsonString, exception.ToString())); } if (match == 0) @@ -266,7 +266,7 @@ namespace Org.OpenAPITools.Model /// JSON Serializer public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { - writer.WriteRawValue((String)(typeof(FruitReq).GetMethod("ToJson").Invoke(value, null))); + writer.WriteRawValue((string)(typeof(FruitReq).GetMethod("ToJson").Invoke(value, null))); } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/GmFruit.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/GmFruit.cs index c168aa41d4c..1aaa59d3f8b 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/GmFruit.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/GmFruit.cs @@ -151,7 +151,7 @@ namespace Org.OpenAPITools.Model catch (Exception exception) { // deserialization failed, try the next one - System.Diagnostics.Debug.WriteLine(String.Format("Failed to deserialize `{0}` into Apple: {1}", jsonString, exception.ToString())); + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into Apple: {1}", jsonString, exception.ToString())); } try @@ -163,7 +163,7 @@ namespace Org.OpenAPITools.Model catch (Exception exception) { // deserialization failed, try the next one - System.Diagnostics.Debug.WriteLine(String.Format("Failed to deserialize `{0}` into Banana: {1}", jsonString, exception.ToString())); + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into Banana: {1}", jsonString, exception.ToString())); } // no match found, throw an exception @@ -229,7 +229,7 @@ namespace Org.OpenAPITools.Model /// JSON Serializer public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { - writer.WriteRawValue((String)(typeof(GmFruit).GetMethod("ToJson").Invoke(value, null))); + writer.WriteRawValue((string)(typeof(GmFruit).GetMethod("ToJson").Invoke(value, null))); } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/HasOnlyReadOnly.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/HasOnlyReadOnly.cs index 3a2c3d26a92..fecd58bf6e8 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/HasOnlyReadOnly.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/HasOnlyReadOnly.cs @@ -55,7 +55,6 @@ namespace Org.OpenAPITools.Model { return false; } - /// /// Gets or Sets Foo /// @@ -70,7 +69,6 @@ namespace Org.OpenAPITools.Model { return false; } - /// /// Gets or Sets additional properties /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/Mammal.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/Mammal.cs index 2e847a10eb6..ed940d7ab6f 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/Mammal.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/Mammal.cs @@ -183,7 +183,7 @@ namespace Org.OpenAPITools.Model newMammal = new Mammal(JsonConvert.DeserializeObject(jsonString, Mammal.AdditionalPropertiesSerializerSettings)); return newMammal; default: - System.Diagnostics.Debug.WriteLine(String.Format("Failed to lookup discriminator value `{0}` for Mammal. Possible values: Pig whale zebra", discriminatorValue)); + System.Diagnostics.Debug.WriteLine(string.Format("Failed to lookup discriminator value `{0}` for Mammal. Possible values: Pig whale zebra", discriminatorValue)); break; } @@ -207,7 +207,7 @@ namespace Org.OpenAPITools.Model catch (Exception exception) { // deserialization failed, try the next one - System.Diagnostics.Debug.WriteLine(String.Format("Failed to deserialize `{0}` into Pig: {1}", jsonString, exception.ToString())); + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into Pig: {1}", jsonString, exception.ToString())); } try @@ -227,7 +227,7 @@ namespace Org.OpenAPITools.Model catch (Exception exception) { // deserialization failed, try the next one - System.Diagnostics.Debug.WriteLine(String.Format("Failed to deserialize `{0}` into Whale: {1}", jsonString, exception.ToString())); + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into Whale: {1}", jsonString, exception.ToString())); } try @@ -247,7 +247,7 @@ namespace Org.OpenAPITools.Model catch (Exception exception) { // deserialization failed, try the next one - System.Diagnostics.Debug.WriteLine(String.Format("Failed to deserialize `{0}` into Zebra: {1}", jsonString, exception.ToString())); + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into Zebra: {1}", jsonString, exception.ToString())); } if (match == 0) @@ -322,7 +322,7 @@ namespace Org.OpenAPITools.Model /// JSON Serializer public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { - writer.WriteRawValue((String)(typeof(Mammal).GetMethod("ToJson").Invoke(value, null))); + writer.WriteRawValue((string)(typeof(Mammal).GetMethod("ToJson").Invoke(value, null))); } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/Name.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/Name.cs index a6a01dd4ed3..0f5da18eafa 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/Name.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/Name.cs @@ -72,7 +72,6 @@ namespace Org.OpenAPITools.Model { return false; } - /// /// Gets or Sets Property /// @@ -93,7 +92,6 @@ namespace Org.OpenAPITools.Model { return false; } - /// /// Gets or Sets additional properties /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/NullableShape.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/NullableShape.cs index 80339ebf79b..20be30e5b89 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/NullableShape.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/NullableShape.cs @@ -163,7 +163,7 @@ namespace Org.OpenAPITools.Model newNullableShape = new NullableShape(JsonConvert.DeserializeObject(jsonString, NullableShape.AdditionalPropertiesSerializerSettings)); return newNullableShape; default: - System.Diagnostics.Debug.WriteLine(String.Format("Failed to lookup discriminator value `{0}` for NullableShape. Possible values: Quadrilateral Triangle", discriminatorValue)); + System.Diagnostics.Debug.WriteLine(string.Format("Failed to lookup discriminator value `{0}` for NullableShape. Possible values: Quadrilateral Triangle", discriminatorValue)); break; } @@ -187,7 +187,7 @@ namespace Org.OpenAPITools.Model catch (Exception exception) { // deserialization failed, try the next one - System.Diagnostics.Debug.WriteLine(String.Format("Failed to deserialize `{0}` into Quadrilateral: {1}", jsonString, exception.ToString())); + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into Quadrilateral: {1}", jsonString, exception.ToString())); } try @@ -207,7 +207,7 @@ namespace Org.OpenAPITools.Model catch (Exception exception) { // deserialization failed, try the next one - System.Diagnostics.Debug.WriteLine(String.Format("Failed to deserialize `{0}` into Triangle: {1}", jsonString, exception.ToString())); + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into Triangle: {1}", jsonString, exception.ToString())); } if (match == 0) @@ -282,7 +282,7 @@ namespace Org.OpenAPITools.Model /// JSON Serializer public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { - writer.WriteRawValue((String)(typeof(NullableShape).GetMethod("ToJson").Invoke(value, null))); + writer.WriteRawValue((string)(typeof(NullableShape).GetMethod("ToJson").Invoke(value, null))); } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/Pig.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/Pig.cs index d8605861e63..967d2139a0a 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/Pig.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/Pig.cs @@ -154,7 +154,7 @@ namespace Org.OpenAPITools.Model newPig = new Pig(JsonConvert.DeserializeObject(jsonString, Pig.AdditionalPropertiesSerializerSettings)); return newPig; default: - System.Diagnostics.Debug.WriteLine(String.Format("Failed to lookup discriminator value `{0}` for Pig. Possible values: BasquePig DanishPig", discriminatorValue)); + System.Diagnostics.Debug.WriteLine(string.Format("Failed to lookup discriminator value `{0}` for Pig. Possible values: BasquePig DanishPig", discriminatorValue)); break; } @@ -178,7 +178,7 @@ namespace Org.OpenAPITools.Model catch (Exception exception) { // deserialization failed, try the next one - System.Diagnostics.Debug.WriteLine(String.Format("Failed to deserialize `{0}` into BasquePig: {1}", jsonString, exception.ToString())); + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into BasquePig: {1}", jsonString, exception.ToString())); } try @@ -198,7 +198,7 @@ namespace Org.OpenAPITools.Model catch (Exception exception) { // deserialization failed, try the next one - System.Diagnostics.Debug.WriteLine(String.Format("Failed to deserialize `{0}` into DanishPig: {1}", jsonString, exception.ToString())); + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into DanishPig: {1}", jsonString, exception.ToString())); } if (match == 0) @@ -273,7 +273,7 @@ namespace Org.OpenAPITools.Model /// JSON Serializer public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { - writer.WriteRawValue((String)(typeof(Pig).GetMethod("ToJson").Invoke(value, null))); + writer.WriteRawValue((string)(typeof(Pig).GetMethod("ToJson").Invoke(value, null))); } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/Quadrilateral.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/Quadrilateral.cs index 17463ca09a4..19bc98ed2ec 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/Quadrilateral.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/Quadrilateral.cs @@ -154,7 +154,7 @@ namespace Org.OpenAPITools.Model newQuadrilateral = new Quadrilateral(JsonConvert.DeserializeObject(jsonString, Quadrilateral.AdditionalPropertiesSerializerSettings)); return newQuadrilateral; default: - System.Diagnostics.Debug.WriteLine(String.Format("Failed to lookup discriminator value `{0}` for Quadrilateral. Possible values: ComplexQuadrilateral SimpleQuadrilateral", discriminatorValue)); + System.Diagnostics.Debug.WriteLine(string.Format("Failed to lookup discriminator value `{0}` for Quadrilateral. Possible values: ComplexQuadrilateral SimpleQuadrilateral", discriminatorValue)); break; } @@ -178,7 +178,7 @@ namespace Org.OpenAPITools.Model catch (Exception exception) { // deserialization failed, try the next one - System.Diagnostics.Debug.WriteLine(String.Format("Failed to deserialize `{0}` into ComplexQuadrilateral: {1}", jsonString, exception.ToString())); + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into ComplexQuadrilateral: {1}", jsonString, exception.ToString())); } try @@ -198,7 +198,7 @@ namespace Org.OpenAPITools.Model catch (Exception exception) { // deserialization failed, try the next one - System.Diagnostics.Debug.WriteLine(String.Format("Failed to deserialize `{0}` into SimpleQuadrilateral: {1}", jsonString, exception.ToString())); + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into SimpleQuadrilateral: {1}", jsonString, exception.ToString())); } if (match == 0) @@ -273,7 +273,7 @@ namespace Org.OpenAPITools.Model /// JSON Serializer public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { - writer.WriteRawValue((String)(typeof(Quadrilateral).GetMethod("ToJson").Invoke(value, null))); + writer.WriteRawValue((string)(typeof(Quadrilateral).GetMethod("ToJson").Invoke(value, null))); } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/ReadOnlyFirst.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/ReadOnlyFirst.cs index 4ab8f7d5c6a..20483c31cdc 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/ReadOnlyFirst.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/ReadOnlyFirst.cs @@ -56,7 +56,6 @@ namespace Org.OpenAPITools.Model { return false; } - /// /// Gets or Sets Baz /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/Shape.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/Shape.cs index e75e0e8b167..f17c4d9a8f5 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/Shape.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/Shape.cs @@ -154,7 +154,7 @@ namespace Org.OpenAPITools.Model newShape = new Shape(JsonConvert.DeserializeObject(jsonString, Shape.AdditionalPropertiesSerializerSettings)); return newShape; default: - System.Diagnostics.Debug.WriteLine(String.Format("Failed to lookup discriminator value `{0}` for Shape. Possible values: Quadrilateral Triangle", discriminatorValue)); + System.Diagnostics.Debug.WriteLine(string.Format("Failed to lookup discriminator value `{0}` for Shape. Possible values: Quadrilateral Triangle", discriminatorValue)); break; } @@ -178,7 +178,7 @@ namespace Org.OpenAPITools.Model catch (Exception exception) { // deserialization failed, try the next one - System.Diagnostics.Debug.WriteLine(String.Format("Failed to deserialize `{0}` into Quadrilateral: {1}", jsonString, exception.ToString())); + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into Quadrilateral: {1}", jsonString, exception.ToString())); } try @@ -198,7 +198,7 @@ namespace Org.OpenAPITools.Model catch (Exception exception) { // deserialization failed, try the next one - System.Diagnostics.Debug.WriteLine(String.Format("Failed to deserialize `{0}` into Triangle: {1}", jsonString, exception.ToString())); + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into Triangle: {1}", jsonString, exception.ToString())); } if (match == 0) @@ -273,7 +273,7 @@ namespace Org.OpenAPITools.Model /// JSON Serializer public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { - writer.WriteRawValue((String)(typeof(Shape).GetMethod("ToJson").Invoke(value, null))); + writer.WriteRawValue((string)(typeof(Shape).GetMethod("ToJson").Invoke(value, null))); } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/ShapeOrNull.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/ShapeOrNull.cs index 7471bafb379..df321dc9e81 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/ShapeOrNull.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/ShapeOrNull.cs @@ -163,7 +163,7 @@ namespace Org.OpenAPITools.Model newShapeOrNull = new ShapeOrNull(JsonConvert.DeserializeObject(jsonString, ShapeOrNull.AdditionalPropertiesSerializerSettings)); return newShapeOrNull; default: - System.Diagnostics.Debug.WriteLine(String.Format("Failed to lookup discriminator value `{0}` for ShapeOrNull. Possible values: Quadrilateral Triangle", discriminatorValue)); + System.Diagnostics.Debug.WriteLine(string.Format("Failed to lookup discriminator value `{0}` for ShapeOrNull. Possible values: Quadrilateral Triangle", discriminatorValue)); break; } @@ -187,7 +187,7 @@ namespace Org.OpenAPITools.Model catch (Exception exception) { // deserialization failed, try the next one - System.Diagnostics.Debug.WriteLine(String.Format("Failed to deserialize `{0}` into Quadrilateral: {1}", jsonString, exception.ToString())); + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into Quadrilateral: {1}", jsonString, exception.ToString())); } try @@ -207,7 +207,7 @@ namespace Org.OpenAPITools.Model catch (Exception exception) { // deserialization failed, try the next one - System.Diagnostics.Debug.WriteLine(String.Format("Failed to deserialize `{0}` into Triangle: {1}", jsonString, exception.ToString())); + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into Triangle: {1}", jsonString, exception.ToString())); } if (match == 0) @@ -282,7 +282,7 @@ namespace Org.OpenAPITools.Model /// JSON Serializer public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { - writer.WriteRawValue((String)(typeof(ShapeOrNull).GetMethod("ToJson").Invoke(value, null))); + writer.WriteRawValue((string)(typeof(ShapeOrNull).GetMethod("ToJson").Invoke(value, null))); } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/Triangle.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/Triangle.cs index cccaa79a8ff..6f33859a898 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/Triangle.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/Triangle.cs @@ -183,7 +183,7 @@ namespace Org.OpenAPITools.Model newTriangle = new Triangle(JsonConvert.DeserializeObject(jsonString, Triangle.AdditionalPropertiesSerializerSettings)); return newTriangle; default: - System.Diagnostics.Debug.WriteLine(String.Format("Failed to lookup discriminator value `{0}` for Triangle. Possible values: EquilateralTriangle IsoscelesTriangle ScaleneTriangle", discriminatorValue)); + System.Diagnostics.Debug.WriteLine(string.Format("Failed to lookup discriminator value `{0}` for Triangle. Possible values: EquilateralTriangle IsoscelesTriangle ScaleneTriangle", discriminatorValue)); break; } @@ -207,7 +207,7 @@ namespace Org.OpenAPITools.Model catch (Exception exception) { // deserialization failed, try the next one - System.Diagnostics.Debug.WriteLine(String.Format("Failed to deserialize `{0}` into EquilateralTriangle: {1}", jsonString, exception.ToString())); + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into EquilateralTriangle: {1}", jsonString, exception.ToString())); } try @@ -227,7 +227,7 @@ namespace Org.OpenAPITools.Model catch (Exception exception) { // deserialization failed, try the next one - System.Diagnostics.Debug.WriteLine(String.Format("Failed to deserialize `{0}` into IsoscelesTriangle: {1}", jsonString, exception.ToString())); + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into IsoscelesTriangle: {1}", jsonString, exception.ToString())); } try @@ -247,7 +247,7 @@ namespace Org.OpenAPITools.Model catch (Exception exception) { // deserialization failed, try the next one - System.Diagnostics.Debug.WriteLine(String.Format("Failed to deserialize `{0}` into ScaleneTriangle: {1}", jsonString, exception.ToString())); + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into ScaleneTriangle: {1}", jsonString, exception.ToString())); } if (match == 0) @@ -322,7 +322,7 @@ namespace Org.OpenAPITools.Model /// JSON Serializer public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { - writer.WriteRawValue((String)(typeof(Triangle).GetMethod("ToJson").Invoke(value, null))); + writer.WriteRawValue((string)(typeof(Triangle).GetMethod("ToJson").Invoke(value, null))); } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/.openapi-generator/VERSION b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/.openapi-generator/VERSION +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Api/AnotherFakeApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Api/AnotherFakeApi.cs index 94d8b854b0d..ad48306e00c 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Api/AnotherFakeApi.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Api/AnotherFakeApi.cs @@ -109,7 +109,7 @@ namespace Org.OpenAPITools.Api /// Initializes a new instance of the class. /// /// - public AnotherFakeApi(String basePath) + public AnotherFakeApi(string basePath) { this.Configuration = Org.OpenAPITools.Client.Configuration.MergeConfigurations( Org.OpenAPITools.Client.GlobalConfiguration.Instance, @@ -172,7 +172,7 @@ namespace Org.OpenAPITools.Api /// Gets the base path of the API client. /// /// The base path - public String GetBasePath() + public string GetBasePath() { return this.Configuration.BasePath; } @@ -225,12 +225,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/json" }; @@ -284,12 +284,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/json" }; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Api/DefaultApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Api/DefaultApi.cs index 27789c4533a..8844aca4ab7 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Api/DefaultApi.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Api/DefaultApi.cs @@ -102,7 +102,7 @@ namespace Org.OpenAPITools.Api /// Initializes a new instance of the class. /// /// - public DefaultApi(String basePath) + public DefaultApi(string basePath) { this.Configuration = Org.OpenAPITools.Client.Configuration.MergeConfigurations( Org.OpenAPITools.Client.GlobalConfiguration.Instance, @@ -165,7 +165,7 @@ namespace Org.OpenAPITools.Api /// Gets the base path of the API client. /// /// The base path - public String GetBasePath() + public string GetBasePath() { return this.Configuration.BasePath; } @@ -212,11 +212,11 @@ namespace Org.OpenAPITools.Api { Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/json" }; @@ -263,11 +263,11 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/json" }; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Api/FakeApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Api/FakeApi.cs index d7749151314..fe862283f1e 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Api/FakeApi.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Api/FakeApi.cs @@ -826,7 +826,7 @@ namespace Org.OpenAPITools.Api /// Initializes a new instance of the class. /// /// - public FakeApi(String basePath) + public FakeApi(string basePath) { this.Configuration = Org.OpenAPITools.Client.Configuration.MergeConfigurations( Org.OpenAPITools.Client.GlobalConfiguration.Instance, @@ -889,7 +889,7 @@ namespace Org.OpenAPITools.Api /// Gets the base path of the API client. /// /// The base path - public String GetBasePath() + public string GetBasePath() { return this.Configuration.BasePath; } @@ -936,11 +936,11 @@ namespace Org.OpenAPITools.Api { Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/json" }; @@ -987,11 +987,11 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/json" }; @@ -1039,12 +1039,12 @@ namespace Org.OpenAPITools.Api { Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "*/*" }; @@ -1094,12 +1094,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "*/*" }; @@ -1148,12 +1148,12 @@ namespace Org.OpenAPITools.Api { Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "*/*" }; @@ -1203,12 +1203,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "*/*" }; @@ -1257,12 +1257,12 @@ namespace Org.OpenAPITools.Api { Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "*/*" }; @@ -1312,12 +1312,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "*/*" }; @@ -1366,12 +1366,12 @@ namespace Org.OpenAPITools.Api { Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "*/*" }; @@ -1421,12 +1421,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "*/*" }; @@ -1473,11 +1473,11 @@ namespace Org.OpenAPITools.Api { Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/json" }; @@ -1524,11 +1524,11 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/json" }; @@ -1579,12 +1579,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); @@ -1636,12 +1636,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; @@ -1698,12 +1698,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); @@ -1762,12 +1762,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; @@ -1820,12 +1820,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/json" }; @@ -1879,12 +1879,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/json" }; @@ -1966,12 +1966,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/x-www-form-urlencoded" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); @@ -2027,7 +2027,7 @@ namespace Org.OpenAPITools.Api // authentication (http_basic_test) required // http basic authentication required - if (!String.IsNullOrEmpty(this.Configuration.Username) || !String.IsNullOrEmpty(this.Configuration.Password)) + if (!string.IsNullOrEmpty(this.Configuration.Username) || !string.IsNullOrEmpty(this.Configuration.Password)) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Basic " + Org.OpenAPITools.Client.ClientUtils.Base64Encode(this.Configuration.Username + ":" + this.Configuration.Password)); } @@ -2102,12 +2102,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/x-www-form-urlencoded" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; @@ -2164,7 +2164,7 @@ namespace Org.OpenAPITools.Api // authentication (http_basic_test) required // http basic authentication required - if (!String.IsNullOrEmpty(this.Configuration.Username) || !String.IsNullOrEmpty(this.Configuration.Password)) + if (!string.IsNullOrEmpty(this.Configuration.Username) || !string.IsNullOrEmpty(this.Configuration.Password)) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Basic " + Org.OpenAPITools.Client.ClientUtils.Base64Encode(this.Configuration.Username + ":" + this.Configuration.Password)); } @@ -2217,12 +2217,12 @@ namespace Org.OpenAPITools.Api { Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/x-www-form-urlencoded" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); @@ -2315,12 +2315,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/x-www-form-urlencoded" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; @@ -2408,11 +2408,11 @@ namespace Org.OpenAPITools.Api { Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); @@ -2439,7 +2439,7 @@ namespace Org.OpenAPITools.Api // authentication (bearer_test) required // bearer authentication required - if (!String.IsNullOrEmpty(this.Configuration.AccessToken)) + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); } @@ -2490,11 +2490,11 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; @@ -2522,7 +2522,7 @@ namespace Org.OpenAPITools.Api // authentication (bearer_test) required // bearer authentication required - if (!String.IsNullOrEmpty(this.Configuration.AccessToken)) + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); } @@ -2565,12 +2565,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); @@ -2622,12 +2622,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; @@ -2684,12 +2684,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/x-www-form-urlencoded" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); @@ -2748,12 +2748,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/x-www-form-urlencoded" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; @@ -2829,11 +2829,11 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); @@ -2913,11 +2913,11 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Api/FakeClassnameTags123Api.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Api/FakeClassnameTags123Api.cs index 56ebdf5fd10..d4fbb5868ad 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Api/FakeClassnameTags123Api.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Api/FakeClassnameTags123Api.cs @@ -109,7 +109,7 @@ namespace Org.OpenAPITools.Api /// Initializes a new instance of the class. /// /// - public FakeClassnameTags123Api(String basePath) + public FakeClassnameTags123Api(string basePath) { this.Configuration = Org.OpenAPITools.Client.Configuration.MergeConfigurations( Org.OpenAPITools.Client.GlobalConfiguration.Instance, @@ -172,7 +172,7 @@ namespace Org.OpenAPITools.Api /// Gets the base path of the API client. /// /// The base path - public String GetBasePath() + public string GetBasePath() { return this.Configuration.BasePath; } @@ -225,12 +225,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/json" }; @@ -243,7 +243,7 @@ namespace Org.OpenAPITools.Api localVarRequestOptions.Data = modelClient; // authentication (api_key_query) required - if (!String.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("api_key_query"))) + 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"))); } @@ -289,12 +289,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/json" }; @@ -308,7 +308,7 @@ namespace Org.OpenAPITools.Api localVarRequestOptions.Data = modelClient; // authentication (api_key_query) required - if (!String.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("api_key_query"))) + 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"))); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Api/PetApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Api/PetApi.cs index 61759145f12..2bf19af1b1a 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Api/PetApi.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Api/PetApi.cs @@ -471,7 +471,7 @@ namespace Org.OpenAPITools.Api /// Initializes a new instance of the class. /// /// - public PetApi(String basePath) + public PetApi(string basePath) { this.Configuration = Org.OpenAPITools.Client.Configuration.MergeConfigurations( Org.OpenAPITools.Client.GlobalConfiguration.Instance, @@ -534,7 +534,7 @@ namespace Org.OpenAPITools.Api /// Gets the base path of the API client. /// /// The base path - public String GetBasePath() + public string GetBasePath() { return this.Configuration.BasePath; } @@ -586,13 +586,13 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json", "application/xml" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); @@ -621,7 +621,7 @@ namespace Org.OpenAPITools.Api } // authentication (petstore_auth) required // oauth required - if (!String.IsNullOrEmpty(this.Configuration.AccessToken)) + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); } @@ -666,13 +666,13 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json", "application/xml" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; @@ -702,7 +702,7 @@ namespace Org.OpenAPITools.Api } // authentication (petstore_auth) required // oauth required - if (!String.IsNullOrEmpty(this.Configuration.AccessToken)) + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); } @@ -743,11 +743,11 @@ namespace Org.OpenAPITools.Api { Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); @@ -764,7 +764,7 @@ namespace Org.OpenAPITools.Api // authentication (petstore_auth) required // oauth required - if (!String.IsNullOrEmpty(this.Configuration.AccessToken)) + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); } @@ -807,11 +807,11 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; @@ -829,7 +829,7 @@ namespace Org.OpenAPITools.Api // authentication (petstore_auth) required // oauth required - if (!String.IsNullOrEmpty(this.Configuration.AccessToken)) + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); } @@ -873,11 +873,11 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/xml", "application/json" }; @@ -908,7 +908,7 @@ namespace Org.OpenAPITools.Api } // authentication (petstore_auth) required // oauth required - if (!String.IsNullOrEmpty(this.Configuration.AccessToken)) + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); } @@ -954,11 +954,11 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/xml", "application/json" }; @@ -990,7 +990,7 @@ namespace Org.OpenAPITools.Api } // authentication (petstore_auth) required // oauth required - if (!String.IsNullOrEmpty(this.Configuration.AccessToken)) + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); } @@ -1034,11 +1034,11 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/xml", "application/json" }; @@ -1069,7 +1069,7 @@ namespace Org.OpenAPITools.Api } // authentication (petstore_auth) required // oauth required - if (!String.IsNullOrEmpty(this.Configuration.AccessToken)) + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); } @@ -1115,11 +1115,11 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/xml", "application/json" }; @@ -1151,7 +1151,7 @@ namespace Org.OpenAPITools.Api } // authentication (petstore_auth) required // oauth required - if (!String.IsNullOrEmpty(this.Configuration.AccessToken)) + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); } @@ -1191,11 +1191,11 @@ namespace Org.OpenAPITools.Api { Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/xml", "application/json" }; @@ -1209,7 +1209,7 @@ namespace Org.OpenAPITools.Api localVarRequestOptions.PathParameters.Add("petId", Org.OpenAPITools.Client.ClientUtils.ParameterToString(petId)); // path parameter // authentication (api_key) required - if (!String.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("api_key"))) + if (!string.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("api_key"))) { localVarRequestOptions.HeaderParameters.Add("api_key", this.Configuration.GetApiKeyWithPrefix("api_key")); } @@ -1251,11 +1251,11 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/xml", "application/json" }; @@ -1270,7 +1270,7 @@ namespace Org.OpenAPITools.Api localVarRequestOptions.PathParameters.Add("petId", Org.OpenAPITools.Client.ClientUtils.ParameterToString(petId)); // path parameter // authentication (api_key) required - if (!String.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("api_key"))) + if (!string.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("api_key"))) { localVarRequestOptions.HeaderParameters.Add("api_key", this.Configuration.GetApiKeyWithPrefix("api_key")); } @@ -1313,13 +1313,13 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json", "application/xml" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); @@ -1348,7 +1348,7 @@ namespace Org.OpenAPITools.Api } // authentication (petstore_auth) required // oauth required - if (!String.IsNullOrEmpty(this.Configuration.AccessToken)) + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); } @@ -1393,13 +1393,13 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json", "application/xml" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; @@ -1429,7 +1429,7 @@ namespace Org.OpenAPITools.Api } // authentication (petstore_auth) required // oauth required - if (!String.IsNullOrEmpty(this.Configuration.AccessToken)) + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); } @@ -1472,12 +1472,12 @@ namespace Org.OpenAPITools.Api { Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/x-www-form-urlencoded" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); @@ -1498,7 +1498,7 @@ namespace Org.OpenAPITools.Api // authentication (petstore_auth) required // oauth required - if (!String.IsNullOrEmpty(this.Configuration.AccessToken)) + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); } @@ -1543,12 +1543,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/x-www-form-urlencoded" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; @@ -1570,7 +1570,7 @@ namespace Org.OpenAPITools.Api // authentication (petstore_auth) required // oauth required - if (!String.IsNullOrEmpty(this.Configuration.AccessToken)) + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); } @@ -1614,12 +1614,12 @@ namespace Org.OpenAPITools.Api { Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "multipart/form-data" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/json" }; @@ -1641,7 +1641,7 @@ namespace Org.OpenAPITools.Api // authentication (petstore_auth) required // oauth required - if (!String.IsNullOrEmpty(this.Configuration.AccessToken)) + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); } @@ -1687,12 +1687,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "multipart/form-data" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/json" }; @@ -1715,7 +1715,7 @@ namespace Org.OpenAPITools.Api // authentication (petstore_auth) required // oauth required - if (!String.IsNullOrEmpty(this.Configuration.AccessToken)) + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); } @@ -1763,12 +1763,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "multipart/form-data" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/json" }; @@ -1787,7 +1787,7 @@ namespace Org.OpenAPITools.Api // authentication (petstore_auth) required // oauth required - if (!String.IsNullOrEmpty(this.Configuration.AccessToken)) + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); } @@ -1837,12 +1837,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "multipart/form-data" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/json" }; @@ -1862,7 +1862,7 @@ namespace Org.OpenAPITools.Api // authentication (petstore_auth) required // oauth required - if (!String.IsNullOrEmpty(this.Configuration.AccessToken)) + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Api/StoreApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Api/StoreApi.cs index 6ab56c9e9bf..ad7387db705 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Api/StoreApi.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Api/StoreApi.cs @@ -234,7 +234,7 @@ namespace Org.OpenAPITools.Api /// Initializes a new instance of the class. /// /// - public StoreApi(String basePath) + public StoreApi(string basePath) { this.Configuration = Org.OpenAPITools.Client.Configuration.MergeConfigurations( Org.OpenAPITools.Client.GlobalConfiguration.Instance, @@ -297,7 +297,7 @@ namespace Org.OpenAPITools.Api /// Gets the base path of the API client. /// /// The base path - public String GetBasePath() + public string GetBasePath() { return this.Configuration.BasePath; } @@ -349,11 +349,11 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); @@ -405,11 +405,11 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; @@ -455,11 +455,11 @@ namespace Org.OpenAPITools.Api { Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/json" }; @@ -471,7 +471,7 @@ namespace Org.OpenAPITools.Api // authentication (api_key) required - if (!String.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("api_key"))) + if (!string.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("api_key"))) { localVarRequestOptions.HeaderParameters.Add("api_key", this.Configuration.GetApiKeyWithPrefix("api_key")); } @@ -511,11 +511,11 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/json" }; @@ -528,7 +528,7 @@ namespace Org.OpenAPITools.Api // authentication (api_key) required - if (!String.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("api_key"))) + if (!string.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("api_key"))) { localVarRequestOptions.HeaderParameters.Add("api_key", this.Configuration.GetApiKeyWithPrefix("api_key")); } @@ -568,11 +568,11 @@ namespace Org.OpenAPITools.Api { Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/xml", "application/json" }; @@ -623,11 +623,11 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/xml", "application/json" }; @@ -681,12 +681,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/xml", "application/json" }; @@ -741,12 +741,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/xml", "application/json" }; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Api/UserApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Api/UserApi.cs index 80436c9b433..a2f2598c8ac 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Api/UserApi.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Api/UserApi.cs @@ -406,7 +406,7 @@ namespace Org.OpenAPITools.Api /// Initializes a new instance of the class. /// /// - public UserApi(String basePath) + public UserApi(string basePath) { this.Configuration = Org.OpenAPITools.Client.Configuration.MergeConfigurations( Org.OpenAPITools.Client.GlobalConfiguration.Instance, @@ -469,7 +469,7 @@ namespace Org.OpenAPITools.Api /// Gets the base path of the API client. /// /// The base path - public String GetBasePath() + public string GetBasePath() { return this.Configuration.BasePath; } @@ -521,12 +521,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); @@ -578,12 +578,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; @@ -634,12 +634,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); @@ -691,12 +691,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; @@ -747,12 +747,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); @@ -804,12 +804,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; @@ -860,11 +860,11 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); @@ -916,11 +916,11 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; @@ -972,11 +972,11 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/xml", "application/json" }; @@ -1031,11 +1031,11 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/xml", "application/json" }; @@ -1095,11 +1095,11 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/xml", "application/json" }; @@ -1161,11 +1161,11 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/xml", "application/json" }; @@ -1213,11 +1213,11 @@ namespace Org.OpenAPITools.Api { Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); @@ -1262,11 +1262,11 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; @@ -1322,12 +1322,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); @@ -1386,12 +1386,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Client/ApiClient.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Client/ApiClient.cs index db5a263b639..0a6db477bbc 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Client/ApiClient.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Client/ApiClient.cs @@ -107,7 +107,7 @@ namespace Org.OpenAPITools.Client var bytes = response.RawBytes; if (response.Headers != null) { - var filePath = String.IsNullOrEmpty(_configuration.TempFolderPath) + var filePath = string.IsNullOrEmpty(_configuration.TempFolderPath) ? Path.GetTempPath() : _configuration.TempFolderPath; var regex = new Regex(@"Content-Disposition=.*filename=['""]?([^'""\s]+)['""]?$"); @@ -131,7 +131,7 @@ namespace Org.OpenAPITools.Client return DateTime.Parse(response.Content, null, System.Globalization.DateTimeStyles.RoundtripKind); } - if (type == typeof(String) || type.Name.StartsWith("System.Nullable")) // return primitive type + if (type == typeof(string) || type.Name.StartsWith("System.Nullable")) // return primitive type { return Convert.ChangeType(response.Content, type); } @@ -163,7 +163,7 @@ namespace Org.OpenAPITools.Client /// public partial class ApiClient : ISynchronousClient, IAsynchronousClient { - private readonly String _baseUrl; + private readonly string _baseUrl; /// /// Specifies the settings on a object. @@ -208,7 +208,7 @@ namespace Org.OpenAPITools.Client /// /// The target service's base path in URL format. /// - public ApiClient(String basePath) + public ApiClient(string basePath) { if (string.IsNullOrEmpty(basePath)) throw new ArgumentException("basePath cannot be empty"); @@ -269,7 +269,7 @@ namespace Org.OpenAPITools.Client /// private RestRequest NewRequest( HttpMethod method, - String path, + string path, RequestOptions options, IReadableConfiguration configuration) { @@ -592,7 +592,7 @@ namespace Org.OpenAPITools.Client if (RetryConfiguration.AsyncRetryPolicy != null) { var policy = RetryConfiguration.AsyncRetryPolicy; - var policyResult = await policy.ExecuteAndCaptureAsync(() => client.ExecuteAsync(req, cancellationToken)).ConfigureAwait(false); + var policyResult = await policy.ExecuteAndCaptureAsync((ct) => client.ExecuteAsync(req, ct), cancellationToken).ConfigureAwait(false); response = (policyResult.Outcome == OutcomeType.Successful) ? client.Deserialize(policyResult.Result) : new RestResponse { Request = req, diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Client/ApiResponse.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Client/ApiResponse.cs index 1b7d787c84b..ca2de833a5a 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Client/ApiResponse.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Client/ApiResponse.cs @@ -44,7 +44,7 @@ namespace Org.OpenAPITools.Client /// /// Gets or sets any error text defined by the calling client. /// - String ErrorText { get; set; } + string ErrorText { get; set; } /// /// Gets or sets any cookies passed along on the response. @@ -85,7 +85,7 @@ namespace Org.OpenAPITools.Client /// /// Gets or sets any error text defined by the calling client. /// - public String ErrorText { get; set; } + public string ErrorText { get; set; } /// /// Gets or sets any cookies passed along on the response. diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Client/ClientUtils.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Client/ClientUtils.cs index 2b6e52d6065..3d038d5ce69 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Client/ClientUtils.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Client/ClientUtils.cs @@ -124,7 +124,7 @@ namespace Org.OpenAPITools.Client /// URL encode a string /// Credit/Ref: https://github.com/restsharp/RestSharp/blob/master/RestSharp/Extensions/StringExtensions.cs#L50 /// - /// String to be URL encoded + /// string to be URL encoded /// Byte array public static string UrlEncode(string input) { @@ -158,7 +158,7 @@ namespace Org.OpenAPITools.Client /// /// Encode string in base64 format. /// - /// String to be encoded. + /// string to be encoded. /// Encoded string. public static string Base64Encode(string text) { @@ -186,7 +186,7 @@ namespace Org.OpenAPITools.Client /// /// The Content-Type array to select from. /// The Content-Type header to use. - public static String SelectHeaderContentType(String[] contentTypes) + public static string SelectHeaderContentType(string[] contentTypes) { if (contentTypes.Length == 0) return null; @@ -207,7 +207,7 @@ namespace Org.OpenAPITools.Client /// /// The accepts array to select from. /// The Accept header to use. - public static String SelectHeaderAccept(String[] accepts) + public static string SelectHeaderAccept(string[] accepts) { if (accepts.Length == 0) return null; @@ -215,7 +215,7 @@ namespace Org.OpenAPITools.Client if (accepts.Contains("application/json", StringComparer.OrdinalIgnoreCase)) return "application/json"; - return String.Join(",", accepts); + return string.Join(",", accepts); } /// @@ -233,9 +233,9 @@ namespace Org.OpenAPITools.Client /// /// MIME /// Returns True if MIME type is json. - public static bool IsJsonMime(String mime) + public static bool IsJsonMime(string mime) { - if (String.IsNullOrWhiteSpace(mime)) return false; + if (string.IsNullOrWhiteSpace(mime)) return false; return JsonRegex.IsMatch(mime) || mime.Equals("application/json-patch+json"); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Client/Configuration.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Client/Configuration.cs index 154091fc731..1b80ca62fad 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Client/Configuration.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Client/Configuration.cs @@ -72,7 +72,7 @@ namespace Org.OpenAPITools.Client /// Defines the base path of the target API server. /// Example: http://localhost:3000/v1/ /// - private String _basePath; + private string _basePath; /// /// Gets or sets the API key based on the authentication name. @@ -516,9 +516,9 @@ namespace Org.OpenAPITools.Client /// /// Returns a string with essential information for debugging. /// - public static String ToDebugReport() + public static string ToDebugReport() { - String report = "C# SDK (Org.OpenAPITools) Debug Report:\n"; + 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"; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Client/HttpSigningConfiguration.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Client/HttpSigningConfiguration.cs index 1b9f9b7a99f..1d2d0019cae 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Client/HttpSigningConfiguration.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Client/HttpSigningConfiguration.cs @@ -120,7 +120,7 @@ namespace Org.OpenAPITools.Client } } - var httpValues = HttpUtility.ParseQueryString(String.Empty); + var httpValues = HttpUtility.ParseQueryString(string.Empty); foreach (var parameter in requestOptions.QueryParameters) { #if (NETCOREAPP) @@ -153,7 +153,7 @@ namespace Org.OpenAPITools.Client uriBuilder.Query = httpValues.ToString().Replace("+", "%20"); var dateTime = DateTime.Now; - String Digest = String.Empty; + string Digest = string.Empty; //get the body string requestBody = string.Empty; @@ -230,7 +230,7 @@ namespace Org.OpenAPITools.Client } } - var headersKeysString = String.Join(" ", HttpSignatureHeader.Keys); + var headersKeysString = string.Join(" ", HttpSignatureHeader.Keys); var headerValuesList = new List(); foreach (var keyVal in HttpSignatureHeader) @@ -411,10 +411,10 @@ namespace Org.OpenAPITools.Client return derBytes.ToArray(); } - private RSACryptoServiceProvider GetRSAProviderFromPemFile(String pemfile, SecureString keyPassPharse = null) + private RSACryptoServiceProvider GetRSAProviderFromPemFile(string pemfile, SecureString keyPassPharse = null) { - const String pempubheader = "-----BEGIN PUBLIC KEY-----"; - const String pempubfooter = "-----END PUBLIC KEY-----"; + const string pempubheader = "-----BEGIN PUBLIC KEY-----"; + const string pempubfooter = "-----END PUBLIC KEY-----"; bool isPrivateKeyFile = true; byte[] pemkey = null; @@ -441,11 +441,11 @@ namespace Org.OpenAPITools.Client return null; } - private byte[] ConvertPrivateKeyToBytes(String instr, SecureString keyPassPharse = null) + private byte[] ConvertPrivateKeyToBytes(string instr, SecureString keyPassPharse = null) { - const String pemprivheader = "-----BEGIN RSA PRIVATE KEY-----"; - const String pemprivfooter = "-----END RSA PRIVATE KEY-----"; - String pemstr = instr.Trim(); + 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)) @@ -456,7 +456,7 @@ namespace Org.OpenAPITools.Client StringBuilder sb = new StringBuilder(pemstr); sb.Replace(pemprivheader, ""); sb.Replace(pemprivfooter, ""); - String pvkstr = sb.ToString().Trim(); + string pvkstr = sb.ToString().Trim(); try { // if there are no PEM encryption info lines, this is an UNencrypted PEM private key @@ -472,12 +472,12 @@ namespace Org.OpenAPITools.Client { return null; } - String saltline = str.ReadLine(); + string saltline = str.ReadLine(); if (!saltline.StartsWith("DEK-Info: DES-EDE3-CBC,")) { return null; } - String saltstr = saltline.Substring(saltline.IndexOf(",") + 1).Trim(); + 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); @@ -487,7 +487,7 @@ namespace Org.OpenAPITools.Client } //------ remaining b64 data is encrypted RSA key ---- - String encryptedstr = str.ReadToEnd(); + string encryptedstr = str.ReadToEnd(); try { //should have b64 encrypted RSA key now diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Client/IApiAccessor.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Client/IApiAccessor.cs index 59465ae8e90..2bd76416004 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Client/IApiAccessor.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Client/IApiAccessor.cs @@ -27,7 +27,7 @@ namespace Org.OpenAPITools.Client /// Gets the base path of the API client. /// /// The base path - String GetBasePath(); + string GetBasePath(); /// /// Provides a factory method hook for the creation of exceptions. diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Client/IAsynchronousClient.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Client/IAsynchronousClient.cs index 8a6f726678a..601e86d561c 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Client/IAsynchronousClient.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Client/IAsynchronousClient.cs @@ -29,7 +29,7 @@ namespace Org.OpenAPITools.Client /// 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)); + 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. @@ -40,7 +40,7 @@ namespace Org.OpenAPITools.Client /// 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)); + 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. @@ -51,7 +51,7 @@ namespace Org.OpenAPITools.Client /// 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)); + 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. @@ -62,7 +62,7 @@ namespace Org.OpenAPITools.Client /// 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)); + 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. @@ -73,7 +73,7 @@ namespace Org.OpenAPITools.Client /// 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)); + 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. @@ -84,7 +84,7 @@ namespace Org.OpenAPITools.Client /// 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)); + 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. @@ -95,6 +95,6 @@ namespace Org.OpenAPITools.Client /// 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)); + Task> PatchAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Client/ISynchronousClient.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Client/ISynchronousClient.cs index d27f01a588b..0e0a7fedacf 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Client/ISynchronousClient.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Client/ISynchronousClient.cs @@ -28,7 +28,7 @@ namespace Org.OpenAPITools.Client /// Per-request configurable settings. /// The return type. /// The response data, decorated with - ApiResponse Get(String path, RequestOptions options, IReadableConfiguration configuration = null); + ApiResponse Get(string path, RequestOptions options, IReadableConfiguration configuration = null); /// /// Executes a blocking call to some using the POST http verb. @@ -38,7 +38,7 @@ namespace Org.OpenAPITools.Client /// Per-request configurable settings. /// The return type. /// The response data, decorated with - ApiResponse Post(String path, RequestOptions options, IReadableConfiguration configuration = null); + ApiResponse Post(string path, RequestOptions options, IReadableConfiguration configuration = null); /// /// Executes a blocking call to some using the PUT http verb. @@ -48,7 +48,7 @@ namespace Org.OpenAPITools.Client /// Per-request configurable settings. /// The return type. /// The response data, decorated with - ApiResponse Put(String path, RequestOptions options, IReadableConfiguration configuration = null); + ApiResponse Put(string path, RequestOptions options, IReadableConfiguration configuration = null); /// /// Executes a blocking call to some using the DELETE http verb. @@ -58,7 +58,7 @@ namespace Org.OpenAPITools.Client /// Per-request configurable settings. /// The return type. /// The response data, decorated with - ApiResponse Delete(String path, RequestOptions options, IReadableConfiguration configuration = null); + ApiResponse Delete(string path, RequestOptions options, IReadableConfiguration configuration = null); /// /// Executes a blocking call to some using the HEAD http verb. @@ -68,7 +68,7 @@ namespace Org.OpenAPITools.Client /// Per-request configurable settings. /// The return type. /// The response data, decorated with - ApiResponse Head(String path, RequestOptions options, IReadableConfiguration configuration = null); + ApiResponse Head(string path, RequestOptions options, IReadableConfiguration configuration = null); /// /// Executes a blocking call to some using the OPTIONS http verb. @@ -78,7 +78,7 @@ namespace Org.OpenAPITools.Client /// Per-request configurable settings. /// The return type. /// The response data, decorated with - ApiResponse Options(String path, RequestOptions options, IReadableConfiguration configuration = null); + ApiResponse Options(string path, RequestOptions options, IReadableConfiguration configuration = null); /// /// Executes a blocking call to some using the PATCH http verb. @@ -88,6 +88,6 @@ namespace Org.OpenAPITools.Client /// Per-request configurable settings. /// The return type. /// The response data, decorated with - ApiResponse Patch(String path, RequestOptions options, IReadableConfiguration configuration = null); + ApiResponse Patch(string path, RequestOptions options, IReadableConfiguration configuration = null); } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Client/RequestOptions.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Client/RequestOptions.cs index d8da585db9c..7a1d5b97a88 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Client/RequestOptions.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Client/RequestOptions.cs @@ -24,29 +24,29 @@ namespace Org.OpenAPITools.Client /// /// Parameters to be bound to path parts of the Request's URL /// - public Dictionary PathParameters { get; set; } + 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; } + public Multimap QueryParameters { get; set; } /// /// Header parameters to be applied to to the request. /// Keys may have 1 or more values associated. /// - public Multimap HeaderParameters { get; set; } + public Multimap HeaderParameters { get; set; } /// /// Form parameters to be sent along with the request. /// - public Dictionary FormParameters { get; set; } + public Dictionary FormParameters { get; set; } /// /// File parameters to be sent along with the request. /// - public Dictionary FileParameters { get; set; } + public Dictionary FileParameters { get; set; } /// /// Cookies to be sent along with the request. @@ -67,8 +67,8 @@ namespace Org.OpenAPITools.Client QueryParameters = new Multimap(); HeaderParameters = new Multimap(); FormParameters = new Dictionary(); - FileParameters = new Dictionary(); + FileParameters = new Dictionary(); Cookies = new List(); } } -} \ No newline at end of file +} diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/Fruit.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/Fruit.cs index 132be5b4d3b..66de6a1c6f1 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/Fruit.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/Fruit.cs @@ -162,7 +162,7 @@ namespace Org.OpenAPITools.Model catch (Exception exception) { // deserialization failed, try the next one - System.Diagnostics.Debug.WriteLine(String.Format("Failed to deserialize `{0}` into Apple: {1}", jsonString, exception.ToString())); + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into Apple: {1}", jsonString, exception.ToString())); } try @@ -182,7 +182,7 @@ namespace Org.OpenAPITools.Model catch (Exception exception) { // deserialization failed, try the next one - System.Diagnostics.Debug.WriteLine(String.Format("Failed to deserialize `{0}` into Banana: {1}", jsonString, exception.ToString())); + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into Banana: {1}", jsonString, exception.ToString())); } if (match == 0) @@ -257,7 +257,7 @@ namespace Org.OpenAPITools.Model /// JSON Serializer public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { - writer.WriteRawValue((String)(typeof(Fruit).GetMethod("ToJson").Invoke(value, null))); + writer.WriteRawValue((string)(typeof(Fruit).GetMethod("ToJson").Invoke(value, null))); } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/FruitReq.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/FruitReq.cs index 380896933df..488c489d73a 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/FruitReq.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/FruitReq.cs @@ -171,7 +171,7 @@ namespace Org.OpenAPITools.Model catch (Exception exception) { // deserialization failed, try the next one - System.Diagnostics.Debug.WriteLine(String.Format("Failed to deserialize `{0}` into AppleReq: {1}", jsonString, exception.ToString())); + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into AppleReq: {1}", jsonString, exception.ToString())); } try @@ -191,7 +191,7 @@ namespace Org.OpenAPITools.Model catch (Exception exception) { // deserialization failed, try the next one - System.Diagnostics.Debug.WriteLine(String.Format("Failed to deserialize `{0}` into BananaReq: {1}", jsonString, exception.ToString())); + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into BananaReq: {1}", jsonString, exception.ToString())); } if (match == 0) @@ -266,7 +266,7 @@ namespace Org.OpenAPITools.Model /// JSON Serializer public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { - writer.WriteRawValue((String)(typeof(FruitReq).GetMethod("ToJson").Invoke(value, null))); + writer.WriteRawValue((string)(typeof(FruitReq).GetMethod("ToJson").Invoke(value, null))); } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/GmFruit.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/GmFruit.cs index c168aa41d4c..1aaa59d3f8b 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/GmFruit.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/GmFruit.cs @@ -151,7 +151,7 @@ namespace Org.OpenAPITools.Model catch (Exception exception) { // deserialization failed, try the next one - System.Diagnostics.Debug.WriteLine(String.Format("Failed to deserialize `{0}` into Apple: {1}", jsonString, exception.ToString())); + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into Apple: {1}", jsonString, exception.ToString())); } try @@ -163,7 +163,7 @@ namespace Org.OpenAPITools.Model catch (Exception exception) { // deserialization failed, try the next one - System.Diagnostics.Debug.WriteLine(String.Format("Failed to deserialize `{0}` into Banana: {1}", jsonString, exception.ToString())); + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into Banana: {1}", jsonString, exception.ToString())); } // no match found, throw an exception @@ -229,7 +229,7 @@ namespace Org.OpenAPITools.Model /// JSON Serializer public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { - writer.WriteRawValue((String)(typeof(GmFruit).GetMethod("ToJson").Invoke(value, null))); + writer.WriteRawValue((string)(typeof(GmFruit).GetMethod("ToJson").Invoke(value, null))); } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/HasOnlyReadOnly.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/HasOnlyReadOnly.cs index dd453ef37f6..5558958ab6a 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/HasOnlyReadOnly.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/HasOnlyReadOnly.cs @@ -54,7 +54,6 @@ namespace Org.OpenAPITools.Model { return false; } - /// /// Gets or Sets Foo /// @@ -69,7 +68,6 @@ namespace Org.OpenAPITools.Model { return false; } - /// /// Returns the string presentation of the object /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/Mammal.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/Mammal.cs index 93652cebd2d..845bc54a3cb 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/Mammal.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/Mammal.cs @@ -189,7 +189,7 @@ namespace Org.OpenAPITools.Model catch (Exception exception) { // deserialization failed, try the next one - System.Diagnostics.Debug.WriteLine(String.Format("Failed to deserialize `{0}` into Pig: {1}", jsonString, exception.ToString())); + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into Pig: {1}", jsonString, exception.ToString())); } try @@ -209,7 +209,7 @@ namespace Org.OpenAPITools.Model catch (Exception exception) { // deserialization failed, try the next one - System.Diagnostics.Debug.WriteLine(String.Format("Failed to deserialize `{0}` into Whale: {1}", jsonString, exception.ToString())); + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into Whale: {1}", jsonString, exception.ToString())); } try @@ -229,7 +229,7 @@ namespace Org.OpenAPITools.Model catch (Exception exception) { // deserialization failed, try the next one - System.Diagnostics.Debug.WriteLine(String.Format("Failed to deserialize `{0}` into Zebra: {1}", jsonString, exception.ToString())); + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into Zebra: {1}", jsonString, exception.ToString())); } if (match == 0) @@ -304,7 +304,7 @@ namespace Org.OpenAPITools.Model /// JSON Serializer public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { - writer.WriteRawValue((String)(typeof(Mammal).GetMethod("ToJson").Invoke(value, null))); + writer.WriteRawValue((string)(typeof(Mammal).GetMethod("ToJson").Invoke(value, null))); } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/Name.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/Name.cs index a2000b1598b..58a46775ccf 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/Name.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/Name.cs @@ -68,7 +68,6 @@ namespace Org.OpenAPITools.Model { return false; } - /// /// Gets or Sets Property /// @@ -89,7 +88,6 @@ namespace Org.OpenAPITools.Model { return false; } - /// /// Returns the string presentation of the object /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/NullableShape.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/NullableShape.cs index e3b59f31af6..5f454dee6d3 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/NullableShape.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/NullableShape.cs @@ -172,7 +172,7 @@ namespace Org.OpenAPITools.Model catch (Exception exception) { // deserialization failed, try the next one - System.Diagnostics.Debug.WriteLine(String.Format("Failed to deserialize `{0}` into Quadrilateral: {1}", jsonString, exception.ToString())); + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into Quadrilateral: {1}", jsonString, exception.ToString())); } try @@ -192,7 +192,7 @@ namespace Org.OpenAPITools.Model catch (Exception exception) { // deserialization failed, try the next one - System.Diagnostics.Debug.WriteLine(String.Format("Failed to deserialize `{0}` into Triangle: {1}", jsonString, exception.ToString())); + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into Triangle: {1}", jsonString, exception.ToString())); } if (match == 0) @@ -267,7 +267,7 @@ namespace Org.OpenAPITools.Model /// JSON Serializer public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { - writer.WriteRawValue((String)(typeof(NullableShape).GetMethod("ToJson").Invoke(value, null))); + writer.WriteRawValue((string)(typeof(NullableShape).GetMethod("ToJson").Invoke(value, null))); } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/Pig.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/Pig.cs index 9ae61e76668..34e2e4de83c 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/Pig.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/Pig.cs @@ -163,7 +163,7 @@ namespace Org.OpenAPITools.Model catch (Exception exception) { // deserialization failed, try the next one - System.Diagnostics.Debug.WriteLine(String.Format("Failed to deserialize `{0}` into BasquePig: {1}", jsonString, exception.ToString())); + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into BasquePig: {1}", jsonString, exception.ToString())); } try @@ -183,7 +183,7 @@ namespace Org.OpenAPITools.Model catch (Exception exception) { // deserialization failed, try the next one - System.Diagnostics.Debug.WriteLine(String.Format("Failed to deserialize `{0}` into DanishPig: {1}", jsonString, exception.ToString())); + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into DanishPig: {1}", jsonString, exception.ToString())); } if (match == 0) @@ -258,7 +258,7 @@ namespace Org.OpenAPITools.Model /// JSON Serializer public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { - writer.WriteRawValue((String)(typeof(Pig).GetMethod("ToJson").Invoke(value, null))); + writer.WriteRawValue((string)(typeof(Pig).GetMethod("ToJson").Invoke(value, null))); } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/Quadrilateral.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/Quadrilateral.cs index f35df8fc7a1..1e00244d163 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/Quadrilateral.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/Quadrilateral.cs @@ -163,7 +163,7 @@ namespace Org.OpenAPITools.Model catch (Exception exception) { // deserialization failed, try the next one - System.Diagnostics.Debug.WriteLine(String.Format("Failed to deserialize `{0}` into ComplexQuadrilateral: {1}", jsonString, exception.ToString())); + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into ComplexQuadrilateral: {1}", jsonString, exception.ToString())); } try @@ -183,7 +183,7 @@ namespace Org.OpenAPITools.Model catch (Exception exception) { // deserialization failed, try the next one - System.Diagnostics.Debug.WriteLine(String.Format("Failed to deserialize `{0}` into SimpleQuadrilateral: {1}", jsonString, exception.ToString())); + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into SimpleQuadrilateral: {1}", jsonString, exception.ToString())); } if (match == 0) @@ -258,7 +258,7 @@ namespace Org.OpenAPITools.Model /// JSON Serializer public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { - writer.WriteRawValue((String)(typeof(Quadrilateral).GetMethod("ToJson").Invoke(value, null))); + writer.WriteRawValue((string)(typeof(Quadrilateral).GetMethod("ToJson").Invoke(value, null))); } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/ReadOnlyFirst.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/ReadOnlyFirst.cs index 17a7c072a84..5bff2796ed9 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/ReadOnlyFirst.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/ReadOnlyFirst.cs @@ -55,7 +55,6 @@ namespace Org.OpenAPITools.Model { return false; } - /// /// Gets or Sets Baz /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/Shape.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/Shape.cs index 6fd2c2fba81..a71a14456e6 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/Shape.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/Shape.cs @@ -163,7 +163,7 @@ namespace Org.OpenAPITools.Model catch (Exception exception) { // deserialization failed, try the next one - System.Diagnostics.Debug.WriteLine(String.Format("Failed to deserialize `{0}` into Quadrilateral: {1}", jsonString, exception.ToString())); + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into Quadrilateral: {1}", jsonString, exception.ToString())); } try @@ -183,7 +183,7 @@ namespace Org.OpenAPITools.Model catch (Exception exception) { // deserialization failed, try the next one - System.Diagnostics.Debug.WriteLine(String.Format("Failed to deserialize `{0}` into Triangle: {1}", jsonString, exception.ToString())); + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into Triangle: {1}", jsonString, exception.ToString())); } if (match == 0) @@ -258,7 +258,7 @@ namespace Org.OpenAPITools.Model /// JSON Serializer public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { - writer.WriteRawValue((String)(typeof(Shape).GetMethod("ToJson").Invoke(value, null))); + writer.WriteRawValue((string)(typeof(Shape).GetMethod("ToJson").Invoke(value, null))); } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/ShapeOrNull.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/ShapeOrNull.cs index 8adfde1b067..f7c4541f236 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/ShapeOrNull.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/ShapeOrNull.cs @@ -172,7 +172,7 @@ namespace Org.OpenAPITools.Model catch (Exception exception) { // deserialization failed, try the next one - System.Diagnostics.Debug.WriteLine(String.Format("Failed to deserialize `{0}` into Quadrilateral: {1}", jsonString, exception.ToString())); + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into Quadrilateral: {1}", jsonString, exception.ToString())); } try @@ -192,7 +192,7 @@ namespace Org.OpenAPITools.Model catch (Exception exception) { // deserialization failed, try the next one - System.Diagnostics.Debug.WriteLine(String.Format("Failed to deserialize `{0}` into Triangle: {1}", jsonString, exception.ToString())); + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into Triangle: {1}", jsonString, exception.ToString())); } if (match == 0) @@ -267,7 +267,7 @@ namespace Org.OpenAPITools.Model /// JSON Serializer public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { - writer.WriteRawValue((String)(typeof(ShapeOrNull).GetMethod("ToJson").Invoke(value, null))); + writer.WriteRawValue((string)(typeof(ShapeOrNull).GetMethod("ToJson").Invoke(value, null))); } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/Triangle.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/Triangle.cs index 5979a1ea74c..0b1b3902702 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/Triangle.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/Triangle.cs @@ -189,7 +189,7 @@ namespace Org.OpenAPITools.Model catch (Exception exception) { // deserialization failed, try the next one - System.Diagnostics.Debug.WriteLine(String.Format("Failed to deserialize `{0}` into EquilateralTriangle: {1}", jsonString, exception.ToString())); + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into EquilateralTriangle: {1}", jsonString, exception.ToString())); } try @@ -209,7 +209,7 @@ namespace Org.OpenAPITools.Model catch (Exception exception) { // deserialization failed, try the next one - System.Diagnostics.Debug.WriteLine(String.Format("Failed to deserialize `{0}` into IsoscelesTriangle: {1}", jsonString, exception.ToString())); + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into IsoscelesTriangle: {1}", jsonString, exception.ToString())); } try @@ -229,7 +229,7 @@ namespace Org.OpenAPITools.Model catch (Exception exception) { // deserialization failed, try the next one - System.Diagnostics.Debug.WriteLine(String.Format("Failed to deserialize `{0}` into ScaleneTriangle: {1}", jsonString, exception.ToString())); + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into ScaleneTriangle: {1}", jsonString, exception.ToString())); } if (match == 0) @@ -304,7 +304,7 @@ namespace Org.OpenAPITools.Model /// JSON Serializer public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { - writer.WriteRawValue((String)(typeof(Triangle).GetMethod("ToJson").Invoke(value, null))); + writer.WriteRawValue((string)(typeof(Triangle).GetMethod("ToJson").Invoke(value, null))); } /// diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/.openapi-generator/VERSION b/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/.openapi-generator/VERSION +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Api/PetApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Api/PetApi.cs index 34913501ea0..82f8266d4a1 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Api/PetApi.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Api/PetApi.cs @@ -422,7 +422,7 @@ namespace Org.OpenAPITools.Api /// Initializes a new instance of the class. /// /// - public PetApi(String basePath) + public PetApi(string basePath) { this.Configuration = Org.OpenAPITools.Client.Configuration.MergeConfigurations( Org.OpenAPITools.Client.GlobalConfiguration.Instance, @@ -485,7 +485,7 @@ namespace Org.OpenAPITools.Api /// Gets the base path of the API client. /// /// The base path - public String GetBasePath() + public string GetBasePath() { return this.Configuration.BasePath; } @@ -538,13 +538,13 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json", "application/xml" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/xml", "application/json" }; @@ -559,7 +559,7 @@ namespace Org.OpenAPITools.Api // authentication (petstore_auth) required // oauth required - if (!String.IsNullOrEmpty(this.Configuration.AccessToken)) + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); } @@ -605,13 +605,13 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json", "application/xml" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/xml", "application/json" }; @@ -627,7 +627,7 @@ namespace Org.OpenAPITools.Api // authentication (petstore_auth) required // oauth required - if (!String.IsNullOrEmpty(this.Configuration.AccessToken)) + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); } @@ -668,11 +668,11 @@ namespace Org.OpenAPITools.Api { Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); @@ -689,7 +689,7 @@ namespace Org.OpenAPITools.Api // authentication (petstore_auth) required // oauth required - if (!String.IsNullOrEmpty(this.Configuration.AccessToken)) + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); } @@ -732,11 +732,11 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; @@ -754,7 +754,7 @@ namespace Org.OpenAPITools.Api // authentication (petstore_auth) required // oauth required - if (!String.IsNullOrEmpty(this.Configuration.AccessToken)) + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); } @@ -798,11 +798,11 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/xml", "application/json" }; @@ -817,7 +817,7 @@ namespace Org.OpenAPITools.Api // authentication (petstore_auth) required // oauth required - if (!String.IsNullOrEmpty(this.Configuration.AccessToken)) + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); } @@ -863,11 +863,11 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/xml", "application/json" }; @@ -883,7 +883,7 @@ namespace Org.OpenAPITools.Api // authentication (petstore_auth) required // oauth required - if (!String.IsNullOrEmpty(this.Configuration.AccessToken)) + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); } @@ -927,11 +927,11 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/xml", "application/json" }; @@ -946,7 +946,7 @@ namespace Org.OpenAPITools.Api // authentication (petstore_auth) required // oauth required - if (!String.IsNullOrEmpty(this.Configuration.AccessToken)) + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); } @@ -992,11 +992,11 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/xml", "application/json" }; @@ -1012,7 +1012,7 @@ namespace Org.OpenAPITools.Api // authentication (petstore_auth) required // oauth required - if (!String.IsNullOrEmpty(this.Configuration.AccessToken)) + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); } @@ -1052,11 +1052,11 @@ namespace Org.OpenAPITools.Api { Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/xml", "application/json" }; @@ -1070,7 +1070,7 @@ namespace Org.OpenAPITools.Api localVarRequestOptions.PathParameters.Add("petId", Org.OpenAPITools.Client.ClientUtils.ParameterToString(petId)); // path parameter // authentication (api_key) required - if (!String.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("api_key"))) + if (!string.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("api_key"))) { localVarRequestOptions.HeaderParameters.Add("api_key", this.Configuration.GetApiKeyWithPrefix("api_key")); } @@ -1112,11 +1112,11 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/xml", "application/json" }; @@ -1131,7 +1131,7 @@ namespace Org.OpenAPITools.Api localVarRequestOptions.PathParameters.Add("petId", Org.OpenAPITools.Client.ClientUtils.ParameterToString(petId)); // path parameter // authentication (api_key) required - if (!String.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("api_key"))) + if (!string.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("api_key"))) { localVarRequestOptions.HeaderParameters.Add("api_key", this.Configuration.GetApiKeyWithPrefix("api_key")); } @@ -1175,13 +1175,13 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json", "application/xml" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/xml", "application/json" }; @@ -1196,7 +1196,7 @@ namespace Org.OpenAPITools.Api // authentication (petstore_auth) required // oauth required - if (!String.IsNullOrEmpty(this.Configuration.AccessToken)) + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); } @@ -1242,13 +1242,13 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json", "application/xml" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/xml", "application/json" }; @@ -1264,7 +1264,7 @@ namespace Org.OpenAPITools.Api // authentication (petstore_auth) required // oauth required - if (!String.IsNullOrEmpty(this.Configuration.AccessToken)) + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); } @@ -1307,12 +1307,12 @@ namespace Org.OpenAPITools.Api { Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/x-www-form-urlencoded" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); @@ -1333,7 +1333,7 @@ namespace Org.OpenAPITools.Api // authentication (petstore_auth) required // oauth required - if (!String.IsNullOrEmpty(this.Configuration.AccessToken)) + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); } @@ -1378,12 +1378,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/x-www-form-urlencoded" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; @@ -1405,7 +1405,7 @@ namespace Org.OpenAPITools.Api // authentication (petstore_auth) required // oauth required - if (!String.IsNullOrEmpty(this.Configuration.AccessToken)) + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); } @@ -1449,12 +1449,12 @@ namespace Org.OpenAPITools.Api { Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "multipart/form-data" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/json" }; @@ -1476,7 +1476,7 @@ namespace Org.OpenAPITools.Api // authentication (petstore_auth) required // oauth required - if (!String.IsNullOrEmpty(this.Configuration.AccessToken)) + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); } @@ -1522,12 +1522,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "multipart/form-data" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/json" }; @@ -1550,7 +1550,7 @@ namespace Org.OpenAPITools.Api // authentication (petstore_auth) required // oauth required - if (!String.IsNullOrEmpty(this.Configuration.AccessToken)) + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Api/StoreApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Api/StoreApi.cs index d4d37dc9d4d..67f8c23d6ca 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Api/StoreApi.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Api/StoreApi.cs @@ -234,7 +234,7 @@ namespace Org.OpenAPITools.Api /// Initializes a new instance of the class. /// /// - public StoreApi(String basePath) + public StoreApi(string basePath) { this.Configuration = Org.OpenAPITools.Client.Configuration.MergeConfigurations( Org.OpenAPITools.Client.GlobalConfiguration.Instance, @@ -297,7 +297,7 @@ namespace Org.OpenAPITools.Api /// Gets the base path of the API client. /// /// The base path - public String GetBasePath() + public string GetBasePath() { return this.Configuration.BasePath; } @@ -349,11 +349,11 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); @@ -405,11 +405,11 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; @@ -455,11 +455,11 @@ namespace Org.OpenAPITools.Api { Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/json" }; @@ -471,7 +471,7 @@ namespace Org.OpenAPITools.Api // authentication (api_key) required - if (!String.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("api_key"))) + if (!string.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("api_key"))) { localVarRequestOptions.HeaderParameters.Add("api_key", this.Configuration.GetApiKeyWithPrefix("api_key")); } @@ -511,11 +511,11 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/json" }; @@ -528,7 +528,7 @@ namespace Org.OpenAPITools.Api // authentication (api_key) required - if (!String.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("api_key"))) + if (!string.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("api_key"))) { localVarRequestOptions.HeaderParameters.Add("api_key", this.Configuration.GetApiKeyWithPrefix("api_key")); } @@ -568,11 +568,11 @@ namespace Org.OpenAPITools.Api { Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/xml", "application/json" }; @@ -623,11 +623,11 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/xml", "application/json" }; @@ -681,12 +681,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/xml", "application/json" }; @@ -741,12 +741,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/xml", "application/json" }; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Api/UserApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Api/UserApi.cs index 8e6455d1b99..ac62b62f067 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Api/UserApi.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Api/UserApi.cs @@ -406,7 +406,7 @@ namespace Org.OpenAPITools.Api /// Initializes a new instance of the class. /// /// - public UserApi(String basePath) + public UserApi(string basePath) { this.Configuration = Org.OpenAPITools.Client.Configuration.MergeConfigurations( Org.OpenAPITools.Client.GlobalConfiguration.Instance, @@ -469,7 +469,7 @@ namespace Org.OpenAPITools.Api /// Gets the base path of the API client. /// /// The base path - public String GetBasePath() + public string GetBasePath() { return this.Configuration.BasePath; } @@ -521,12 +521,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); @@ -538,7 +538,7 @@ namespace Org.OpenAPITools.Api localVarRequestOptions.Data = user; // authentication (api_key) required - if (!String.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("api_key"))) + if (!string.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("api_key"))) { localVarRequestOptions.HeaderParameters.Add("api_key", this.Configuration.GetApiKeyWithPrefix("api_key")); } @@ -583,12 +583,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; @@ -601,7 +601,7 @@ namespace Org.OpenAPITools.Api localVarRequestOptions.Data = user; // authentication (api_key) required - if (!String.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("api_key"))) + if (!string.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("api_key"))) { localVarRequestOptions.HeaderParameters.Add("api_key", this.Configuration.GetApiKeyWithPrefix("api_key")); } @@ -644,12 +644,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); @@ -661,7 +661,7 @@ namespace Org.OpenAPITools.Api localVarRequestOptions.Data = user; // authentication (api_key) required - if (!String.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("api_key"))) + if (!string.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("api_key"))) { localVarRequestOptions.HeaderParameters.Add("api_key", this.Configuration.GetApiKeyWithPrefix("api_key")); } @@ -706,12 +706,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; @@ -724,7 +724,7 @@ namespace Org.OpenAPITools.Api localVarRequestOptions.Data = user; // authentication (api_key) required - if (!String.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("api_key"))) + if (!string.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("api_key"))) { localVarRequestOptions.HeaderParameters.Add("api_key", this.Configuration.GetApiKeyWithPrefix("api_key")); } @@ -767,12 +767,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); @@ -784,7 +784,7 @@ namespace Org.OpenAPITools.Api localVarRequestOptions.Data = user; // authentication (api_key) required - if (!String.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("api_key"))) + if (!string.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("api_key"))) { localVarRequestOptions.HeaderParameters.Add("api_key", this.Configuration.GetApiKeyWithPrefix("api_key")); } @@ -829,12 +829,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; @@ -847,7 +847,7 @@ namespace Org.OpenAPITools.Api localVarRequestOptions.Data = user; // authentication (api_key) required - if (!String.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("api_key"))) + if (!string.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("api_key"))) { localVarRequestOptions.HeaderParameters.Add("api_key", this.Configuration.GetApiKeyWithPrefix("api_key")); } @@ -890,11 +890,11 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); @@ -906,7 +906,7 @@ namespace Org.OpenAPITools.Api localVarRequestOptions.PathParameters.Add("username", Org.OpenAPITools.Client.ClientUtils.ParameterToString(username)); // path parameter // authentication (api_key) required - if (!String.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("api_key"))) + if (!string.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("api_key"))) { localVarRequestOptions.HeaderParameters.Add("api_key", this.Configuration.GetApiKeyWithPrefix("api_key")); } @@ -951,11 +951,11 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; @@ -968,7 +968,7 @@ namespace Org.OpenAPITools.Api localVarRequestOptions.PathParameters.Add("username", Org.OpenAPITools.Client.ClientUtils.ParameterToString(username)); // path parameter // authentication (api_key) required - if (!String.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("api_key"))) + if (!string.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("api_key"))) { localVarRequestOptions.HeaderParameters.Add("api_key", this.Configuration.GetApiKeyWithPrefix("api_key")); } @@ -1012,11 +1012,11 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/xml", "application/json" }; @@ -1071,11 +1071,11 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/xml", "application/json" }; @@ -1135,11 +1135,11 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/xml", "application/json" }; @@ -1201,11 +1201,11 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { "application/xml", "application/json" }; @@ -1253,11 +1253,11 @@ namespace Org.OpenAPITools.Api { Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); @@ -1268,7 +1268,7 @@ namespace Org.OpenAPITools.Api // authentication (api_key) required - if (!String.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("api_key"))) + if (!string.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("api_key"))) { localVarRequestOptions.HeaderParameters.Add("api_key", this.Configuration.GetApiKeyWithPrefix("api_key")); } @@ -1307,11 +1307,11 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; @@ -1323,7 +1323,7 @@ namespace Org.OpenAPITools.Api // authentication (api_key) required - if (!String.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("api_key"))) + if (!string.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("api_key"))) { localVarRequestOptions.HeaderParameters.Add("api_key", this.Configuration.GetApiKeyWithPrefix("api_key")); } @@ -1372,12 +1372,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); @@ -1390,7 +1390,7 @@ namespace Org.OpenAPITools.Api localVarRequestOptions.Data = user; // authentication (api_key) required - if (!String.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("api_key"))) + if (!string.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("api_key"))) { localVarRequestOptions.HeaderParameters.Add("api_key", this.Configuration.GetApiKeyWithPrefix("api_key")); } @@ -1441,12 +1441,12 @@ namespace Org.OpenAPITools.Api Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); - String[] _contentTypes = new String[] { + string[] _contentTypes = new string[] { "application/json" }; // to determine the Accept header - String[] _accepts = new String[] { + string[] _accepts = new string[] { }; @@ -1460,7 +1460,7 @@ namespace Org.OpenAPITools.Api localVarRequestOptions.Data = user; // authentication (api_key) required - if (!String.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("api_key"))) + if (!string.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("api_key"))) { localVarRequestOptions.HeaderParameters.Add("api_key", this.Configuration.GetApiKeyWithPrefix("api_key")); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Client/ApiClient.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Client/ApiClient.cs index 2626b1c2f6f..9d4a14d562e 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Client/ApiClient.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Client/ApiClient.cs @@ -106,7 +106,7 @@ namespace Org.OpenAPITools.Client var bytes = response.RawBytes; if (response.Headers != null) { - var filePath = String.IsNullOrEmpty(_configuration.TempFolderPath) + var filePath = string.IsNullOrEmpty(_configuration.TempFolderPath) ? Path.GetTempPath() : _configuration.TempFolderPath; var regex = new Regex(@"Content-Disposition=.*filename=['""]?([^'""\s]+)['""]?$"); @@ -130,7 +130,7 @@ namespace Org.OpenAPITools.Client return DateTime.Parse(response.Content, null, System.Globalization.DateTimeStyles.RoundtripKind); } - if (type == typeof(String) || type.Name.StartsWith("System.Nullable")) // return primitive type + if (type == typeof(string) || type.Name.StartsWith("System.Nullable")) // return primitive type { return Convert.ChangeType(response.Content, type); } @@ -162,7 +162,7 @@ namespace Org.OpenAPITools.Client /// public partial class ApiClient : ISynchronousClient, IAsynchronousClient { - private readonly String _baseUrl; + private readonly string _baseUrl; /// /// Specifies the settings on a object. @@ -207,7 +207,7 @@ namespace Org.OpenAPITools.Client /// /// The target service's base path in URL format. /// - public ApiClient(String basePath) + public ApiClient(string basePath) { if (string.IsNullOrEmpty(basePath)) throw new ArgumentException("basePath cannot be empty"); @@ -268,7 +268,7 @@ namespace Org.OpenAPITools.Client /// private RestRequest NewRequest( HttpMethod method, - String path, + string path, RequestOptions options, IReadableConfiguration configuration) { @@ -591,7 +591,7 @@ namespace Org.OpenAPITools.Client if (RetryConfiguration.AsyncRetryPolicy != null) { var policy = RetryConfiguration.AsyncRetryPolicy; - var policyResult = await policy.ExecuteAndCaptureAsync(() => client.ExecuteAsync(req, cancellationToken)).ConfigureAwait(false); + var policyResult = await policy.ExecuteAndCaptureAsync((ct) => client.ExecuteAsync(req, ct), cancellationToken).ConfigureAwait(false); response = (policyResult.Outcome == OutcomeType.Successful) ? client.Deserialize(policyResult.Result) : new RestResponse { Request = req, diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Client/ApiResponse.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Client/ApiResponse.cs index 57a13978ecb..6d91a6f7a47 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Client/ApiResponse.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Client/ApiResponse.cs @@ -44,7 +44,7 @@ namespace Org.OpenAPITools.Client /// /// Gets or sets any error text defined by the calling client. /// - String ErrorText { get; set; } + string ErrorText { get; set; } /// /// Gets or sets any cookies passed along on the response. @@ -85,7 +85,7 @@ namespace Org.OpenAPITools.Client /// /// Gets or sets any error text defined by the calling client. /// - public String ErrorText { get; set; } + public string ErrorText { get; set; } /// /// Gets or sets any cookies passed along on the response. diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Client/ClientUtils.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Client/ClientUtils.cs index e1d9a6e0abc..3676a500c04 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Client/ClientUtils.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Client/ClientUtils.cs @@ -124,7 +124,7 @@ namespace Org.OpenAPITools.Client /// URL encode a string /// Credit/Ref: https://github.com/restsharp/RestSharp/blob/master/RestSharp/Extensions/StringExtensions.cs#L50 /// - /// String to be URL encoded + /// string to be URL encoded /// Byte array public static string UrlEncode(string input) { @@ -158,7 +158,7 @@ namespace Org.OpenAPITools.Client /// /// Encode string in base64 format. /// - /// String to be encoded. + /// string to be encoded. /// Encoded string. public static string Base64Encode(string text) { @@ -186,7 +186,7 @@ namespace Org.OpenAPITools.Client /// /// The Content-Type array to select from. /// The Content-Type header to use. - public static String SelectHeaderContentType(String[] contentTypes) + public static string SelectHeaderContentType(string[] contentTypes) { if (contentTypes.Length == 0) return null; @@ -207,7 +207,7 @@ namespace Org.OpenAPITools.Client /// /// The accepts array to select from. /// The Accept header to use. - public static String SelectHeaderAccept(String[] accepts) + public static string SelectHeaderAccept(string[] accepts) { if (accepts.Length == 0) return null; @@ -215,7 +215,7 @@ namespace Org.OpenAPITools.Client if (accepts.Contains("application/json", StringComparer.OrdinalIgnoreCase)) return "application/json"; - return String.Join(",", accepts); + return string.Join(",", accepts); } /// @@ -233,9 +233,9 @@ namespace Org.OpenAPITools.Client /// /// MIME /// Returns True if MIME type is json. - public static bool IsJsonMime(String mime) + public static bool IsJsonMime(string mime) { - if (String.IsNullOrWhiteSpace(mime)) return false; + if (string.IsNullOrWhiteSpace(mime)) return false; return JsonRegex.IsMatch(mime) || mime.Equals("application/json-patch+json"); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Client/Configuration.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Client/Configuration.cs index 92fbefd0e34..896bd754ea5 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Client/Configuration.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Client/Configuration.cs @@ -67,7 +67,7 @@ namespace Org.OpenAPITools.Client /// Defines the base path of the target API server. /// Example: http://localhost:3000/v1/ /// - private String _basePath; + private string _basePath; /// /// Gets or sets the API key based on the authentication name. @@ -440,9 +440,9 @@ namespace Org.OpenAPITools.Client /// /// Returns a string with essential information for debugging. /// - public static String ToDebugReport() + public static string ToDebugReport() { - String report = "C# SDK (Org.OpenAPITools) Debug Report:\n"; + 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"; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Client/IApiAccessor.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Client/IApiAccessor.cs index edcf9827ebb..c8a78e995ce 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Client/IApiAccessor.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Client/IApiAccessor.cs @@ -27,7 +27,7 @@ namespace Org.OpenAPITools.Client /// Gets the base path of the API client. /// /// The base path - String GetBasePath(); + string GetBasePath(); /// /// Provides a factory method hook for the creation of exceptions. diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Client/IAsynchronousClient.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Client/IAsynchronousClient.cs index 6b62316325d..066d9b39482 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Client/IAsynchronousClient.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Client/IAsynchronousClient.cs @@ -29,7 +29,7 @@ namespace Org.OpenAPITools.Client /// 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)); + 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. @@ -40,7 +40,7 @@ namespace Org.OpenAPITools.Client /// 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)); + 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. @@ -51,7 +51,7 @@ namespace Org.OpenAPITools.Client /// 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)); + 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. @@ -62,7 +62,7 @@ namespace Org.OpenAPITools.Client /// 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)); + 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. @@ -73,7 +73,7 @@ namespace Org.OpenAPITools.Client /// 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)); + 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. @@ -84,7 +84,7 @@ namespace Org.OpenAPITools.Client /// 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)); + 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. @@ -95,6 +95,6 @@ namespace Org.OpenAPITools.Client /// 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)); + Task> PatchAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Client/ISynchronousClient.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Client/ISynchronousClient.cs index 22bb7a560f7..3910f6d68ce 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Client/ISynchronousClient.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Client/ISynchronousClient.cs @@ -28,7 +28,7 @@ namespace Org.OpenAPITools.Client /// Per-request configurable settings. /// The return type. /// The response data, decorated with - ApiResponse Get(String path, RequestOptions options, IReadableConfiguration configuration = null); + ApiResponse Get(string path, RequestOptions options, IReadableConfiguration configuration = null); /// /// Executes a blocking call to some using the POST http verb. @@ -38,7 +38,7 @@ namespace Org.OpenAPITools.Client /// Per-request configurable settings. /// The return type. /// The response data, decorated with - ApiResponse Post(String path, RequestOptions options, IReadableConfiguration configuration = null); + ApiResponse Post(string path, RequestOptions options, IReadableConfiguration configuration = null); /// /// Executes a blocking call to some using the PUT http verb. @@ -48,7 +48,7 @@ namespace Org.OpenAPITools.Client /// Per-request configurable settings. /// The return type. /// The response data, decorated with - ApiResponse Put(String path, RequestOptions options, IReadableConfiguration configuration = null); + ApiResponse Put(string path, RequestOptions options, IReadableConfiguration configuration = null); /// /// Executes a blocking call to some using the DELETE http verb. @@ -58,7 +58,7 @@ namespace Org.OpenAPITools.Client /// Per-request configurable settings. /// The return type. /// The response data, decorated with - ApiResponse Delete(String path, RequestOptions options, IReadableConfiguration configuration = null); + ApiResponse Delete(string path, RequestOptions options, IReadableConfiguration configuration = null); /// /// Executes a blocking call to some using the HEAD http verb. @@ -68,7 +68,7 @@ namespace Org.OpenAPITools.Client /// Per-request configurable settings. /// The return type. /// The response data, decorated with - ApiResponse Head(String path, RequestOptions options, IReadableConfiguration configuration = null); + ApiResponse Head(string path, RequestOptions options, IReadableConfiguration configuration = null); /// /// Executes a blocking call to some using the OPTIONS http verb. @@ -78,7 +78,7 @@ namespace Org.OpenAPITools.Client /// Per-request configurable settings. /// The return type. /// The response data, decorated with - ApiResponse Options(String path, RequestOptions options, IReadableConfiguration configuration = null); + ApiResponse Options(string path, RequestOptions options, IReadableConfiguration configuration = null); /// /// Executes a blocking call to some using the PATCH http verb. @@ -88,6 +88,6 @@ namespace Org.OpenAPITools.Client /// Per-request configurable settings. /// The return type. /// The response data, decorated with - ApiResponse Patch(String path, RequestOptions options, IReadableConfiguration configuration = null); + ApiResponse Patch(string path, RequestOptions options, IReadableConfiguration configuration = null); } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Client/RequestOptions.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Client/RequestOptions.cs index e5facdfdaf8..c6b3ccc38f2 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Client/RequestOptions.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Client/RequestOptions.cs @@ -24,29 +24,29 @@ namespace Org.OpenAPITools.Client /// /// Parameters to be bound to path parts of the Request's URL /// - public Dictionary PathParameters { get; set; } + 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; } + public Multimap QueryParameters { get; set; } /// /// Header parameters to be applied to to the request. /// Keys may have 1 or more values associated. /// - public Multimap HeaderParameters { get; set; } + public Multimap HeaderParameters { get; set; } /// /// Form parameters to be sent along with the request. /// - public Dictionary FormParameters { get; set; } + public Dictionary FormParameters { get; set; } /// /// File parameters to be sent along with the request. /// - public Dictionary FileParameters { get; set; } + public Dictionary FileParameters { get; set; } /// /// Cookies to be sent along with the request. @@ -67,8 +67,8 @@ namespace Org.OpenAPITools.Client QueryParameters = new Multimap(); HeaderParameters = new Multimap(); FormParameters = new Dictionary(); - FileParameters = new Dictionary(); + FileParameters = new Dictionary(); Cookies = new List(); } } -} \ No newline at end of file +} diff --git a/samples/client/petstore/csharp/OpenAPIClient/.openapi-generator/VERSION b/samples/client/petstore/csharp/OpenAPIClient/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/client/petstore/csharp/OpenAPIClient/.openapi-generator/VERSION +++ b/samples/client/petstore/csharp/OpenAPIClient/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/client/petstore/csharp/OpenAPIClient/README.md b/samples/client/petstore/csharp/OpenAPIClient/README.md index f33c01b2a43..0174c279b8d 100644 --- a/samples/client/petstore/csharp/OpenAPIClient/README.md +++ b/samples/client/petstore/csharp/OpenAPIClient/README.md @@ -114,6 +114,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* | [**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 | *FakeApi* | [**TestClientModel**](docs/FakeApi.md#testclientmodel) | **PATCH** /fake | To test \"client\" model diff --git a/samples/client/petstore/csharp/OpenAPIClient/docs/FakeApi.md b/samples/client/petstore/csharp/OpenAPIClient/docs/FakeApi.md index 64474672ca8..b821e3f31c1 100644 --- a/samples/client/petstore/csharp/OpenAPIClient/docs/FakeApi.md +++ b/samples/client/petstore/csharp/OpenAPIClient/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 | +[**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 | [**TestClientModel**](FakeApi.md#testclientmodel) | **PATCH** /fake | To test \"client\" model @@ -546,13 +547,87 @@ No authorization required [[Back to README]](../README.md) +## TestBodyWithBinary + +> void TestBodyWithBinary (System.IO.Stream body) + + + +For this test, the body has to be a binary file. + +### 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 TestBodyWithBinaryExample + { + public static void Main() + { + Configuration.Default.BasePath = "http://petstore.swagger.io:80/v2"; + var apiInstance = new FakeApi(Configuration.Default); + var body = BINARY_DATA_HERE; // System.IO.Stream | image to upload + + try + { + apiInstance.TestBodyWithBinary(body); + } + catch (ApiException e) + { + Debug.Print("Exception when calling FakeApi.TestBodyWithBinary: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +### Parameters + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | **System.IO.Stream**| image to upload | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: image/png +- **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) + + ## TestBodyWithFileSchema > void TestBodyWithFileSchema (FileSchemaTestClass fileSchemaTestClass) -For this test, the body for this request much reference a schema named `File`. +For this test, the body for this request must reference a schema named `File`. ### Example 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 6161aa33d32..f9f9e77ca7e 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 @@ -178,7 +178,28 @@ namespace Org.OpenAPITools.Api /// /// /// - /// For this test, the body for this request much reference a schema named `File`. + /// For this test, the body has to be a binary file. + /// + /// Thrown when fails to make API call + /// image to upload + /// + void TestBodyWithBinary (System.IO.Stream body); + + /// + /// + /// + /// + /// For this test, the body has to be a binary file. + /// + /// Thrown when fails to make API call + /// image to upload + /// ApiResponse of Object(void) + ApiResponse TestBodyWithBinaryWithHttpInfo (System.IO.Stream body); + /// + /// + /// + /// + /// For this test, the body for this request must reference a schema named `File`. /// /// Thrown when fails to make API call /// @@ -189,7 +210,7 @@ namespace Org.OpenAPITools.Api /// /// /// - /// For this test, the body for this request much reference a schema named `File`. + /// For this test, the body for this request must reference a schema named `File`. /// /// Thrown when fails to make API call /// @@ -594,7 +615,30 @@ namespace Org.OpenAPITools.Api /// /// /// - /// For this test, the body for this request much reference a schema named `File`. + /// For this test, the body has to be a binary file. + /// + /// Thrown when fails to make API call + /// image to upload + /// Cancellation Token to cancel request (optional) + /// Task of void + System.Threading.Tasks.Task TestBodyWithBinaryAsync (System.IO.Stream body, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// + /// + /// + /// For this test, the body has to be a binary file. + /// + /// Thrown when fails to make API call + /// image to upload + /// Cancellation Token to cancel request (optional) + /// Task of ApiResponse + System.Threading.Tasks.Task> TestBodyWithBinaryWithHttpInfoAsync (System.IO.Stream body, CancellationToken cancellationToken = default(CancellationToken)); + /// + /// + /// + /// + /// For this test, the body for this request must reference a schema named `File`. /// /// Thrown when fails to make API call /// @@ -606,7 +650,7 @@ namespace Org.OpenAPITools.Api /// /// /// - /// For this test, the body for this request much reference a schema named `File`. + /// For this test, the body for this request must reference a schema named `File`. /// /// Thrown when fails to make API call /// @@ -1988,7 +2032,154 @@ namespace Org.OpenAPITools.Api } /// - /// For this test, the body for this request much reference a schema named `File`. + /// For this test, the body has to be a binary file. + /// + /// Thrown when fails to make API call + /// image to upload + /// + public void TestBodyWithBinary (System.IO.Stream body) + { + TestBodyWithBinaryWithHttpInfo(body); + } + + /// + /// For this test, the body has to be a binary file. + /// + /// Thrown when fails to make API call + /// image to upload + /// ApiResponse of Object(void) + public ApiResponse TestBodyWithBinaryWithHttpInfo (System.IO.Stream body) + { + // verify the required parameter 'body' is set + if (body == null) + throw new ApiException(400, "Missing required parameter 'body' when calling FakeApi->TestBodyWithBinary"); + + var localVarPath = "/fake/body-with-binary"; + var localVarPathParams = new Dictionary(); + var localVarQueryParams = new List>(); + var localVarHeaderParams = new Dictionary(this.Configuration.DefaultHeader); + var localVarFormParams = new Dictionary(); + var localVarFileParams = new Dictionary(); + Object localVarPostBody = null; + + // to determine the Content-Type header + String[] localVarHttpContentTypes = new String[] { + "image/png" + }; + String localVarHttpContentType = this.Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); + + // to determine the Accept header + String[] localVarHttpHeaderAccepts = new String[] { + }; + String localVarHttpHeaderAccept = this.Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); + if (localVarHttpHeaderAccept != null) + localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); + + if (body != null && body.GetType() != typeof(byte[])) + { + localVarPostBody = this.Configuration.ApiClient.Serialize(body); // http body (model) parameter + } + else + { + localVarPostBody = body; // byte array + } + + + // make the HTTP request + IRestResponse localVarResponse = (IRestResponse) this.Configuration.ApiClient.CallApi(localVarPath, + Method.PUT, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, + localVarPathParams, localVarHttpContentType); + + int localVarStatusCode = (int) localVarResponse.StatusCode; + + if (ExceptionFactory != null) + { + Exception exception = ExceptionFactory("TestBodyWithBinary", localVarResponse); + if (exception != null) throw exception; + } + + return new ApiResponse(localVarStatusCode, + localVarResponse.Headers.ToDictionary(x => x.Name, x => string.Join(",", x.Value)), + null); + } + + /// + /// For this test, the body has to be a binary file. + /// + /// Thrown when fails to make API call + /// image to upload + /// Cancellation Token to cancel request (optional) + /// Task of void + public async System.Threading.Tasks.Task TestBodyWithBinaryAsync (System.IO.Stream body, CancellationToken cancellationToken = default(CancellationToken)) + { + await TestBodyWithBinaryWithHttpInfoAsync(body, cancellationToken); + + } + + /// + /// For this test, the body has to be a binary file. + /// + /// Thrown when fails to make API call + /// image to upload + /// Cancellation Token to cancel request (optional) + /// Task of ApiResponse + public async System.Threading.Tasks.Task> TestBodyWithBinaryWithHttpInfoAsync (System.IO.Stream body, CancellationToken cancellationToken = default(CancellationToken)) + { + // verify the required parameter 'body' is set + if (body == null) + throw new ApiException(400, "Missing required parameter 'body' when calling FakeApi->TestBodyWithBinary"); + + var localVarPath = "/fake/body-with-binary"; + var localVarPathParams = new Dictionary(); + var localVarQueryParams = new List>(); + var localVarHeaderParams = new Dictionary(this.Configuration.DefaultHeader); + var localVarFormParams = new Dictionary(); + var localVarFileParams = new Dictionary(); + Object localVarPostBody = null; + + // to determine the Content-Type header + String[] localVarHttpContentTypes = new String[] { + "image/png" + }; + String localVarHttpContentType = this.Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); + + // to determine the Accept header + String[] localVarHttpHeaderAccepts = new String[] { + }; + String localVarHttpHeaderAccept = this.Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); + if (localVarHttpHeaderAccept != null) + localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); + + if (body != null && body.GetType() != typeof(byte[])) + { + localVarPostBody = this.Configuration.ApiClient.Serialize(body); // http body (model) parameter + } + else + { + localVarPostBody = body; // byte array + } + + + // make the HTTP request + IRestResponse localVarResponse = (IRestResponse) await this.Configuration.ApiClient.CallApiAsync(localVarPath, + Method.PUT, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, + localVarPathParams, localVarHttpContentType, cancellationToken); + + int localVarStatusCode = (int) localVarResponse.StatusCode; + + if (ExceptionFactory != null) + { + Exception exception = ExceptionFactory("TestBodyWithBinary", localVarResponse); + if (exception != null) throw exception; + } + + return new ApiResponse(localVarStatusCode, + localVarResponse.Headers.ToDictionary(x => x.Name, x => string.Join(",", x.Value)), + null); + } + + /// + /// For this test, the body for this request must reference a schema named `File`. /// /// Thrown when fails to make API call /// @@ -1999,7 +2190,7 @@ namespace Org.OpenAPITools.Api } /// - /// For this test, the body for this request much reference a schema named `File`. + /// For this test, the body for this request must reference a schema named `File`. /// /// Thrown when fails to make API call /// @@ -2060,7 +2251,7 @@ namespace Org.OpenAPITools.Api } /// - /// For this test, the body for this request much reference a schema named `File`. + /// For this test, the body for this request must reference a schema named `File`. /// /// Thrown when fails to make API call /// @@ -2073,7 +2264,7 @@ namespace Org.OpenAPITools.Api } /// - /// For this test, the body for this request much reference a schema named `File`. + /// For this test, the body for this request must reference a schema named `File`. /// /// Thrown when fails to make API call /// @@ -3394,7 +3585,7 @@ namespace Org.OpenAPITools.Api if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); - if (pipe != null) localVarQueryParams.AddRange(this.Configuration.ApiClient.ParameterToKeyValuePairs("multi", "pipe", pipe)); // query parameter + if (pipe != null) localVarQueryParams.AddRange(this.Configuration.ApiClient.ParameterToKeyValuePairs("pipes", "pipe", pipe)); // query parameter if (ioutil != null) localVarQueryParams.AddRange(this.Configuration.ApiClient.ParameterToKeyValuePairs("csv", "ioutil", ioutil)); // query parameter if (http != null) localVarQueryParams.AddRange(this.Configuration.ApiClient.ParameterToKeyValuePairs("ssv", "http", http)); // query parameter if (url != null) localVarQueryParams.AddRange(this.Configuration.ApiClient.ParameterToKeyValuePairs("csv", "url", url)); // query parameter @@ -3485,7 +3676,7 @@ namespace Org.OpenAPITools.Api if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); - if (pipe != null) localVarQueryParams.AddRange(this.Configuration.ApiClient.ParameterToKeyValuePairs("multi", "pipe", pipe)); // query parameter + if (pipe != null) localVarQueryParams.AddRange(this.Configuration.ApiClient.ParameterToKeyValuePairs("pipes", "pipe", pipe)); // query parameter if (ioutil != null) localVarQueryParams.AddRange(this.Configuration.ApiClient.ParameterToKeyValuePairs("csv", "ioutil", ioutil)); // query parameter if (http != null) localVarQueryParams.AddRange(this.Configuration.ApiClient.ParameterToKeyValuePairs("ssv", "http", http)); // query parameter if (url != null) localVarQueryParams.AddRange(this.Configuration.ApiClient.ParameterToKeyValuePairs("csv", "url", url)); // query parameter diff --git a/samples/client/petstore/elixir/.openapi-generator/VERSION b/samples/client/petstore/elixir/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/client/petstore/elixir/.openapi-generator/VERSION +++ b/samples/client/petstore/elixir/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x 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 7d05057b3a6..407ff92dbbd 100644 --- a/samples/client/petstore/elixir/lib/openapi_petstore/api/fake.ex +++ b/samples/client/petstore/elixir/lib/openapi_petstore/api/fake.ex @@ -215,7 +215,33 @@ defmodule OpenapiPetstore.Api.Fake do end @doc """ - For this test, the body for this request much reference a schema named `File`. + For this test, the body has to be a binary file. + + ## Parameters + + - connection (OpenapiPetstore.Connection): Connection to server + - body (String.t): image to upload + - opts (KeywordList): [optional] Optional parameters + ## Returns + + {:ok, nil} on success + {:error, Tesla.Env.t} on failure + """ + @spec test_body_with_binary(Tesla.Env.client, String.t, keyword()) :: {:ok, nil} | {:error, Tesla.Env.t} + def test_body_with_binary(connection, body, _opts \\ []) do + %{} + |> method(:put) + |> url("/fake/body-with-binary") + |> add_param(:body, :body, body) + |> Enum.into([]) + |> (&Connection.request(connection, &1)).() + |> evaluate_response([ + { 200, false} + ]) + end + + @doc """ + For this test, the body for this request must reference a schema named `File`. ## Parameters diff --git a/samples/client/petstore/erlang-client/.openapi-generator/FILES b/samples/client/petstore/erlang-client/.openapi-generator/FILES new file mode 100644 index 00000000000..63262b16b50 --- /dev/null +++ b/samples/client/petstore/erlang-client/.openapi-generator/FILES @@ -0,0 +1,13 @@ +README.md +rebar.config +src/petstore.app.src +src/petstore_api_response.erl +src/petstore_category.erl +src/petstore_order.erl +src/petstore_pet.erl +src/petstore_pet_api.erl +src/petstore_store_api.erl +src/petstore_tag.erl +src/petstore_user.erl +src/petstore_user_api.erl +src/petstore_utils.erl diff --git a/samples/client/petstore/erlang-client/.openapi-generator/VERSION b/samples/client/petstore/erlang-client/.openapi-generator/VERSION index c30f0ec2be7..6555596f931 100644 --- a/samples/client/petstore/erlang-client/.openapi-generator/VERSION +++ b/samples/client/petstore/erlang-client/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.0-SNAPSHOT \ No newline at end of file +5.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/erlang-client/src/petstore_pet_api.erl b/samples/client/petstore/erlang-client/src/petstore_pet_api.erl index 54991ba9dd1..0aa298cb360 100644 --- a/samples/client/petstore/erlang-client/src/petstore_pet_api.erl +++ b/samples/client/petstore/erlang-client/src/petstore_pet_api.erl @@ -9,7 +9,7 @@ update_pet_with_form/2, update_pet_with_form/3, upload_file/2, upload_file/3]). --define(BASE_URL, "/v2"). +-define(BASE_URL, <<"/v2">>). %% @doc Add a new pet to the store %% @@ -23,7 +23,7 @@ add_pet(Ctx, PetstorePet, Optional) -> Cfg = maps:get(cfg, Optional, application:get_env(kuberl, config, #{})), Method = post, - Path = ["/pet"], + Path = [<<"/pet">>], QS = [], Headers = [], Body1 = PetstorePet, @@ -44,7 +44,7 @@ delete_pet(Ctx, PetId, Optional) -> Cfg = maps:get(cfg, Optional, application:get_env(kuberl, config, #{})), Method = delete, - Path = ["/pet/", PetId, ""], + Path = [<<"/pet/", PetId, "">>], QS = [], Headers = []++petstore_utils:optional_params(['api_key'], _OptionalParams), Body1 = [], @@ -65,7 +65,7 @@ find_pets_by_status(Ctx, Status, Optional) -> Cfg = maps:get(cfg, Optional, application:get_env(kuberl, config, #{})), Method = get, - Path = ["/pet/findByStatus"], + Path = [<<"/pet/findByStatus">>], QS = lists:flatten([[{<<"status">>, X} || X <- Status]])++petstore_utils:optional_params([], _OptionalParams), Headers = [], Body1 = [], @@ -86,7 +86,7 @@ find_pets_by_tags(Ctx, Tags, Optional) -> Cfg = maps:get(cfg, Optional, application:get_env(kuberl, config, #{})), Method = get, - Path = ["/pet/findByTags"], + Path = [<<"/pet/findByTags">>], QS = lists:flatten([[{<<"tags">>, X} || X <- Tags]])++petstore_utils:optional_params([], _OptionalParams), Headers = [], Body1 = [], @@ -107,7 +107,7 @@ get_pet_by_id(Ctx, PetId, Optional) -> Cfg = maps:get(cfg, Optional, application:get_env(kuberl, config, #{})), Method = get, - Path = ["/pet/", PetId, ""], + Path = [<<"/pet/", PetId, "">>], QS = [], Headers = [], Body1 = [], @@ -128,7 +128,7 @@ update_pet(Ctx, PetstorePet, Optional) -> Cfg = maps:get(cfg, Optional, application:get_env(kuberl, config, #{})), Method = put, - Path = ["/pet"], + Path = [<<"/pet">>], QS = [], Headers = [], Body1 = PetstorePet, @@ -149,7 +149,7 @@ update_pet_with_form(Ctx, PetId, Optional) -> Cfg = maps:get(cfg, Optional, application:get_env(kuberl, config, #{})), Method = post, - Path = ["/pet/", PetId, ""], + Path = [<<"/pet/", PetId, "">>], QS = [], Headers = [], Body1 = {form, []++petstore_utils:optional_params(['name', 'status'], _OptionalParams)}, @@ -170,7 +170,7 @@ upload_file(Ctx, PetId, Optional) -> Cfg = maps:get(cfg, Optional, application:get_env(kuberl, config, #{})), Method = post, - Path = ["/pet/", PetId, "/uploadImage"], + Path = [<<"/pet/", PetId, "/uploadImage">>], QS = [], Headers = [], Body1 = {form, []++petstore_utils:optional_params(['additionalMetadata', 'file'], _OptionalParams)}, diff --git a/samples/client/petstore/erlang-client/src/petstore_store_api.erl b/samples/client/petstore/erlang-client/src/petstore_store_api.erl index 2e72823d9d9..0d59557dc98 100644 --- a/samples/client/petstore/erlang-client/src/petstore_store_api.erl +++ b/samples/client/petstore/erlang-client/src/petstore_store_api.erl @@ -5,7 +5,7 @@ get_order_by_id/2, get_order_by_id/3, place_order/2, place_order/3]). --define(BASE_URL, "/v2"). +-define(BASE_URL, <<"/v2">>). %% @doc Delete purchase order by ID %% For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors @@ -19,7 +19,7 @@ delete_order(Ctx, OrderId, Optional) -> Cfg = maps:get(cfg, Optional, application:get_env(kuberl, config, #{})), Method = delete, - Path = ["/store/order/", OrderId, ""], + Path = [<<"/store/order/", OrderId, "">>], QS = [], Headers = [], Body1 = [], @@ -40,7 +40,7 @@ get_inventory(Ctx, Optional) -> Cfg = maps:get(cfg, Optional, application:get_env(kuberl, config, #{})), Method = get, - Path = ["/store/inventory"], + Path = [<<"/store/inventory">>], QS = [], Headers = [], Body1 = [], @@ -61,7 +61,7 @@ get_order_by_id(Ctx, OrderId, Optional) -> Cfg = maps:get(cfg, Optional, application:get_env(kuberl, config, #{})), Method = get, - Path = ["/store/order/", OrderId, ""], + Path = [<<"/store/order/", OrderId, "">>], QS = [], Headers = [], Body1 = [], @@ -82,7 +82,7 @@ place_order(Ctx, PetstoreOrder, Optional) -> Cfg = maps:get(cfg, Optional, application:get_env(kuberl, config, #{})), Method = post, - Path = ["/store/order"], + Path = [<<"/store/order">>], QS = [], Headers = [], Body1 = PetstoreOrder, diff --git a/samples/client/petstore/erlang-client/src/petstore_user_api.erl b/samples/client/petstore/erlang-client/src/petstore_user_api.erl index 45a8a9d7872..a60ccfb43eb 100644 --- a/samples/client/petstore/erlang-client/src/petstore_user_api.erl +++ b/samples/client/petstore/erlang-client/src/petstore_user_api.erl @@ -9,7 +9,7 @@ logout_user/1, logout_user/2, update_user/3, update_user/4]). --define(BASE_URL, "/v2"). +-define(BASE_URL, <<"/v2">>). %% @doc Create user %% This can only be done by the logged in user. @@ -23,7 +23,7 @@ create_user(Ctx, PetstoreUser, Optional) -> Cfg = maps:get(cfg, Optional, application:get_env(kuberl, config, #{})), Method = post, - Path = ["/user"], + Path = [<<"/user">>], QS = [], Headers = [], Body1 = PetstoreUser, @@ -44,7 +44,7 @@ create_users_with_array_input(Ctx, PetstoreUserArray, Optional) -> Cfg = maps:get(cfg, Optional, application:get_env(kuberl, config, #{})), Method = post, - Path = ["/user/createWithArray"], + Path = [<<"/user/createWithArray">>], QS = [], Headers = [], Body1 = PetstoreUserArray, @@ -65,7 +65,7 @@ create_users_with_list_input(Ctx, PetstoreUserArray, Optional) -> Cfg = maps:get(cfg, Optional, application:get_env(kuberl, config, #{})), Method = post, - Path = ["/user/createWithList"], + Path = [<<"/user/createWithList">>], QS = [], Headers = [], Body1 = PetstoreUserArray, @@ -86,7 +86,7 @@ delete_user(Ctx, Username, Optional) -> Cfg = maps:get(cfg, Optional, application:get_env(kuberl, config, #{})), Method = delete, - Path = ["/user/", Username, ""], + Path = [<<"/user/", Username, "">>], QS = [], Headers = [], Body1 = [], @@ -107,7 +107,7 @@ get_user_by_name(Ctx, Username, Optional) -> Cfg = maps:get(cfg, Optional, application:get_env(kuberl, config, #{})), Method = get, - Path = ["/user/", Username, ""], + Path = [<<"/user/", Username, "">>], QS = [], Headers = [], Body1 = [], @@ -128,7 +128,7 @@ login_user(Ctx, Username, Password, Optional) -> Cfg = maps:get(cfg, Optional, application:get_env(kuberl, config, #{})), Method = get, - Path = ["/user/login"], + Path = [<<"/user/login">>], QS = lists:flatten([{<<"username">>, Username}, {<<"password">>, Password}])++petstore_utils:optional_params([], _OptionalParams), Headers = [], Body1 = [], @@ -149,7 +149,7 @@ logout_user(Ctx, Optional) -> Cfg = maps:get(cfg, Optional, application:get_env(kuberl, config, #{})), Method = get, - Path = ["/user/logout"], + Path = [<<"/user/logout">>], QS = [], Headers = [], Body1 = [], @@ -170,7 +170,7 @@ update_user(Ctx, Username, PetstoreUser, Optional) -> Cfg = maps:get(cfg, Optional, application:get_env(kuberl, config, #{})), Method = put, - Path = ["/user/", Username, ""], + Path = [<<"/user/", Username, "">>], QS = [], Headers = [], Body1 = PetstoreUser, diff --git a/samples/client/petstore/erlang-proper/.openapi-generator/FILES b/samples/client/petstore/erlang-proper/.openapi-generator/FILES new file mode 100644 index 00000000000..2a5af8d28a5 --- /dev/null +++ b/samples/client/petstore/erlang-proper/.openapi-generator/FILES @@ -0,0 +1,20 @@ +README.md +rebar.config +src/model/petstore_api_response.erl +src/model/petstore_category.erl +src/model/petstore_order.erl +src/model/petstore_pet.erl +src/model/petstore_tag.erl +src/model/petstore_user.erl +src/petstore.app.src +src/petstore.hrl +src/petstore_api.erl +src/petstore_api.erl +src/petstore_api.erl +src/petstore_gen.erl +src/petstore_statem.erl +src/petstore_statem.erl +src/petstore_statem.erl +src/petstore_statem.hrl +src/petstore_utils.erl +test/prop_petstore.erl diff --git a/samples/client/petstore/erlang-proper/.openapi-generator/VERSION b/samples/client/petstore/erlang-proper/.openapi-generator/VERSION index d99e7162d01..6555596f931 100644 --- a/samples/client/petstore/erlang-proper/.openapi-generator/VERSION +++ b/samples/client/petstore/erlang-proper/.openapi-generator/VERSION @@ -1 +1 @@ -5.0.0-SNAPSHOT \ No newline at end of file +5.2.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 5f68295fc19..e8415097f3a 100644 --- a/samples/client/petstore/go/go-petstore/.openapi-generator/VERSION +++ b/samples/client/petstore/go/go-petstore/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/client/petstore/go/go-petstore/client.go b/samples/client/petstore/go/go-petstore/client.go index 251130b3c2c..411570ac871 100644 --- a/samples/client/petstore/go/go-petstore/client.go +++ b/samples/client/petstore/go/go-petstore/client.go @@ -18,6 +18,7 @@ import ( "errors" "fmt" "io" + "io/ioutil" "log" "mime/multipart" "net/http" @@ -374,6 +375,15 @@ func (c *APIClient) decode(v interface{}, b []byte, contentType string) (err err *s = string(b) return nil } + if f, ok := v.(**os.File); ok { + *f, err = ioutil.TempFile("", "HttpClientFile") + if err != nil { + return + } + _, err = (*f).Write(b) + _, err = (*f).Seek(0, io.SeekStart) + return + } if xmlCheck.MatchString(contentType) { if err = xml.Unmarshal(b, v); err != nil { return err diff --git a/samples/client/petstore/groovy/.openapi-generator/VERSION b/samples/client/petstore/groovy/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/client/petstore/groovy/.openapi-generator/VERSION +++ b/samples/client/petstore/groovy/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/client/petstore/haskell-http-client/.openapi-generator/VERSION b/samples/client/petstore/haskell-http-client/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/client/petstore/haskell-http-client/.openapi-generator/VERSION +++ b/samples/client/petstore/haskell-http-client/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x 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 5f68295fc19..e8415097f3a 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,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/client/petstore/java/feign/.openapi-generator/VERSION b/samples/client/petstore/java/feign/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/client/petstore/java/feign/.openapi-generator/VERSION +++ b/samples/client/petstore/java/feign/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x 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 5f68295fc19..e8415097f3a 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,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/client/petstore/java/jersey1/.openapi-generator/VERSION b/samples/client/petstore/java/jersey1/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/client/petstore/java/jersey1/.openapi-generator/VERSION +++ b/samples/client/petstore/java/jersey1/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x 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 5f68295fc19..e8415097f3a 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,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/client/petstore/java/jersey2-java8/.openapi-generator/VERSION b/samples/client/petstore/java/jersey2-java8/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/client/petstore/java/jersey2-java8/.openapi-generator/VERSION +++ b/samples/client/petstore/java/jersey2-java8/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x 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 5f68295fc19..e8415097f3a 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,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/client/petstore/java/microprofile-rest-client/pom.xml b/samples/client/petstore/java/microprofile-rest-client/pom.xml index 5faf0c0c062..91b6ef610f5 100644 --- a/samples/client/petstore/java/microprofile-rest-client/pom.xml +++ b/samples/client/petstore/java/microprofile-rest-client/pom.xml @@ -141,7 +141,7 @@ 1.5.18 9.2.9.v20150224 4.13.1 - 1.1.7 + 1.2.0 2.5 3.2.7 2.9.7 diff --git a/samples/client/petstore/java/native-async/.openapi-generator/VERSION b/samples/client/petstore/java/native-async/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/client/petstore/java/native-async/.openapi-generator/VERSION +++ b/samples/client/petstore/java/native-async/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/client/petstore/java/native-async/build.gradle b/samples/client/petstore/java/native-async/build.gradle index 80b7de54bf7..9e037855cba 100644 --- a/samples/client/petstore/java/native-async/build.gradle +++ b/samples/client/petstore/java/native-async/build.gradle @@ -22,6 +22,17 @@ apply plugin: 'maven' sourceCompatibility = JavaVersion.VERSION_11 targetCompatibility = JavaVersion.VERSION_11 +// Some text from the schema is copy pasted into the source files as UTF-8 +// but the default still seems to be to use platform encoding +tasks.withType(JavaCompile) { + configure(options) { + options.encoding = 'UTF-8' + } +} +javadoc { + options.encoding = 'UTF-8' +} + install { repositories.mavenInstaller { pom.artifactId = 'petstore-native' @@ -53,7 +64,6 @@ ext { swagger_annotations_version = "1.5.22" jackson_version = "2.10.4" junit_version = "4.13.1" - ws_rs_version = "2.1.1" } dependencies { @@ -65,6 +75,5 @@ dependencies { implementation "com.fasterxml.jackson.datatype:jackson-datatype-jsr310:$jackson_version" implementation "org.openapitools:jackson-databind-nullable:0.2.1" implementation 'javax.annotation:javax.annotation-api:1.3.2' - implementation "javax.ws.rs:javax.ws.rs-api:$ws_rs_version" testImplementation "junit:junit:$junit_version" } diff --git a/samples/client/petstore/java/native-async/pom.xml b/samples/client/petstore/java/native-async/pom.xml index b49e8a71559..de6911c94fd 100644 --- a/samples/client/petstore/java/native-async/pom.xml +++ b/samples/client/petstore/java/native-async/pom.xml @@ -200,13 +200,6 @@ provided - - - javax.ws.rs - javax.ws.rs-api - ${javax-ws-rs-api-version} - - junit @@ -224,7 +217,6 @@ 2.10.4 0.2.1 1.3.2 - 2.1.1 4.13.1 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 519cd35cc6a..04d3f7c1799 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 @@ -11,11 +11,9 @@ import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; -import javax.ws.rs.core.GenericType; -import javax.ws.rs.ext.ContextResolver; @javax.annotation.processing.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") -public class JSON implements ContextResolver { +public class JSON { private ObjectMapper mapper; public JSON() { @@ -41,11 +39,6 @@ public class JSON implements ContextResolver { mapper.setDateFormat(dateFormat); } - @Override - public ObjectMapper getContext(Class type) { - return mapper; - } - /** * Get the object mapper * @@ -178,10 +171,10 @@ public class JSON implements ContextResolver { visitedClasses.add(modelClass); // Traverse the oneOf/anyOf composed schemas. - Map descendants = modelDescendants.get(modelClass); + Map> descendants = modelDescendants.get(modelClass); if (descendants != null) { - for (GenericType childType : descendants.values()) { - if (isInstanceOf(childType.getRawType(), inst, visitedClasses)) { + for (Class childType : descendants.values()) { + if (isInstanceOf(childType, inst, visitedClasses)) { return true; } } @@ -192,12 +185,12 @@ public class JSON implements ContextResolver { /** * A map of discriminators for all model classes. */ - private static Map, ClassDiscriminatorMapping> modelDiscriminators = new HashMap, ClassDiscriminatorMapping>(); + private static Map, ClassDiscriminatorMapping> modelDiscriminators = new HashMap<>(); /** * A map of oneOf/anyOf descendants for each model class. */ - private static Map, Map> modelDescendants = new HashMap, Map>(); + private static Map, Map>> modelDescendants = new HashMap<>(); /** * Register a model class discriminator. @@ -217,7 +210,7 @@ public class JSON implements ContextResolver { * @param modelClass the model class * @param descendants a map of oneOf/anyOf descendants. */ - public static void registerDescendants(Class modelClass, Map descendants) { + public static void registerDescendants(Class modelClass, Map> descendants) { modelDescendants.put(modelClass, descendants); } diff --git a/samples/client/petstore/java/native-async/src/main/java/org/openapitools/client/api/AnotherFakeApi.java b/samples/client/petstore/java/native-async/src/main/java/org/openapitools/client/api/AnotherFakeApi.java index f2247d141bb..59947067502 100644 --- a/samples/client/petstore/java/native-async/src/main/java/org/openapitools/client/api/AnotherFakeApi.java +++ b/samples/client/petstore/java/native-async/src/main/java/org/openapitools/client/api/AnotherFakeApi.java @@ -60,19 +60,16 @@ public class AnotherFakeApi { memberVarResponseInterceptor = apiClient.getResponseInterceptor(); } - private ApiException getApiException(String operationId, HttpResponselocalVarResponse) { - return new ApiException(localVarResponse.statusCode(), - operationId + " call received non-success response", - localVarResponse.headers(), - localVarResponse.body()); + private ApiException getApiException(String operationId, HttpResponse response) { + String message = formatExceptionMessage(operationId, response.statusCode(), response.body()); + return new ApiException(response.statusCode(), message, response.headers(), response.body()); } - protected ApiException createApiException(HttpResponse response, String msgPrefix) throws IOException { - String body = response.body() == null ? null : new String(response.body().readAllBytes()); - if (body != null) { - msgPrefix += ": " + body; + private String formatExceptionMessage(String operationId, int statusCode, String body) { + if (body == null || body.isEmpty()) { + body = "[no body]"; } - return new ApiException(response.statusCode(), msgPrefix, response.headers(), body); + return operationId + " call failed with: " + statusCode + " - " + body; } /** 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 388dce55a87..c84924f6aba 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 @@ -68,19 +68,16 @@ public class FakeApi { memberVarResponseInterceptor = apiClient.getResponseInterceptor(); } - private ApiException getApiException(String operationId, HttpResponselocalVarResponse) { - return new ApiException(localVarResponse.statusCode(), - operationId + " call received non-success response", - localVarResponse.headers(), - localVarResponse.body()); + private ApiException getApiException(String operationId, HttpResponse response) { + String message = formatExceptionMessage(operationId, response.statusCode(), response.body()); + return new ApiException(response.statusCode(), message, response.headers(), response.body()); } - protected ApiException createApiException(HttpResponse response, String msgPrefix) throws IOException { - String body = response.body() == null ? null : new String(response.body().readAllBytes()); - if (body != null) { - msgPrefix += ": " + body; + private String formatExceptionMessage(String operationId, int statusCode, String body) { + if (body == null || body.isEmpty()) { + body = "[no body]"; } - return new ApiException(response.statusCode(), msgPrefix, response.headers(), body); + return operationId + " call failed with: " + statusCode + " - " + body; } /** diff --git a/samples/client/petstore/java/native-async/src/main/java/org/openapitools/client/api/FakeClassnameTags123Api.java b/samples/client/petstore/java/native-async/src/main/java/org/openapitools/client/api/FakeClassnameTags123Api.java index f8076cd6914..ea9a7d97193 100644 --- a/samples/client/petstore/java/native-async/src/main/java/org/openapitools/client/api/FakeClassnameTags123Api.java +++ b/samples/client/petstore/java/native-async/src/main/java/org/openapitools/client/api/FakeClassnameTags123Api.java @@ -60,19 +60,16 @@ public class FakeClassnameTags123Api { memberVarResponseInterceptor = apiClient.getResponseInterceptor(); } - private ApiException getApiException(String operationId, HttpResponselocalVarResponse) { - return new ApiException(localVarResponse.statusCode(), - operationId + " call received non-success response", - localVarResponse.headers(), - localVarResponse.body()); + private ApiException getApiException(String operationId, HttpResponse response) { + String message = formatExceptionMessage(operationId, response.statusCode(), response.body()); + return new ApiException(response.statusCode(), message, response.headers(), response.body()); } - protected ApiException createApiException(HttpResponse response, String msgPrefix) throws IOException { - String body = response.body() == null ? null : new String(response.body().readAllBytes()); - if (body != null) { - msgPrefix += ": " + body; + private String formatExceptionMessage(String operationId, int statusCode, String body) { + if (body == null || body.isEmpty()) { + body = "[no body]"; } - return new ApiException(response.statusCode(), msgPrefix, response.headers(), body); + return operationId + " call failed with: " + statusCode + " - " + body; } /** diff --git a/samples/client/petstore/java/native-async/src/main/java/org/openapitools/client/api/PetApi.java b/samples/client/petstore/java/native-async/src/main/java/org/openapitools/client/api/PetApi.java index 2dcd304b1f5..e65cb647aaf 100644 --- a/samples/client/petstore/java/native-async/src/main/java/org/openapitools/client/api/PetApi.java +++ b/samples/client/petstore/java/native-async/src/main/java/org/openapitools/client/api/PetApi.java @@ -63,19 +63,16 @@ public class PetApi { memberVarResponseInterceptor = apiClient.getResponseInterceptor(); } - private ApiException getApiException(String operationId, HttpResponselocalVarResponse) { - return new ApiException(localVarResponse.statusCode(), - operationId + " call received non-success response", - localVarResponse.headers(), - localVarResponse.body()); + private ApiException getApiException(String operationId, HttpResponse response) { + String message = formatExceptionMessage(operationId, response.statusCode(), response.body()); + return new ApiException(response.statusCode(), message, response.headers(), response.body()); } - protected ApiException createApiException(HttpResponse response, String msgPrefix) throws IOException { - String body = response.body() == null ? null : new String(response.body().readAllBytes()); - if (body != null) { - msgPrefix += ": " + body; + private String formatExceptionMessage(String operationId, int statusCode, String body) { + if (body == null || body.isEmpty()) { + body = "[no body]"; } - return new ApiException(response.statusCode(), msgPrefix, response.headers(), body); + return operationId + " call failed with: " + statusCode + " - " + body; } /** diff --git a/samples/client/petstore/java/native-async/src/main/java/org/openapitools/client/api/StoreApi.java b/samples/client/petstore/java/native-async/src/main/java/org/openapitools/client/api/StoreApi.java index ec19468ccef..82bb7296d85 100644 --- a/samples/client/petstore/java/native-async/src/main/java/org/openapitools/client/api/StoreApi.java +++ b/samples/client/petstore/java/native-async/src/main/java/org/openapitools/client/api/StoreApi.java @@ -60,19 +60,16 @@ public class StoreApi { memberVarResponseInterceptor = apiClient.getResponseInterceptor(); } - private ApiException getApiException(String operationId, HttpResponselocalVarResponse) { - return new ApiException(localVarResponse.statusCode(), - operationId + " call received non-success response", - localVarResponse.headers(), - localVarResponse.body()); + private ApiException getApiException(String operationId, HttpResponse response) { + String message = formatExceptionMessage(operationId, response.statusCode(), response.body()); + return new ApiException(response.statusCode(), message, response.headers(), response.body()); } - protected ApiException createApiException(HttpResponse response, String msgPrefix) throws IOException { - String body = response.body() == null ? null : new String(response.body().readAllBytes()); - if (body != null) { - msgPrefix += ": " + body; + private String formatExceptionMessage(String operationId, int statusCode, String body) { + if (body == null || body.isEmpty()) { + body = "[no body]"; } - return new ApiException(response.statusCode(), msgPrefix, response.headers(), body); + return operationId + " call failed with: " + statusCode + " - " + body; } /** diff --git a/samples/client/petstore/java/native-async/src/main/java/org/openapitools/client/api/UserApi.java b/samples/client/petstore/java/native-async/src/main/java/org/openapitools/client/api/UserApi.java index ba2cad99cf8..3d9893a34f4 100644 --- a/samples/client/petstore/java/native-async/src/main/java/org/openapitools/client/api/UserApi.java +++ b/samples/client/petstore/java/native-async/src/main/java/org/openapitools/client/api/UserApi.java @@ -60,19 +60,16 @@ public class UserApi { memberVarResponseInterceptor = apiClient.getResponseInterceptor(); } - private ApiException getApiException(String operationId, HttpResponselocalVarResponse) { - return new ApiException(localVarResponse.statusCode(), - operationId + " call received non-success response", - localVarResponse.headers(), - localVarResponse.body()); + private ApiException getApiException(String operationId, HttpResponse response) { + String message = formatExceptionMessage(operationId, response.statusCode(), response.body()); + return new ApiException(response.statusCode(), message, response.headers(), response.body()); } - protected ApiException createApiException(HttpResponse response, String msgPrefix) throws IOException { - String body = response.body() == null ? null : new String(response.body().readAllBytes()); - if (body != null) { - msgPrefix += ": " + body; + private String formatExceptionMessage(String operationId, int statusCode, String body) { + if (body == null || body.isEmpty()) { + body = "[no body]"; } - return new ApiException(response.statusCode(), msgPrefix, response.headers(), body); + return operationId + " call failed with: " + statusCode + " - " + body; } /** diff --git a/samples/client/petstore/java/native-async/src/main/java/org/openapitools/client/model/AbstractOpenApiSchema.java b/samples/client/petstore/java/native-async/src/main/java/org/openapitools/client/model/AbstractOpenApiSchema.java index 1736eb73c5a..882bf6fc3af 100644 --- a/samples/client/petstore/java/native-async/src/main/java/org/openapitools/client/model/AbstractOpenApiSchema.java +++ b/samples/client/petstore/java/native-async/src/main/java/org/openapitools/client/model/AbstractOpenApiSchema.java @@ -17,7 +17,6 @@ import org.openapitools.client.ApiException; import java.util.Objects; import java.lang.reflect.Type; import java.util.Map; -import javax.ws.rs.core.GenericType; import com.fasterxml.jackson.annotation.JsonValue; @@ -46,7 +45,7 @@ public abstract class AbstractOpenApiSchema { * * @return an instance of the actual schema/object */ - public abstract Map getSchemas(); + public abstract Map> getSchemas(); /** * Get the actual instance diff --git a/samples/client/petstore/java/native/.openapi-generator/VERSION b/samples/client/petstore/java/native/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/client/petstore/java/native/.openapi-generator/VERSION +++ b/samples/client/petstore/java/native/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/client/petstore/java/native/build.gradle b/samples/client/petstore/java/native/build.gradle index 80b7de54bf7..9e037855cba 100644 --- a/samples/client/petstore/java/native/build.gradle +++ b/samples/client/petstore/java/native/build.gradle @@ -22,6 +22,17 @@ apply plugin: 'maven' sourceCompatibility = JavaVersion.VERSION_11 targetCompatibility = JavaVersion.VERSION_11 +// Some text from the schema is copy pasted into the source files as UTF-8 +// but the default still seems to be to use platform encoding +tasks.withType(JavaCompile) { + configure(options) { + options.encoding = 'UTF-8' + } +} +javadoc { + options.encoding = 'UTF-8' +} + install { repositories.mavenInstaller { pom.artifactId = 'petstore-native' @@ -53,7 +64,6 @@ ext { swagger_annotations_version = "1.5.22" jackson_version = "2.10.4" junit_version = "4.13.1" - ws_rs_version = "2.1.1" } dependencies { @@ -65,6 +75,5 @@ dependencies { implementation "com.fasterxml.jackson.datatype:jackson-datatype-jsr310:$jackson_version" implementation "org.openapitools:jackson-databind-nullable:0.2.1" implementation 'javax.annotation:javax.annotation-api:1.3.2' - implementation "javax.ws.rs:javax.ws.rs-api:$ws_rs_version" testImplementation "junit:junit:$junit_version" } diff --git a/samples/client/petstore/java/native/pom.xml b/samples/client/petstore/java/native/pom.xml index b49e8a71559..de6911c94fd 100644 --- a/samples/client/petstore/java/native/pom.xml +++ b/samples/client/petstore/java/native/pom.xml @@ -200,13 +200,6 @@ provided - - - javax.ws.rs - javax.ws.rs-api - ${javax-ws-rs-api-version} - - junit @@ -224,7 +217,6 @@ 2.10.4 0.2.1 1.3.2 - 2.1.1 4.13.1 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 519cd35cc6a..04d3f7c1799 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 @@ -11,11 +11,9 @@ import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; -import javax.ws.rs.core.GenericType; -import javax.ws.rs.ext.ContextResolver; @javax.annotation.processing.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") -public class JSON implements ContextResolver { +public class JSON { private ObjectMapper mapper; public JSON() { @@ -41,11 +39,6 @@ public class JSON implements ContextResolver { mapper.setDateFormat(dateFormat); } - @Override - public ObjectMapper getContext(Class type) { - return mapper; - } - /** * Get the object mapper * @@ -178,10 +171,10 @@ public class JSON implements ContextResolver { visitedClasses.add(modelClass); // Traverse the oneOf/anyOf composed schemas. - Map descendants = modelDescendants.get(modelClass); + Map> descendants = modelDescendants.get(modelClass); if (descendants != null) { - for (GenericType childType : descendants.values()) { - if (isInstanceOf(childType.getRawType(), inst, visitedClasses)) { + for (Class childType : descendants.values()) { + if (isInstanceOf(childType, inst, visitedClasses)) { return true; } } @@ -192,12 +185,12 @@ public class JSON implements ContextResolver { /** * A map of discriminators for all model classes. */ - private static Map, ClassDiscriminatorMapping> modelDiscriminators = new HashMap, ClassDiscriminatorMapping>(); + private static Map, ClassDiscriminatorMapping> modelDiscriminators = new HashMap<>(); /** * A map of oneOf/anyOf descendants for each model class. */ - private static Map, Map> modelDescendants = new HashMap, Map>(); + private static Map, Map>> modelDescendants = new HashMap<>(); /** * Register a model class discriminator. @@ -217,7 +210,7 @@ public class JSON implements ContextResolver { * @param modelClass the model class * @param descendants a map of oneOf/anyOf descendants. */ - public static void registerDescendants(Class modelClass, Map descendants) { + public static void registerDescendants(Class modelClass, Map> descendants) { modelDescendants.put(modelClass, descendants); } diff --git a/samples/client/petstore/java/native/src/main/java/org/openapitools/client/api/AnotherFakeApi.java b/samples/client/petstore/java/native/src/main/java/org/openapitools/client/api/AnotherFakeApi.java index 2c0088e76d8..e31f3cd51f9 100644 --- a/samples/client/petstore/java/native/src/main/java/org/openapitools/client/api/AnotherFakeApi.java +++ b/samples/client/petstore/java/native/src/main/java/org/openapitools/client/api/AnotherFakeApi.java @@ -58,12 +58,17 @@ public class AnotherFakeApi { memberVarResponseInterceptor = apiClient.getResponseInterceptor(); } - protected ApiException createApiException(HttpResponse response, String msgPrefix) throws IOException { + protected ApiException getApiException(String operationId, HttpResponse response) throws IOException { String body = response.body() == null ? null : new String(response.body().readAllBytes()); - if (body != null) { - msgPrefix += ": " + body; + String message = formatExceptionMessage(operationId, response.statusCode(), body); + return new ApiException(response.statusCode(), message, response.headers(), body); + } + + private String formatExceptionMessage(String operationId, int statusCode, String body) { + if (body == null || body.isEmpty()) { + body = "[no body]"; } - return new ApiException(response.statusCode(), msgPrefix, response.headers(), body); + return operationId + " call failed with: " + statusCode + " - " + body; } /** @@ -95,7 +100,7 @@ public class AnotherFakeApi { memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw createApiException(localVarResponse, "call123testSpecialTags call received non-success response"); + throw getApiException("call123testSpecialTags", localVarResponse); } return new ApiResponse( localVarResponse.statusCode(), 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 6d3b64d8344..d12c79a0c0d 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 @@ -66,12 +66,17 @@ public class FakeApi { memberVarResponseInterceptor = apiClient.getResponseInterceptor(); } - protected ApiException createApiException(HttpResponse response, String msgPrefix) throws IOException { + protected ApiException getApiException(String operationId, HttpResponse response) throws IOException { String body = response.body() == null ? null : new String(response.body().readAllBytes()); - if (body != null) { - msgPrefix += ": " + body; + String message = formatExceptionMessage(operationId, response.statusCode(), body); + return new ApiException(response.statusCode(), message, response.headers(), body); + } + + private String formatExceptionMessage(String operationId, int statusCode, String body) { + if (body == null || body.isEmpty()) { + body = "[no body]"; } - return new ApiException(response.statusCode(), msgPrefix, response.headers(), body); + return operationId + " call failed with: " + statusCode + " - " + body; } /** @@ -101,7 +106,7 @@ public class FakeApi { memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw createApiException(localVarResponse, "createXmlItem call received non-success response"); + throw getApiException("createXmlItem", localVarResponse); } return new ApiResponse( localVarResponse.statusCode(), @@ -175,7 +180,7 @@ public class FakeApi { memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw createApiException(localVarResponse, "fakeOuterBooleanSerialize call received non-success response"); + throw getApiException("fakeOuterBooleanSerialize", localVarResponse); } return new ApiResponse( localVarResponse.statusCode(), @@ -245,7 +250,7 @@ public class FakeApi { memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw createApiException(localVarResponse, "fakeOuterCompositeSerialize call received non-success response"); + throw getApiException("fakeOuterCompositeSerialize", localVarResponse); } return new ApiResponse( localVarResponse.statusCode(), @@ -315,7 +320,7 @@ public class FakeApi { memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw createApiException(localVarResponse, "fakeOuterNumberSerialize call received non-success response"); + throw getApiException("fakeOuterNumberSerialize", localVarResponse); } return new ApiResponse( localVarResponse.statusCode(), @@ -385,7 +390,7 @@ public class FakeApi { memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw createApiException(localVarResponse, "fakeOuterStringSerialize call received non-success response"); + throw getApiException("fakeOuterStringSerialize", localVarResponse); } return new ApiResponse( localVarResponse.statusCode(), @@ -453,7 +458,7 @@ public class FakeApi { memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw createApiException(localVarResponse, "testBodyWithFileSchema call received non-success response"); + throw getApiException("testBodyWithFileSchema", localVarResponse); } return new ApiResponse( localVarResponse.statusCode(), @@ -527,7 +532,7 @@ public class FakeApi { memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw createApiException(localVarResponse, "testBodyWithQueryParams call received non-success response"); + throw getApiException("testBodyWithQueryParams", localVarResponse); } return new ApiResponse( localVarResponse.statusCode(), @@ -614,7 +619,7 @@ public class FakeApi { memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw createApiException(localVarResponse, "testClientModel call received non-success response"); + throw getApiException("testClientModel", localVarResponse); } return new ApiResponse( localVarResponse.statusCode(), @@ -712,7 +717,7 @@ public class FakeApi { memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw createApiException(localVarResponse, "testEndpointParameters call received non-success response"); + throw getApiException("testEndpointParameters", localVarResponse); } return new ApiResponse( localVarResponse.statusCode(), @@ -804,7 +809,7 @@ public class FakeApi { memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw createApiException(localVarResponse, "testEnumParameters call received non-success response"); + throw getApiException("testEnumParameters", localVarResponse); } return new ApiResponse( localVarResponse.statusCode(), @@ -927,7 +932,7 @@ public class FakeApi { memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw createApiException(localVarResponse, "testGroupParameters call received non-success response"); + throw getApiException("testGroupParameters", localVarResponse); } return new ApiResponse( localVarResponse.statusCode(), @@ -1096,7 +1101,7 @@ public class FakeApi { memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw createApiException(localVarResponse, "testInlineAdditionalProperties call received non-success response"); + throw getApiException("testInlineAdditionalProperties", localVarResponse); } return new ApiResponse( localVarResponse.statusCode(), @@ -1170,7 +1175,7 @@ public class FakeApi { memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw createApiException(localVarResponse, "testJsonFormData call received non-success response"); + throw getApiException("testJsonFormData", localVarResponse); } return new ApiResponse( localVarResponse.statusCode(), @@ -1248,7 +1253,7 @@ public class FakeApi { memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw createApiException(localVarResponse, "testQueryParameterCollectionFormat call received non-success response"); + throw getApiException("testQueryParameterCollectionFormat", localVarResponse); } return new ApiResponse( localVarResponse.statusCode(), diff --git a/samples/client/petstore/java/native/src/main/java/org/openapitools/client/api/FakeClassnameTags123Api.java b/samples/client/petstore/java/native/src/main/java/org/openapitools/client/api/FakeClassnameTags123Api.java index b16a097a9c3..f81bfe6b042 100644 --- a/samples/client/petstore/java/native/src/main/java/org/openapitools/client/api/FakeClassnameTags123Api.java +++ b/samples/client/petstore/java/native/src/main/java/org/openapitools/client/api/FakeClassnameTags123Api.java @@ -58,12 +58,17 @@ public class FakeClassnameTags123Api { memberVarResponseInterceptor = apiClient.getResponseInterceptor(); } - protected ApiException createApiException(HttpResponse response, String msgPrefix) throws IOException { + protected ApiException getApiException(String operationId, HttpResponse response) throws IOException { String body = response.body() == null ? null : new String(response.body().readAllBytes()); - if (body != null) { - msgPrefix += ": " + body; + String message = formatExceptionMessage(operationId, response.statusCode(), body); + return new ApiException(response.statusCode(), message, response.headers(), body); + } + + private String formatExceptionMessage(String operationId, int statusCode, String body) { + if (body == null || body.isEmpty()) { + body = "[no body]"; } - return new ApiException(response.statusCode(), msgPrefix, response.headers(), body); + return operationId + " call failed with: " + statusCode + " - " + body; } /** @@ -95,7 +100,7 @@ public class FakeClassnameTags123Api { memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw createApiException(localVarResponse, "testClassname call received non-success response"); + throw getApiException("testClassname", localVarResponse); } return new ApiResponse( localVarResponse.statusCode(), diff --git a/samples/client/petstore/java/native/src/main/java/org/openapitools/client/api/PetApi.java b/samples/client/petstore/java/native/src/main/java/org/openapitools/client/api/PetApi.java index ff744b27275..36cdfe2419d 100644 --- a/samples/client/petstore/java/native/src/main/java/org/openapitools/client/api/PetApi.java +++ b/samples/client/petstore/java/native/src/main/java/org/openapitools/client/api/PetApi.java @@ -61,12 +61,17 @@ public class PetApi { memberVarResponseInterceptor = apiClient.getResponseInterceptor(); } - protected ApiException createApiException(HttpResponse response, String msgPrefix) throws IOException { + protected ApiException getApiException(String operationId, HttpResponse response) throws IOException { String body = response.body() == null ? null : new String(response.body().readAllBytes()); - if (body != null) { - msgPrefix += ": " + body; + String message = formatExceptionMessage(operationId, response.statusCode(), body); + return new ApiException(response.statusCode(), message, response.headers(), body); + } + + private String formatExceptionMessage(String operationId, int statusCode, String body) { + if (body == null || body.isEmpty()) { + body = "[no body]"; } - return new ApiException(response.statusCode(), msgPrefix, response.headers(), body); + return operationId + " call failed with: " + statusCode + " - " + body; } /** @@ -96,7 +101,7 @@ public class PetApi { memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw createApiException(localVarResponse, "addPet call received non-success response"); + throw getApiException("addPet", localVarResponse); } return new ApiResponse( localVarResponse.statusCode(), @@ -170,7 +175,7 @@ public class PetApi { memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw createApiException(localVarResponse, "deletePet call received non-success response"); + throw getApiException("deletePet", localVarResponse); } return new ApiResponse( localVarResponse.statusCode(), @@ -242,7 +247,7 @@ public class PetApi { memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw createApiException(localVarResponse, "findPetsByStatus call received non-success response"); + throw getApiException("findPetsByStatus", localVarResponse); } return new ApiResponse>( localVarResponse.statusCode(), @@ -323,7 +328,7 @@ public class PetApi { memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw createApiException(localVarResponse, "findPetsByTags call received non-success response"); + throw getApiException("findPetsByTags", localVarResponse); } return new ApiResponse>( localVarResponse.statusCode(), @@ -400,7 +405,7 @@ public class PetApi { memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw createApiException(localVarResponse, "getPetById call received non-success response"); + throw getApiException("getPetById", localVarResponse); } return new ApiResponse( localVarResponse.statusCode(), @@ -467,7 +472,7 @@ public class PetApi { memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw createApiException(localVarResponse, "updatePet call received non-success response"); + throw getApiException("updatePet", localVarResponse); } return new ApiResponse( localVarResponse.statusCode(), @@ -543,7 +548,7 @@ public class PetApi { memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw createApiException(localVarResponse, "updatePetWithForm call received non-success response"); + throw getApiException("updatePetWithForm", localVarResponse); } return new ApiResponse( localVarResponse.statusCode(), @@ -616,7 +621,7 @@ public class PetApi { memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw createApiException(localVarResponse, "uploadFile call received non-success response"); + throw getApiException("uploadFile", localVarResponse); } return new ApiResponse( localVarResponse.statusCode(), @@ -689,7 +694,7 @@ public class PetApi { memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw createApiException(localVarResponse, "uploadFileWithRequiredFile call received non-success response"); + throw getApiException("uploadFileWithRequiredFile", localVarResponse); } return new ApiResponse( localVarResponse.statusCode(), diff --git a/samples/client/petstore/java/native/src/main/java/org/openapitools/client/api/StoreApi.java b/samples/client/petstore/java/native/src/main/java/org/openapitools/client/api/StoreApi.java index caffb9cd6ff..7ff31d54a16 100644 --- a/samples/client/petstore/java/native/src/main/java/org/openapitools/client/api/StoreApi.java +++ b/samples/client/petstore/java/native/src/main/java/org/openapitools/client/api/StoreApi.java @@ -58,12 +58,17 @@ public class StoreApi { memberVarResponseInterceptor = apiClient.getResponseInterceptor(); } - protected ApiException createApiException(HttpResponse response, String msgPrefix) throws IOException { + protected ApiException getApiException(String operationId, HttpResponse response) throws IOException { String body = response.body() == null ? null : new String(response.body().readAllBytes()); - if (body != null) { - msgPrefix += ": " + body; + String message = formatExceptionMessage(operationId, response.statusCode(), body); + return new ApiException(response.statusCode(), message, response.headers(), body); + } + + private String formatExceptionMessage(String operationId, int statusCode, String body) { + if (body == null || body.isEmpty()) { + body = "[no body]"; } - return new ApiException(response.statusCode(), msgPrefix, response.headers(), body); + return operationId + " call failed with: " + statusCode + " - " + body; } /** @@ -93,7 +98,7 @@ public class StoreApi { memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw createApiException(localVarResponse, "deleteOrder call received non-success response"); + throw getApiException("deleteOrder", localVarResponse); } return new ApiResponse( localVarResponse.statusCode(), @@ -160,7 +165,7 @@ public class StoreApi { memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw createApiException(localVarResponse, "getInventory call received non-success response"); + throw getApiException("getInventory", localVarResponse); } return new ApiResponse>( localVarResponse.statusCode(), @@ -224,7 +229,7 @@ public class StoreApi { memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw createApiException(localVarResponse, "getOrderById call received non-success response"); + throw getApiException("getOrderById", localVarResponse); } return new ApiResponse( localVarResponse.statusCode(), @@ -293,7 +298,7 @@ public class StoreApi { memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw createApiException(localVarResponse, "placeOrder call received non-success response"); + throw getApiException("placeOrder", localVarResponse); } return new ApiResponse( localVarResponse.statusCode(), diff --git a/samples/client/petstore/java/native/src/main/java/org/openapitools/client/api/UserApi.java b/samples/client/petstore/java/native/src/main/java/org/openapitools/client/api/UserApi.java index e841c2cd1e6..3d657dacaea 100644 --- a/samples/client/petstore/java/native/src/main/java/org/openapitools/client/api/UserApi.java +++ b/samples/client/petstore/java/native/src/main/java/org/openapitools/client/api/UserApi.java @@ -58,12 +58,17 @@ public class UserApi { memberVarResponseInterceptor = apiClient.getResponseInterceptor(); } - protected ApiException createApiException(HttpResponse response, String msgPrefix) throws IOException { + protected ApiException getApiException(String operationId, HttpResponse response) throws IOException { String body = response.body() == null ? null : new String(response.body().readAllBytes()); - if (body != null) { - msgPrefix += ": " + body; + String message = formatExceptionMessage(operationId, response.statusCode(), body); + return new ApiException(response.statusCode(), message, response.headers(), body); + } + + private String formatExceptionMessage(String operationId, int statusCode, String body) { + if (body == null || body.isEmpty()) { + body = "[no body]"; } - return new ApiException(response.statusCode(), msgPrefix, response.headers(), body); + return operationId + " call failed with: " + statusCode + " - " + body; } /** @@ -93,7 +98,7 @@ public class UserApi { memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw createApiException(localVarResponse, "createUser call received non-success response"); + throw getApiException("createUser", localVarResponse); } return new ApiResponse( localVarResponse.statusCode(), @@ -165,7 +170,7 @@ public class UserApi { memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw createApiException(localVarResponse, "createUsersWithArrayInput call received non-success response"); + throw getApiException("createUsersWithArrayInput", localVarResponse); } return new ApiResponse( localVarResponse.statusCode(), @@ -237,7 +242,7 @@ public class UserApi { memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw createApiException(localVarResponse, "createUsersWithListInput call received non-success response"); + throw getApiException("createUsersWithListInput", localVarResponse); } return new ApiResponse( localVarResponse.statusCode(), @@ -309,7 +314,7 @@ public class UserApi { memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw createApiException(localVarResponse, "deleteUser call received non-success response"); + throw getApiException("deleteUser", localVarResponse); } return new ApiResponse( localVarResponse.statusCode(), @@ -378,7 +383,7 @@ public class UserApi { memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw createApiException(localVarResponse, "getUserByName call received non-success response"); + throw getApiException("getUserByName", localVarResponse); } return new ApiResponse( localVarResponse.statusCode(), @@ -449,7 +454,7 @@ public class UserApi { memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw createApiException(localVarResponse, "loginUser call received non-success response"); + throw getApiException("loginUser", localVarResponse); } return new ApiResponse( localVarResponse.statusCode(), @@ -527,7 +532,7 @@ public class UserApi { memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw createApiException(localVarResponse, "logoutUser call received non-success response"); + throw getApiException("logoutUser", localVarResponse); } return new ApiResponse( localVarResponse.statusCode(), @@ -591,7 +596,7 @@ public class UserApi { memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw createApiException(localVarResponse, "updateUser call received non-success response"); + throw getApiException("updateUser", localVarResponse); } return new ApiResponse( localVarResponse.statusCode(), diff --git a/samples/client/petstore/java/native/src/main/java/org/openapitools/client/model/AbstractOpenApiSchema.java b/samples/client/petstore/java/native/src/main/java/org/openapitools/client/model/AbstractOpenApiSchema.java index 1736eb73c5a..882bf6fc3af 100644 --- a/samples/client/petstore/java/native/src/main/java/org/openapitools/client/model/AbstractOpenApiSchema.java +++ b/samples/client/petstore/java/native/src/main/java/org/openapitools/client/model/AbstractOpenApiSchema.java @@ -17,7 +17,6 @@ import org.openapitools.client.ApiException; import java.util.Objects; import java.lang.reflect.Type; import java.util.Map; -import javax.ws.rs.core.GenericType; import com.fasterxml.jackson.annotation.JsonValue; @@ -46,7 +45,7 @@ public abstract class AbstractOpenApiSchema { * * @return an instance of the actual schema/object */ - public abstract Map getSchemas(); + public abstract Map> getSchemas(); /** * Get the actual instance 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 5f68295fc19..e8415097f3a 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,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x 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 5f68295fc19..e8415097f3a 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,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/client/petstore/java/okhttp-gson/.openapi-generator/VERSION b/samples/client/petstore/java/okhttp-gson/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/client/petstore/java/okhttp-gson/.openapi-generator/VERSION +++ b/samples/client/petstore/java/okhttp-gson/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x 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 5f68295fc19..e8415097f3a 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,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/client/petstore/java/rest-assured/.openapi-generator/VERSION b/samples/client/petstore/java/rest-assured/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/client/petstore/java/rest-assured/.openapi-generator/VERSION +++ b/samples/client/petstore/java/rest-assured/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/client/petstore/java/resteasy/.openapi-generator/VERSION b/samples/client/petstore/java/resteasy/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/client/petstore/java/resteasy/.openapi-generator/VERSION +++ b/samples/client/petstore/java/resteasy/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/client/petstore/java/resteasy/README.md b/samples/client/petstore/java/resteasy/README.md index 6a6d3e6b69d..35b1b3e8770 100644 --- a/samples/client/petstore/java/resteasy/README.md +++ b/samples/client/petstore/java/resteasy/README.md @@ -13,7 +13,7 @@ This spec is mainly for testing Petstore server and contains fake endpoints, mod Building the API client library requires: -1. Java 1.7+ +1. Java 1.8+ 2. Maven/Gradle ## Installation diff --git a/samples/client/petstore/java/resteasy/build.gradle b/samples/client/petstore/java/resteasy/build.gradle index 5d2d24177fc..47a46676967 100644 --- a/samples/client/petstore/java/resteasy/build.gradle +++ b/samples/client/petstore/java/resteasy/build.gradle @@ -33,8 +33,8 @@ if(hasProperty('target') && target == 'android') { targetSdkVersion 23 } compileOptions { - sourceCompatibility JavaVersion.VERSION_1_7 - targetCompatibility JavaVersion.VERSION_1_7 + sourceCompatibility JavaVersion.VERSION_1_8 + targetCompatibility JavaVersion.VERSION_1_8 } // Rename the aar correctly @@ -78,8 +78,8 @@ if(hasProperty('target') && target == 'android') { apply plugin: 'java' apply plugin: 'maven' - sourceCompatibility = JavaVersion.VERSION_1_7 - targetCompatibility = JavaVersion.VERSION_1_7 + sourceCompatibility = JavaVersion.VERSION_1_8 + targetCompatibility = JavaVersion.VERSION_1_8 install { repositories.mavenInstaller { @@ -99,8 +99,7 @@ ext { jackson_databind_version = "2.10.5.1" jackson_databind_nullable_version = "0.2.1" threetenbp_version = "2.9.10" - resteasy_version = "3.1.3.Final" - jodatime_version = "2.9.9" + resteasy_version = "4.5.11.Final" junit_version = "4.13" } @@ -115,9 +114,7 @@ dependencies { 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-joda:$jackson_version" - implementation "joda-time:joda-time:$jodatime_version" - implementation "com.brsanthu:migbase64:2.2" + implementation "com.fasterxml.jackson.datatype:jackson-datatype-jsr310:$jackson_version" implementation 'javax.annotation:javax.annotation-api:1.3.2' testImplementation "junit:junit:$junit_version" } diff --git a/samples/client/petstore/java/resteasy/build.sbt b/samples/client/petstore/java/resteasy/build.sbt index 92192b08f14..2686e7b74de 100644 --- a/samples/client/petstore/java/resteasy/build.sbt +++ b/samples/client/petstore/java/resteasy/build.sbt @@ -11,15 +11,13 @@ lazy val root = (project in file(".")). 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" % "3.1.3.Final" % "compile", - "org.jboss.resteasy" % "resteasy-jackson2-provider" % "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.10.5" % "compile", "com.fasterxml.jackson.core" % "jackson-annotations" % "2.10.5" % "compile", "com.fasterxml.jackson.core" % "jackson-databind" % "2.10.5.1" % "compile", "com.github.joschi.jackson" % "jackson-datatype-threetenbp" % "2.9.10" % "compile", - "com.fasterxml.jackson.datatype" % "jackson-datatype-joda" % "2.9.10" % "compile", - "joda-time" % "joda-time" % "2.9.9" % "compile", - "com.brsanthu" % "migbase64" % "2.2" % "compile", + "com.fasterxml.jackson.datatype" % "jackson-datatype-jsr310" % "2.9.10" % "compile", "javax.annotation" % "javax.annotation-api" % "1.3.2" % "compile", "junit" % "junit" % "4.13" % "test", "com.novocode" % "junit-interface" % "0.10" % "test" diff --git a/samples/client/petstore/java/resteasy/pom.xml b/samples/client/petstore/java/resteasy/pom.xml index 5a197bb9ecb..6e429c2da2d 100644 --- a/samples/client/petstore/java/resteasy/pom.xml +++ b/samples/client/petstore/java/resteasy/pom.xml @@ -135,8 +135,8 @@ maven-compiler-plugin 2.5.1 - 1.7 - 1.7 + 1.8 + 1.8 @@ -145,7 +145,7 @@ 3.1.1 none - 1.7 + 1.8 @@ -175,11 +175,43 @@ org.jboss.resteasy resteasy-client ${resteasy-version} + + + org.jboss.resteasy + resteasy-jaxrs-services + + + net.jcip + jcip-annotations + + + org.jboss.spec.javax.annotation + jboss-annotations-api_1.2_spec + + + javax.activation + activation + + org.jboss.resteasy resteasy-multipart-provider ${resteasy-version} + + + com.sun.xml.bind + jaxb-impl + + + com.sun.mail + javax.mail + + + javax.activation + activation + + @@ -202,28 +234,10 @@ jackson-databind-nullable ${jackson-databind-nullable-version} - - com.fasterxml.jackson.datatype - jackson-datatype-joda - ${jackson-version} - - - joda-time - joda-time - ${jodatime-version} - - - - - com.brsanthu - migbase64 - 2.2 - - org.jboss.resteasy resteasy-jackson2-provider - 3.1.3.Final + ${resteasy-version} com.fasterxml.jackson.datatype @@ -252,13 +266,12 @@ UTF-8 1.5.22 - 3.1.3.Final + 4.5.11.Final 2.10.5 2.10.5.1 0.2.1 1.3.2 2.9.10 - 2.9.9 1.0.0 4.13 diff --git a/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/JSON.java b/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/JSON.java index 9368681606c..85ff9ce7928 100644 --- a/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/JSON.java +++ b/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/JSON.java @@ -3,7 +3,7 @@ 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.joda.*; +import com.fasterxml.jackson.datatype.jsr310.*; import java.text.DateFormat; @@ -24,7 +24,7 @@ public class JSON implements ContextResolver { mapper.setDateFormat(new RFC3339DateFormat()); JsonNullableModule jnm = new JsonNullableModule(); mapper.registerModule(jnm); - mapper.registerModule(new JodaModule()); + mapper.registerModule(new JavaTimeModule()); } /** diff --git a/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/auth/HttpBasicAuth.java b/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/auth/HttpBasicAuth.java index bd1f1225416..b7558356542 100644 --- a/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/auth/HttpBasicAuth.java +++ b/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/auth/HttpBasicAuth.java @@ -15,12 +15,12 @@ package org.openapitools.client.auth; import org.openapitools.client.Pair; -import com.migcomponents.migbase64.Base64; +import java.util.Base64; +import java.nio.charset.StandardCharsets; import java.util.Map; import java.util.List; -import java.io.UnsupportedEncodingException; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") public class HttpBasicAuth implements Authentication { @@ -49,10 +49,6 @@ public class HttpBasicAuth implements Authentication { return; } String str = (username == null ? "" : username) + ":" + (password == null ? "" : password); - try { - headerParams.put("Authorization", "Basic " + Base64.encodeToString(str.getBytes("UTF-8"), false)); - } catch (UnsupportedEncodingException e) { - throw new RuntimeException(e); - } + headerParams.put("Authorization", "Basic " + Base64.getEncoder().encodeToString(str.getBytes(StandardCharsets.UTF_8))); } } diff --git a/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/AdditionalPropertiesClass.java b/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/AdditionalPropertiesClass.java index 4e476cf79de..450b245ab2b 100644 --- a/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/AdditionalPropertiesClass.java +++ b/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/AdditionalPropertiesClass.java @@ -89,7 +89,7 @@ public class AdditionalPropertiesClass { public AdditionalPropertiesClass putMapStringItem(String key, String mapStringItem) { if (this.mapString == null) { - this.mapString = new HashMap(); + this.mapString = new HashMap<>(); } this.mapString.put(key, mapStringItem); return this; @@ -124,7 +124,7 @@ public class AdditionalPropertiesClass { public AdditionalPropertiesClass putMapNumberItem(String key, BigDecimal mapNumberItem) { if (this.mapNumber == null) { - this.mapNumber = new HashMap(); + this.mapNumber = new HashMap<>(); } this.mapNumber.put(key, mapNumberItem); return this; @@ -159,7 +159,7 @@ public class AdditionalPropertiesClass { public AdditionalPropertiesClass putMapIntegerItem(String key, Integer mapIntegerItem) { if (this.mapInteger == null) { - this.mapInteger = new HashMap(); + this.mapInteger = new HashMap<>(); } this.mapInteger.put(key, mapIntegerItem); return this; @@ -194,7 +194,7 @@ public class AdditionalPropertiesClass { public AdditionalPropertiesClass putMapBooleanItem(String key, Boolean mapBooleanItem) { if (this.mapBoolean == null) { - this.mapBoolean = new HashMap(); + this.mapBoolean = new HashMap<>(); } this.mapBoolean.put(key, mapBooleanItem); return this; @@ -229,7 +229,7 @@ public class AdditionalPropertiesClass { public AdditionalPropertiesClass putMapArrayIntegerItem(String key, List mapArrayIntegerItem) { if (this.mapArrayInteger == null) { - this.mapArrayInteger = new HashMap>(); + this.mapArrayInteger = new HashMap<>(); } this.mapArrayInteger.put(key, mapArrayIntegerItem); return this; @@ -264,7 +264,7 @@ public class AdditionalPropertiesClass { public AdditionalPropertiesClass putMapArrayAnytypeItem(String key, List mapArrayAnytypeItem) { if (this.mapArrayAnytype == null) { - this.mapArrayAnytype = new HashMap>(); + this.mapArrayAnytype = new HashMap<>(); } this.mapArrayAnytype.put(key, mapArrayAnytypeItem); return this; @@ -299,7 +299,7 @@ public class AdditionalPropertiesClass { public AdditionalPropertiesClass putMapMapStringItem(String key, Map mapMapStringItem) { if (this.mapMapString == null) { - this.mapMapString = new HashMap>(); + this.mapMapString = new HashMap<>(); } this.mapMapString.put(key, mapMapStringItem); return this; @@ -334,7 +334,7 @@ public class AdditionalPropertiesClass { public AdditionalPropertiesClass putMapMapAnytypeItem(String key, Map mapMapAnytypeItem) { if (this.mapMapAnytype == null) { - this.mapMapAnytype = new HashMap>(); + this.mapMapAnytype = new HashMap<>(); } this.mapMapAnytype.put(key, mapMapAnytypeItem); return this; diff --git a/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/ArrayOfArrayOfNumberOnly.java b/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/ArrayOfArrayOfNumberOnly.java index e558e02ebe5..50ec3008bd6 100644 --- a/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/ArrayOfArrayOfNumberOnly.java +++ b/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/ArrayOfArrayOfNumberOnly.java @@ -48,7 +48,7 @@ public class ArrayOfArrayOfNumberOnly { public ArrayOfArrayOfNumberOnly addArrayArrayNumberItem(List arrayArrayNumberItem) { if (this.arrayArrayNumber == null) { - this.arrayArrayNumber = new ArrayList>(); + this.arrayArrayNumber = new ArrayList<>(); } this.arrayArrayNumber.add(arrayArrayNumberItem); return this; diff --git a/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/ArrayOfNumberOnly.java b/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/ArrayOfNumberOnly.java index fd5f507f169..e4bd3504968 100644 --- a/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/ArrayOfNumberOnly.java +++ b/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/ArrayOfNumberOnly.java @@ -48,7 +48,7 @@ public class ArrayOfNumberOnly { public ArrayOfNumberOnly addArrayNumberItem(BigDecimal arrayNumberItem) { if (this.arrayNumber == null) { - this.arrayNumber = new ArrayList(); + this.arrayNumber = new ArrayList<>(); } this.arrayNumber.add(arrayNumberItem); return this; diff --git a/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/ArrayTest.java b/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/ArrayTest.java index 281f50c3fb3..e2faf5ed423 100644 --- a/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/ArrayTest.java +++ b/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/ArrayTest.java @@ -56,7 +56,7 @@ public class ArrayTest { public ArrayTest addArrayOfStringItem(String arrayOfStringItem) { if (this.arrayOfString == null) { - this.arrayOfString = new ArrayList(); + this.arrayOfString = new ArrayList<>(); } this.arrayOfString.add(arrayOfStringItem); return this; @@ -91,7 +91,7 @@ public class ArrayTest { public ArrayTest addArrayArrayOfIntegerItem(List arrayArrayOfIntegerItem) { if (this.arrayArrayOfInteger == null) { - this.arrayArrayOfInteger = new ArrayList>(); + this.arrayArrayOfInteger = new ArrayList<>(); } this.arrayArrayOfInteger.add(arrayArrayOfIntegerItem); return this; @@ -126,7 +126,7 @@ public class ArrayTest { public ArrayTest addArrayArrayOfModelItem(List arrayArrayOfModelItem) { if (this.arrayArrayOfModel == null) { - this.arrayArrayOfModel = new ArrayList>(); + this.arrayArrayOfModel = new ArrayList<>(); } this.arrayArrayOfModel.add(arrayArrayOfModelItem); return this; diff --git a/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/EnumArrays.java b/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/EnumArrays.java index 6f8c2056318..7cdb3158948 100644 --- a/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/EnumArrays.java +++ b/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/EnumArrays.java @@ -148,7 +148,7 @@ public class EnumArrays { public EnumArrays addArrayEnumItem(ArrayEnumEnum arrayEnumItem) { if (this.arrayEnum == null) { - this.arrayEnum = new ArrayList(); + this.arrayEnum = new ArrayList<>(); } this.arrayEnum.add(arrayEnumItem); return this; diff --git a/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/FileSchemaTestClass.java b/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/FileSchemaTestClass.java index fdc4c5a0920..69eeeaea732 100644 --- a/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/FileSchemaTestClass.java +++ b/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/FileSchemaTestClass.java @@ -78,7 +78,7 @@ public class FileSchemaTestClass { public FileSchemaTestClass addFilesItem(java.io.File filesItem) { if (this.files == null) { - this.files = new ArrayList(); + this.files = new ArrayList<>(); } this.files.add(filesItem); return this; diff --git a/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/MapTest.java b/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/MapTest.java index 3561bb9ac0c..e795f5b836f 100644 --- a/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/MapTest.java +++ b/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/MapTest.java @@ -95,7 +95,7 @@ public class MapTest { public MapTest putMapMapOfStringItem(String key, Map mapMapOfStringItem) { if (this.mapMapOfString == null) { - this.mapMapOfString = new HashMap>(); + this.mapMapOfString = new HashMap<>(); } this.mapMapOfString.put(key, mapMapOfStringItem); return this; @@ -130,7 +130,7 @@ public class MapTest { public MapTest putMapOfEnumStringItem(String key, InnerEnum mapOfEnumStringItem) { if (this.mapOfEnumString == null) { - this.mapOfEnumString = new HashMap(); + this.mapOfEnumString = new HashMap<>(); } this.mapOfEnumString.put(key, mapOfEnumStringItem); return this; @@ -165,7 +165,7 @@ public class MapTest { public MapTest putDirectMapItem(String key, Boolean directMapItem) { if (this.directMap == null) { - this.directMap = new HashMap(); + this.directMap = new HashMap<>(); } this.directMap.put(key, directMapItem); return this; @@ -200,7 +200,7 @@ public class MapTest { public MapTest putIndirectMapItem(String key, Boolean indirectMapItem) { if (this.indirectMap == null) { - this.indirectMap = new HashMap(); + this.indirectMap = new HashMap<>(); } this.indirectMap.put(key, indirectMapItem); return this; diff --git a/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/MixedPropertiesAndAdditionalPropertiesClass.java index f8973bf9835..b61d9919217 100644 --- a/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/MixedPropertiesAndAdditionalPropertiesClass.java +++ b/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -113,7 +113,7 @@ public class MixedPropertiesAndAdditionalPropertiesClass { public MixedPropertiesAndAdditionalPropertiesClass putMapItem(String key, Animal mapItem) { if (this.map == null) { - this.map = new HashMap(); + this.map = new HashMap<>(); } this.map.put(key, mapItem); return this; diff --git a/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/Pet.java b/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/Pet.java index 3b5363bdd40..8dba5c55885 100644 --- a/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/Pet.java +++ b/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/Pet.java @@ -54,7 +54,7 @@ public class Pet { private String name; public static final String JSON_PROPERTY_PHOTO_URLS = "photoUrls"; - private Set photoUrls = new LinkedHashSet(); + private Set photoUrls = new LinkedHashSet<>(); public static final String JSON_PROPERTY_TAGS = "tags"; private List tags = null; @@ -219,7 +219,7 @@ public class Pet { public Pet addTagsItem(Tag tagsItem) { if (this.tags == null) { - this.tags = new ArrayList(); + this.tags = new ArrayList<>(); } this.tags.add(tagsItem); return this; diff --git a/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/TypeHolderDefault.java b/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/TypeHolderDefault.java index a5086c76768..e918613f558 100644 --- a/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/TypeHolderDefault.java +++ b/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/TypeHolderDefault.java @@ -53,7 +53,7 @@ public class TypeHolderDefault { private Boolean boolItem = true; public static final String JSON_PROPERTY_ARRAY_ITEM = "array_item"; - private List arrayItem = new ArrayList(); + private List arrayItem = new ArrayList<>(); public TypeHolderDefault stringItem(String stringItem) { diff --git a/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/TypeHolderExample.java b/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/TypeHolderExample.java index a2767367b35..d718b404737 100644 --- a/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/TypeHolderExample.java +++ b/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/TypeHolderExample.java @@ -57,7 +57,7 @@ public class TypeHolderExample { private Boolean boolItem; public static final String JSON_PROPERTY_ARRAY_ITEM = "array_item"; - private List arrayItem = new ArrayList(); + private List arrayItem = new ArrayList<>(); public TypeHolderExample stringItem(String stringItem) { diff --git a/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/XmlItem.java b/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/XmlItem.java index 0d54cd8ba26..1090a5110a2 100644 --- a/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/XmlItem.java +++ b/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/XmlItem.java @@ -268,7 +268,7 @@ public class XmlItem { public XmlItem addWrappedArrayItem(Integer wrappedArrayItem) { if (this.wrappedArray == null) { - this.wrappedArray = new ArrayList(); + this.wrappedArray = new ArrayList<>(); } this.wrappedArray.add(wrappedArrayItem); return this; @@ -411,7 +411,7 @@ public class XmlItem { public XmlItem addNameArrayItem(Integer nameArrayItem) { if (this.nameArray == null) { - this.nameArray = new ArrayList(); + this.nameArray = new ArrayList<>(); } this.nameArray.add(nameArrayItem); return this; @@ -446,7 +446,7 @@ public class XmlItem { public XmlItem addNameWrappedArrayItem(Integer nameWrappedArrayItem) { if (this.nameWrappedArray == null) { - this.nameWrappedArray = new ArrayList(); + this.nameWrappedArray = new ArrayList<>(); } this.nameWrappedArray.add(nameWrappedArrayItem); return this; @@ -589,7 +589,7 @@ public class XmlItem { public XmlItem addPrefixArrayItem(Integer prefixArrayItem) { if (this.prefixArray == null) { - this.prefixArray = new ArrayList(); + this.prefixArray = new ArrayList<>(); } this.prefixArray.add(prefixArrayItem); return this; @@ -624,7 +624,7 @@ public class XmlItem { public XmlItem addPrefixWrappedArrayItem(Integer prefixWrappedArrayItem) { if (this.prefixWrappedArray == null) { - this.prefixWrappedArray = new ArrayList(); + this.prefixWrappedArray = new ArrayList<>(); } this.prefixWrappedArray.add(prefixWrappedArrayItem); return this; @@ -767,7 +767,7 @@ public class XmlItem { public XmlItem addNamespaceArrayItem(Integer namespaceArrayItem) { if (this.namespaceArray == null) { - this.namespaceArray = new ArrayList(); + this.namespaceArray = new ArrayList<>(); } this.namespaceArray.add(namespaceArrayItem); return this; @@ -802,7 +802,7 @@ public class XmlItem { public XmlItem addNamespaceWrappedArrayItem(Integer namespaceWrappedArrayItem) { if (this.namespaceWrappedArray == null) { - this.namespaceWrappedArray = new ArrayList(); + this.namespaceWrappedArray = new ArrayList<>(); } this.namespaceWrappedArray.add(namespaceWrappedArrayItem); return this; @@ -945,7 +945,7 @@ public class XmlItem { public XmlItem addPrefixNsArrayItem(Integer prefixNsArrayItem) { if (this.prefixNsArray == null) { - this.prefixNsArray = new ArrayList(); + this.prefixNsArray = new ArrayList<>(); } this.prefixNsArray.add(prefixNsArrayItem); return this; @@ -980,7 +980,7 @@ public class XmlItem { public XmlItem addPrefixNsWrappedArrayItem(Integer prefixNsWrappedArrayItem) { if (this.prefixNsWrappedArray == null) { - this.prefixNsWrappedArray = new ArrayList(); + this.prefixNsWrappedArray = new ArrayList<>(); } this.prefixNsWrappedArray.add(prefixNsWrappedArrayItem); return this; diff --git a/samples/client/petstore/java/resttemplate-withXml/.openapi-generator/VERSION b/samples/client/petstore/java/resttemplate-withXml/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/client/petstore/java/resttemplate-withXml/.openapi-generator/VERSION +++ b/samples/client/petstore/java/resttemplate-withXml/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x 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 11da16b2e48..ae98ba62fdc 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 @@ -36,6 +36,7 @@ import org.springframework.http.converter.json.AbstractJackson2HttpMessageConver import com.fasterxml.jackson.databind.ObjectMapper; import org.openapitools.jackson.nullable.JsonNullableModule; + import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; diff --git a/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/api/AnotherFakeApi.java b/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/api/AnotherFakeApi.java index 6cd06d48e57..dee726fce33 100644 --- a/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/api/AnotherFakeApi.java +++ b/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/api/AnotherFakeApi.java @@ -89,11 +89,11 @@ public class AnotherFakeApi { final String[] contentTypes = { "application/json" }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; - return apiClient.invokeAPI(path, HttpMethod.PATCH, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.PATCH, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } } 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 a4388e7f41d..045664b3bbb 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 @@ -94,12 +94,12 @@ public class FakeApi { final String[] contentTypes = { "application/xml", "application/xml; charset=utf-8", "application/xml; charset=utf-16", "text/xml", "text/xml; charset=utf-8", "text/xml; charset=utf-16" }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; - return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } /** * @@ -136,12 +136,12 @@ public class FakeApi { }; final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); final String[] contentTypes = { }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; - return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } /** * @@ -178,12 +178,12 @@ public class FakeApi { }; final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); final String[] contentTypes = { }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; - return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } /** * @@ -220,12 +220,12 @@ public class FakeApi { }; final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); final String[] contentTypes = { }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; - return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } /** * @@ -262,12 +262,12 @@ public class FakeApi { }; final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); final String[] contentTypes = { }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; - return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } /** * @@ -308,12 +308,12 @@ public class FakeApi { final String[] contentTypes = { "application/json" }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; - return apiClient.invokeAPI(path, HttpMethod.PUT, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.PUT, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } /** * @@ -363,12 +363,12 @@ public class FakeApi { final String[] contentTypes = { "application/json" }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; - return apiClient.invokeAPI(path, HttpMethod.PUT, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.PUT, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } /** * To test \"client\" model @@ -412,12 +412,12 @@ public class FakeApi { final String[] contentTypes = { "application/json" }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; - return apiClient.invokeAPI(path, HttpMethod.PATCH, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.PATCH, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } /** * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 @@ -530,12 +530,12 @@ public class FakeApi { final String[] contentTypes = { "application/x-www-form-urlencoded" }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { "http_basic_test" }; ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; - return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } /** * To test enum parameters @@ -602,12 +602,12 @@ public class FakeApi { final String[] contentTypes = { "application/x-www-form-urlencoded" }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; - return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } /** * Fake endpoint to test group parameters (optional) @@ -676,12 +676,12 @@ public class FakeApi { final String[] localVarAccepts = { }; final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); final String[] contentTypes = { }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; - return apiClient.invokeAPI(path, HttpMethod.DELETE, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.DELETE, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } /** * test inline additionalProperties @@ -722,12 +722,12 @@ public class FakeApi { final String[] contentTypes = { "application/json" }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; - return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } /** * test json serialization of form data @@ -780,12 +780,12 @@ public class FakeApi { final String[] contentTypes = { "application/x-www-form-urlencoded" }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; - return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } /** * @@ -858,11 +858,11 @@ public class FakeApi { final String[] localVarAccepts = { }; final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); final String[] contentTypes = { }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; - return apiClient.invokeAPI(path, HttpMethod.PUT, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.PUT, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } } diff --git a/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/api/FakeClassnameTags123Api.java b/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/api/FakeClassnameTags123Api.java index 1aaa79e9b97..26ad7b23546 100644 --- a/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/api/FakeClassnameTags123Api.java +++ b/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/api/FakeClassnameTags123Api.java @@ -89,11 +89,11 @@ public class FakeClassnameTags123Api { final String[] contentTypes = { "application/json" }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { "api_key_query" }; ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; - return apiClient.invokeAPI(path, HttpMethod.PATCH, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.PATCH, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } } 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 6e44289f45e..b5ff30e3cf2 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 @@ -91,12 +91,12 @@ public class PetApi { final String[] contentTypes = { "application/json", "application/xml" }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { "petstore_auth" }; ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; - return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } /** * Deletes a pet @@ -145,12 +145,12 @@ public class PetApi { final String[] localVarAccepts = { }; final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); final String[] contentTypes = { }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { "petstore_auth" }; ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; - return apiClient.invokeAPI(path, HttpMethod.DELETE, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.DELETE, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } /** * Finds Pets by status @@ -196,12 +196,12 @@ public class PetApi { }; final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); final String[] contentTypes = { }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { "petstore_auth" }; ParameterizedTypeReference> returnType = new ParameterizedTypeReference>() {}; - return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } /** * Finds Pets by tags @@ -249,12 +249,12 @@ public class PetApi { }; final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); final String[] contentTypes = { }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { "petstore_auth" }; ParameterizedTypeReference> returnType = new ParameterizedTypeReference>() {}; - return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } /** * Find pet by ID @@ -303,12 +303,12 @@ public class PetApi { }; final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); final String[] contentTypes = { }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { "api_key" }; ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; - return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } /** * Update an existing pet @@ -355,12 +355,12 @@ public class PetApi { final String[] contentTypes = { "application/json", "application/xml" }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { "petstore_auth" }; ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; - return apiClient.invokeAPI(path, HttpMethod.PUT, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.PUT, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } /** * Updates a pet in the store with form data @@ -413,12 +413,12 @@ public class PetApi { final String[] contentTypes = { "application/x-www-form-urlencoded" }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { "petstore_auth" }; ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; - return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } /** * uploads an image @@ -474,12 +474,12 @@ public class PetApi { final String[] contentTypes = { "multipart/form-data" }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { "petstore_auth" }; ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; - return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } /** * uploads an image (required) @@ -540,11 +540,11 @@ public class PetApi { final String[] contentTypes = { "multipart/form-data" }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { "petstore_auth" }; ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; - return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } } diff --git a/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/api/StoreApi.java b/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/api/StoreApi.java index 1f1cbc751ef..63aa265f38e 100644 --- a/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/api/StoreApi.java +++ b/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/api/StoreApi.java @@ -89,12 +89,12 @@ public class StoreApi { final String[] localVarAccepts = { }; final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); final String[] contentTypes = { }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; - return apiClient.invokeAPI(path, HttpMethod.DELETE, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.DELETE, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } /** * Returns pet inventories by status @@ -129,12 +129,12 @@ public class StoreApi { }; final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); final String[] contentTypes = { }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { "api_key" }; ParameterizedTypeReference> returnType = new ParameterizedTypeReference>() {}; - return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } /** * Find purchase order by ID @@ -183,12 +183,12 @@ public class StoreApi { }; final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); final String[] contentTypes = { }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; - return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } /** * Place an order for a pet @@ -232,11 +232,11 @@ public class StoreApi { }; final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); final String[] contentTypes = { }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; - return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } } 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 35f6e660963..46be8cbbd61 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 @@ -84,12 +84,12 @@ public class UserApi { final String[] localVarAccepts = { }; final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); final String[] contentTypes = { }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; - return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } /** * Creates list of users with given input array @@ -128,12 +128,12 @@ public class UserApi { final String[] localVarAccepts = { }; final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); final String[] contentTypes = { }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; - return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } /** * Creates list of users with given input array @@ -172,12 +172,12 @@ public class UserApi { final String[] localVarAccepts = { }; final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); final String[] contentTypes = { }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; - return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } /** * Delete user @@ -221,12 +221,12 @@ public class UserApi { final String[] localVarAccepts = { }; final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); final String[] contentTypes = { }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; - return apiClient.invokeAPI(path, HttpMethod.DELETE, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.DELETE, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } /** * Get user by user name @@ -275,12 +275,12 @@ public class UserApi { }; final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); final String[] contentTypes = { }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; - return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } /** * Logs user into the system @@ -334,12 +334,12 @@ public class UserApi { }; final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); final String[] contentTypes = { }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; - return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } /** * Logs out current logged in user session @@ -371,12 +371,12 @@ public class UserApi { final String[] localVarAccepts = { }; final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); final String[] contentTypes = { }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; - return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } /** * Updated user @@ -427,11 +427,11 @@ public class UserApi { final String[] localVarAccepts = { }; final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); final String[] contentTypes = { }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; - return apiClient.invokeAPI(path, HttpMethod.PUT, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.PUT, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } } diff --git a/samples/client/petstore/java/resttemplate/.openapi-generator/VERSION b/samples/client/petstore/java/resttemplate/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/client/petstore/java/resttemplate/.openapi-generator/VERSION +++ b/samples/client/petstore/java/resttemplate/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x 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 11c1b834935..ff33cd2248f 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 @@ -31,6 +31,7 @@ import org.springframework.http.converter.json.AbstractJackson2HttpMessageConver import com.fasterxml.jackson.databind.ObjectMapper; import org.openapitools.jackson.nullable.JsonNullableModule; + import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; diff --git a/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/api/AnotherFakeApi.java b/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/api/AnotherFakeApi.java index 6cd06d48e57..dee726fce33 100644 --- a/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/api/AnotherFakeApi.java +++ b/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/api/AnotherFakeApi.java @@ -89,11 +89,11 @@ public class AnotherFakeApi { final String[] contentTypes = { "application/json" }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; - return apiClient.invokeAPI(path, HttpMethod.PATCH, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.PATCH, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } } 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 a4388e7f41d..045664b3bbb 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 @@ -94,12 +94,12 @@ public class FakeApi { final String[] contentTypes = { "application/xml", "application/xml; charset=utf-8", "application/xml; charset=utf-16", "text/xml", "text/xml; charset=utf-8", "text/xml; charset=utf-16" }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; - return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } /** * @@ -136,12 +136,12 @@ public class FakeApi { }; final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); final String[] contentTypes = { }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; - return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } /** * @@ -178,12 +178,12 @@ public class FakeApi { }; final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); final String[] contentTypes = { }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; - return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } /** * @@ -220,12 +220,12 @@ public class FakeApi { }; final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); final String[] contentTypes = { }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; - return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } /** * @@ -262,12 +262,12 @@ public class FakeApi { }; final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); final String[] contentTypes = { }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; - return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } /** * @@ -308,12 +308,12 @@ public class FakeApi { final String[] contentTypes = { "application/json" }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; - return apiClient.invokeAPI(path, HttpMethod.PUT, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.PUT, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } /** * @@ -363,12 +363,12 @@ public class FakeApi { final String[] contentTypes = { "application/json" }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; - return apiClient.invokeAPI(path, HttpMethod.PUT, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.PUT, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } /** * To test \"client\" model @@ -412,12 +412,12 @@ public class FakeApi { final String[] contentTypes = { "application/json" }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; - return apiClient.invokeAPI(path, HttpMethod.PATCH, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.PATCH, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } /** * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 @@ -530,12 +530,12 @@ public class FakeApi { final String[] contentTypes = { "application/x-www-form-urlencoded" }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { "http_basic_test" }; ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; - return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } /** * To test enum parameters @@ -602,12 +602,12 @@ public class FakeApi { final String[] contentTypes = { "application/x-www-form-urlencoded" }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; - return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } /** * Fake endpoint to test group parameters (optional) @@ -676,12 +676,12 @@ public class FakeApi { final String[] localVarAccepts = { }; final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); final String[] contentTypes = { }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; - return apiClient.invokeAPI(path, HttpMethod.DELETE, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.DELETE, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } /** * test inline additionalProperties @@ -722,12 +722,12 @@ public class FakeApi { final String[] contentTypes = { "application/json" }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; - return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } /** * test json serialization of form data @@ -780,12 +780,12 @@ public class FakeApi { final String[] contentTypes = { "application/x-www-form-urlencoded" }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; - return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } /** * @@ -858,11 +858,11 @@ public class FakeApi { final String[] localVarAccepts = { }; final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); final String[] contentTypes = { }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; - return apiClient.invokeAPI(path, HttpMethod.PUT, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.PUT, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } } diff --git a/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/api/FakeClassnameTags123Api.java b/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/api/FakeClassnameTags123Api.java index 1aaa79e9b97..26ad7b23546 100644 --- a/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/api/FakeClassnameTags123Api.java +++ b/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/api/FakeClassnameTags123Api.java @@ -89,11 +89,11 @@ public class FakeClassnameTags123Api { final String[] contentTypes = { "application/json" }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { "api_key_query" }; ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; - return apiClient.invokeAPI(path, HttpMethod.PATCH, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.PATCH, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } } 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 6e44289f45e..b5ff30e3cf2 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 @@ -91,12 +91,12 @@ public class PetApi { final String[] contentTypes = { "application/json", "application/xml" }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { "petstore_auth" }; ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; - return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } /** * Deletes a pet @@ -145,12 +145,12 @@ public class PetApi { final String[] localVarAccepts = { }; final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); final String[] contentTypes = { }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { "petstore_auth" }; ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; - return apiClient.invokeAPI(path, HttpMethod.DELETE, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.DELETE, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } /** * Finds Pets by status @@ -196,12 +196,12 @@ public class PetApi { }; final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); final String[] contentTypes = { }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { "petstore_auth" }; ParameterizedTypeReference> returnType = new ParameterizedTypeReference>() {}; - return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } /** * Finds Pets by tags @@ -249,12 +249,12 @@ public class PetApi { }; final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); final String[] contentTypes = { }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { "petstore_auth" }; ParameterizedTypeReference> returnType = new ParameterizedTypeReference>() {}; - return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } /** * Find pet by ID @@ -303,12 +303,12 @@ public class PetApi { }; final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); final String[] contentTypes = { }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { "api_key" }; ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; - return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } /** * Update an existing pet @@ -355,12 +355,12 @@ public class PetApi { final String[] contentTypes = { "application/json", "application/xml" }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { "petstore_auth" }; ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; - return apiClient.invokeAPI(path, HttpMethod.PUT, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.PUT, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } /** * Updates a pet in the store with form data @@ -413,12 +413,12 @@ public class PetApi { final String[] contentTypes = { "application/x-www-form-urlencoded" }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { "petstore_auth" }; ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; - return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } /** * uploads an image @@ -474,12 +474,12 @@ public class PetApi { final String[] contentTypes = { "multipart/form-data" }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { "petstore_auth" }; ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; - return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } /** * uploads an image (required) @@ -540,11 +540,11 @@ public class PetApi { final String[] contentTypes = { "multipart/form-data" }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { "petstore_auth" }; ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; - return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } } diff --git a/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/api/StoreApi.java b/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/api/StoreApi.java index 1f1cbc751ef..63aa265f38e 100644 --- a/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/api/StoreApi.java +++ b/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/api/StoreApi.java @@ -89,12 +89,12 @@ public class StoreApi { final String[] localVarAccepts = { }; final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); final String[] contentTypes = { }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; - return apiClient.invokeAPI(path, HttpMethod.DELETE, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.DELETE, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } /** * Returns pet inventories by status @@ -129,12 +129,12 @@ public class StoreApi { }; final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); final String[] contentTypes = { }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { "api_key" }; ParameterizedTypeReference> returnType = new ParameterizedTypeReference>() {}; - return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } /** * Find purchase order by ID @@ -183,12 +183,12 @@ public class StoreApi { }; final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); final String[] contentTypes = { }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; - return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } /** * Place an order for a pet @@ -232,11 +232,11 @@ public class StoreApi { }; final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); final String[] contentTypes = { }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; - return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } } 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 35f6e660963..46be8cbbd61 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 @@ -84,12 +84,12 @@ public class UserApi { final String[] localVarAccepts = { }; final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); final String[] contentTypes = { }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; - return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } /** * Creates list of users with given input array @@ -128,12 +128,12 @@ public class UserApi { final String[] localVarAccepts = { }; final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); final String[] contentTypes = { }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; - return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } /** * Creates list of users with given input array @@ -172,12 +172,12 @@ public class UserApi { final String[] localVarAccepts = { }; final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); final String[] contentTypes = { }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; - return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } /** * Delete user @@ -221,12 +221,12 @@ public class UserApi { final String[] localVarAccepts = { }; final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); final String[] contentTypes = { }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; - return apiClient.invokeAPI(path, HttpMethod.DELETE, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.DELETE, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } /** * Get user by user name @@ -275,12 +275,12 @@ public class UserApi { }; final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); final String[] contentTypes = { }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; - return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } /** * Logs user into the system @@ -334,12 +334,12 @@ public class UserApi { }; final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); final String[] contentTypes = { }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; - return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } /** * Logs out current logged in user session @@ -371,12 +371,12 @@ public class UserApi { final String[] localVarAccepts = { }; final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); final String[] contentTypes = { }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; - return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } /** * Updated user @@ -427,11 +427,11 @@ public class UserApi { final String[] localVarAccepts = { }; final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); final String[] contentTypes = { }; - final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); + final MediaType localVarContentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; ParameterizedTypeReference returnType = new ParameterizedTypeReference() {}; - return apiClient.invokeAPI(path, HttpMethod.PUT, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, HttpMethod.PUT, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, authNames, returnType); } } diff --git a/samples/client/petstore/java/retrofit2-play26/.openapi-generator/VERSION b/samples/client/petstore/java/retrofit2-play26/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/client/petstore/java/retrofit2-play26/.openapi-generator/VERSION +++ b/samples/client/petstore/java/retrofit2-play26/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/client/petstore/java/retrofit2/.openapi-generator/VERSION b/samples/client/petstore/java/retrofit2/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/client/petstore/java/retrofit2/.openapi-generator/VERSION +++ b/samples/client/petstore/java/retrofit2/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/client/petstore/java/retrofit2rx2/.openapi-generator/VERSION b/samples/client/petstore/java/retrofit2rx2/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/client/petstore/java/retrofit2rx2/.openapi-generator/VERSION +++ b/samples/client/petstore/java/retrofit2rx2/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/client/petstore/java/retrofit2rx3/.openapi-generator/VERSION b/samples/client/petstore/java/retrofit2rx3/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/client/petstore/java/retrofit2rx3/.openapi-generator/VERSION +++ b/samples/client/petstore/java/retrofit2rx3/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x 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 5f68295fc19..e8415097f3a 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,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/client/petstore/java/vertx/.openapi-generator/VERSION b/samples/client/petstore/java/vertx/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/client/petstore/java/vertx/.openapi-generator/VERSION +++ b/samples/client/petstore/java/vertx/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/client/petstore/java/webclient/.openapi-generator/VERSION b/samples/client/petstore/java/webclient/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/client/petstore/java/webclient/.openapi-generator/VERSION +++ b/samples/client/petstore/java/webclient/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x 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 b8a53e2f947..ecf56b68430 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 @@ -29,6 +29,7 @@ import org.springframework.http.client.reactive.ClientHttpRequest; import org.springframework.web.client.RestClientException; import org.springframework.web.util.UriComponentsBuilder; import org.springframework.web.reactive.function.client.WebClient; +import org.springframework.web.reactive.function.client.WebClient.ResponseSpec; import org.springframework.web.reactive.function.client.ClientResponse; import org.springframework.web.reactive.function.BodyInserter; import org.springframework.web.reactive.function.BodyInserters; @@ -497,6 +498,15 @@ public class ApiClient extends JavaTimeFormatter { 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; @@ -511,7 +521,7 @@ public class ApiClient extends JavaTimeFormatter { } for (String accept : accepts) { MediaType mediaType = MediaType.parseMediaType(accept); - if (isJsonMime(mediaType)) { + if (isJsonMime(mediaType) && !isProblemJsonMime(accept)) { return Collections.singletonList(mediaType); } } @@ -580,31 +590,9 @@ public class ApiClient extends JavaTimeFormatter { * @param returnType The return type into which to deserialize the response * @return The response body in chosen type */ - public Mono 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 { + public ResponseSpec 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 { final WebClient.RequestBodySpec requestBuilder = prepareRequest(path, method, pathParams, queryParams, body, headerParams, cookieParams, formParams, accept, contentType, authNames); - return requestBuilder.retrieve().bodyToMono(returnType); - } - - /** - * 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 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 chosen type - */ - public Flux invokeFluxAPI(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 { - final WebClient.RequestBodySpec requestBuilder = prepareRequest(path, method, pathParams, queryParams, body, headerParams, cookieParams, formParams, accept, contentType, authNames); - return requestBuilder.retrieve().bodyToFlux(returnType); + return requestBuilder.retrieve(); } private WebClient.RequestBodySpec prepareRequest(String path, HttpMethod method, Map pathParams, MultiValueMap queryParams, Object body, HttpHeaders headerParams, MultiValueMap cookieParams, MultiValueMap formParams, List accept, MediaType contentType, String[] authNames) { diff --git a/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/api/AnotherFakeApi.java b/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/api/AnotherFakeApi.java index edc44d99937..20e60e88ad2 100644 --- a/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/api/AnotherFakeApi.java +++ b/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/api/AnotherFakeApi.java @@ -15,12 +15,14 @@ import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import org.springframework.web.util.UriComponentsBuilder; import org.springframework.core.ParameterizedTypeReference; +import org.springframework.web.reactive.function.client.WebClient.ResponseSpec; import org.springframework.web.reactive.function.client.WebClientResponseException; 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; import reactor.core.publisher.Mono; import reactor.core.publisher.Flux; @@ -53,7 +55,7 @@ public class AnotherFakeApi { * @return Client * @throws WebClientResponseException if an error occurs while attempting to invoke the API */ - public Mono call123testSpecialTags(Client body) throws WebClientResponseException { + private ResponseSpec call123testSpecialTagsRequestCreation(Client body) throws WebClientResponseException { Object postBody = body; // verify the required parameter 'body' is set if (body == null) { @@ -81,4 +83,22 @@ public class AnotherFakeApi { ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; return apiClient.invokeAPI("/another-fake/dummy", HttpMethod.PATCH, pathParams, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); } + + /** + * To test special tags + * To test special tags and operation ID starting with number + *

    200 - successful operation + * @param body client model + * @return Client + * @throws WebClientResponseException if an error occurs while attempting to invoke the API + */ + public Mono call123testSpecialTags(Client body) throws WebClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; + return call123testSpecialTagsRequestCreation(body).bodyToMono(localVarReturnType); + } + + public Mono> call123testSpecialTagsWithHttpInfo(Client body) throws WebClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; + return call123testSpecialTagsRequestCreation(body).toEntity(localVarReturnType); + } } 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 95108f72e5e..aea0af298fa 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 @@ -23,12 +23,14 @@ import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import org.springframework.web.util.UriComponentsBuilder; import org.springframework.core.ParameterizedTypeReference; +import org.springframework.web.reactive.function.client.WebClient.ResponseSpec; import org.springframework.web.reactive.function.client.WebClientResponseException; 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; import reactor.core.publisher.Mono; import reactor.core.publisher.Flux; @@ -60,7 +62,7 @@ public class FakeApi { * @param xmlItem XmlItem Body * @throws WebClientResponseException if an error occurs while attempting to invoke the API */ - public Mono createXmlItem(XmlItem xmlItem) throws WebClientResponseException { + private ResponseSpec createXmlItemRequestCreation(XmlItem xmlItem) throws WebClientResponseException { Object postBody = xmlItem; // verify the required parameter 'xmlItem' is set if (xmlItem == null) { @@ -86,6 +88,23 @@ public class FakeApi { ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; return apiClient.invokeAPI("/fake/create_xml_item", HttpMethod.POST, pathParams, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); } + + /** + * creates an XmlItem + * this route creates an XmlItem + *

    200 - successful operation + * @param xmlItem XmlItem Body + * @throws WebClientResponseException if an error occurs while attempting to invoke the API + */ + public Mono createXmlItem(XmlItem xmlItem) throws WebClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; + return createXmlItemRequestCreation(xmlItem).bodyToMono(localVarReturnType); + } + + public Mono> createXmlItemWithHttpInfo(XmlItem xmlItem) throws WebClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; + return createXmlItemRequestCreation(xmlItem).toEntity(localVarReturnType); + } /** * * Test serialization of outer boolean types @@ -94,7 +113,7 @@ public class FakeApi { * @return Boolean * @throws WebClientResponseException if an error occurs while attempting to invoke the API */ - public Mono fakeOuterBooleanSerialize(Boolean body) throws WebClientResponseException { + private ResponseSpec fakeOuterBooleanSerializeRequestCreation(Boolean body) throws WebClientResponseException { Object postBody = body; // create path and map variables final Map pathParams = new HashMap(); @@ -116,6 +135,24 @@ public class FakeApi { ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; return apiClient.invokeAPI("/fake/outer/boolean", HttpMethod.POST, pathParams, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); } + + /** + * + * Test serialization of outer boolean types + *

    200 - Output boolean + * @param body Input boolean as post body + * @return Boolean + * @throws WebClientResponseException if an error occurs while attempting to invoke the API + */ + public Mono fakeOuterBooleanSerialize(Boolean body) throws WebClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; + return fakeOuterBooleanSerializeRequestCreation(body).bodyToMono(localVarReturnType); + } + + public Mono> fakeOuterBooleanSerializeWithHttpInfo(Boolean body) throws WebClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; + return fakeOuterBooleanSerializeRequestCreation(body).toEntity(localVarReturnType); + } /** * * Test serialization of object with outer number type @@ -124,7 +161,7 @@ public class FakeApi { * @return OuterComposite * @throws WebClientResponseException if an error occurs while attempting to invoke the API */ - public Mono fakeOuterCompositeSerialize(OuterComposite body) throws WebClientResponseException { + private ResponseSpec fakeOuterCompositeSerializeRequestCreation(OuterComposite body) throws WebClientResponseException { Object postBody = body; // create path and map variables final Map pathParams = new HashMap(); @@ -146,6 +183,24 @@ public class FakeApi { ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; return apiClient.invokeAPI("/fake/outer/composite", HttpMethod.POST, pathParams, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); } + + /** + * + * Test serialization of object with outer number type + *

    200 - Output composite + * @param body Input composite as post body + * @return OuterComposite + * @throws WebClientResponseException if an error occurs while attempting to invoke the API + */ + public Mono fakeOuterCompositeSerialize(OuterComposite body) throws WebClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; + return fakeOuterCompositeSerializeRequestCreation(body).bodyToMono(localVarReturnType); + } + + public Mono> fakeOuterCompositeSerializeWithHttpInfo(OuterComposite body) throws WebClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; + return fakeOuterCompositeSerializeRequestCreation(body).toEntity(localVarReturnType); + } /** * * Test serialization of outer number types @@ -154,7 +209,7 @@ public class FakeApi { * @return BigDecimal * @throws WebClientResponseException if an error occurs while attempting to invoke the API */ - public Mono fakeOuterNumberSerialize(BigDecimal body) throws WebClientResponseException { + private ResponseSpec fakeOuterNumberSerializeRequestCreation(BigDecimal body) throws WebClientResponseException { Object postBody = body; // create path and map variables final Map pathParams = new HashMap(); @@ -176,6 +231,24 @@ public class FakeApi { ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; return apiClient.invokeAPI("/fake/outer/number", HttpMethod.POST, pathParams, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); } + + /** + * + * Test serialization of outer number types + *

    200 - Output number + * @param body Input number as post body + * @return BigDecimal + * @throws WebClientResponseException if an error occurs while attempting to invoke the API + */ + public Mono fakeOuterNumberSerialize(BigDecimal body) throws WebClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; + return fakeOuterNumberSerializeRequestCreation(body).bodyToMono(localVarReturnType); + } + + public Mono> fakeOuterNumberSerializeWithHttpInfo(BigDecimal body) throws WebClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; + return fakeOuterNumberSerializeRequestCreation(body).toEntity(localVarReturnType); + } /** * * Test serialization of outer string types @@ -184,7 +257,7 @@ public class FakeApi { * @return String * @throws WebClientResponseException if an error occurs while attempting to invoke the API */ - public Mono fakeOuterStringSerialize(String body) throws WebClientResponseException { + private ResponseSpec fakeOuterStringSerializeRequestCreation(String body) throws WebClientResponseException { Object postBody = body; // create path and map variables final Map pathParams = new HashMap(); @@ -206,6 +279,24 @@ public class FakeApi { ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; return apiClient.invokeAPI("/fake/outer/string", HttpMethod.POST, pathParams, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); } + + /** + * + * Test serialization of outer string types + *

    200 - Output string + * @param body Input string as post body + * @return String + * @throws WebClientResponseException if an error occurs while attempting to invoke the API + */ + public Mono fakeOuterStringSerialize(String body) throws WebClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; + return fakeOuterStringSerializeRequestCreation(body).bodyToMono(localVarReturnType); + } + + public Mono> fakeOuterStringSerializeWithHttpInfo(String body) throws WebClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; + return fakeOuterStringSerializeRequestCreation(body).toEntity(localVarReturnType); + } /** * * For this test, the body for this request much reference a schema named `File`. @@ -213,7 +304,7 @@ public class FakeApi { * @param body The body parameter * @throws WebClientResponseException if an error occurs while attempting to invoke the API */ - public Mono testBodyWithFileSchema(FileSchemaTestClass body) throws WebClientResponseException { + private ResponseSpec testBodyWithFileSchemaRequestCreation(FileSchemaTestClass body) throws WebClientResponseException { Object postBody = body; // verify the required parameter 'body' is set if (body == null) { @@ -239,6 +330,23 @@ public class FakeApi { ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; return apiClient.invokeAPI("/fake/body-with-file-schema", HttpMethod.PUT, pathParams, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); } + + /** + * + * For this test, the body for this request much reference a schema named `File`. + *

    200 - Success + * @param body The body parameter + * @throws WebClientResponseException if an error occurs while attempting to invoke the API + */ + public Mono testBodyWithFileSchema(FileSchemaTestClass body) throws WebClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; + return testBodyWithFileSchemaRequestCreation(body).bodyToMono(localVarReturnType); + } + + public Mono> testBodyWithFileSchemaWithHttpInfo(FileSchemaTestClass body) throws WebClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; + return testBodyWithFileSchemaRequestCreation(body).toEntity(localVarReturnType); + } /** * * @@ -247,7 +355,7 @@ public class FakeApi { * @param body The body parameter * @throws WebClientResponseException if an error occurs while attempting to invoke the API */ - public Mono testBodyWithQueryParams(String query, User body) throws WebClientResponseException { + private ResponseSpec testBodyWithQueryParamsRequestCreation(String query, User body) throws WebClientResponseException { Object postBody = body; // verify the required parameter 'query' is set if (query == null) { @@ -279,6 +387,24 @@ public class FakeApi { ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; return apiClient.invokeAPI("/fake/body-with-query-params", HttpMethod.PUT, pathParams, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); } + + /** + * + * + *

    200 - Success + * @param query The query parameter + * @param body The body parameter + * @throws WebClientResponseException if an error occurs while attempting to invoke the API + */ + public Mono testBodyWithQueryParams(String query, User body) throws WebClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; + return testBodyWithQueryParamsRequestCreation(query, body).bodyToMono(localVarReturnType); + } + + public Mono> testBodyWithQueryParamsWithHttpInfo(String query, User body) throws WebClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; + return testBodyWithQueryParamsRequestCreation(query, body).toEntity(localVarReturnType); + } /** * To test \"client\" model * To test \"client\" model @@ -287,7 +413,7 @@ public class FakeApi { * @return Client * @throws WebClientResponseException if an error occurs while attempting to invoke the API */ - public Mono testClientModel(Client body) throws WebClientResponseException { + private ResponseSpec testClientModelRequestCreation(Client body) throws WebClientResponseException { Object postBody = body; // verify the required parameter 'body' is set if (body == null) { @@ -315,6 +441,24 @@ public class FakeApi { ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; return apiClient.invokeAPI("/fake", HttpMethod.PATCH, pathParams, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); } + + /** + * To test \"client\" model + * To test \"client\" model + *

    200 - successful operation + * @param body client model + * @return Client + * @throws WebClientResponseException if an error occurs while attempting to invoke the API + */ + public Mono testClientModel(Client body) throws WebClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; + return testClientModelRequestCreation(body).bodyToMono(localVarReturnType); + } + + public Mono> testClientModelWithHttpInfo(Client body) throws WebClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; + return testClientModelRequestCreation(body).toEntity(localVarReturnType); + } /** * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 @@ -336,7 +480,7 @@ public class FakeApi { * @param paramCallback None * @throws WebClientResponseException if an error occurs while attempting to invoke the API */ - public Mono testEndpointParameters(BigDecimal number, Double _double, String patternWithoutDelimiter, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, String string, File binary, LocalDate date, OffsetDateTime dateTime, String password, String paramCallback) throws WebClientResponseException { + private ResponseSpec testEndpointParametersRequestCreation(BigDecimal number, Double _double, String patternWithoutDelimiter, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, String string, File binary, LocalDate date, OffsetDateTime dateTime, String password, String paramCallback) throws WebClientResponseException { Object postBody = null; // verify the required parameter 'number' is set if (number == null) { @@ -403,6 +547,37 @@ public class FakeApi { ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; return apiClient.invokeAPI("/fake", HttpMethod.POST, pathParams, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); } + + /** + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + *

    400 - Invalid username supplied + *

    404 - User not found + * @param number None + * @param _double None + * @param patternWithoutDelimiter None + * @param _byte None + * @param integer None + * @param int32 None + * @param int64 None + * @param _float None + * @param string None + * @param binary None + * @param date None + * @param dateTime None + * @param password None + * @param paramCallback None + * @throws WebClientResponseException if an error occurs while attempting to invoke the API + */ + public Mono testEndpointParameters(BigDecimal number, Double _double, String patternWithoutDelimiter, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, String string, File binary, LocalDate date, OffsetDateTime dateTime, String password, String paramCallback) throws WebClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; + return testEndpointParametersRequestCreation(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password, paramCallback).bodyToMono(localVarReturnType); + } + + public Mono> testEndpointParametersWithHttpInfo(BigDecimal number, Double _double, String patternWithoutDelimiter, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, String string, File binary, LocalDate date, OffsetDateTime dateTime, String password, String paramCallback) throws WebClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; + return testEndpointParametersRequestCreation(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password, paramCallback).toEntity(localVarReturnType); + } /** * To test enum parameters * To test enum parameters @@ -418,7 +593,7 @@ public class FakeApi { * @param enumFormString Form parameter enum test (string) * @throws WebClientResponseException if an error occurs while attempting to invoke the API */ - public Mono testEnumParameters(List enumHeaderStringArray, String enumHeaderString, List enumQueryStringArray, String enumQueryString, Integer enumQueryInteger, Double enumQueryDouble, List enumFormStringArray, String enumFormString) throws WebClientResponseException { + private ResponseSpec testEnumParametersRequestCreation(List enumHeaderStringArray, String enumHeaderString, List enumQueryStringArray, String enumQueryString, Integer enumQueryInteger, Double enumQueryDouble, List enumFormStringArray, String enumFormString) throws WebClientResponseException { Object postBody = null; // create path and map variables final Map pathParams = new HashMap(); @@ -454,6 +629,31 @@ public class FakeApi { ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; return apiClient.invokeAPI("/fake", HttpMethod.GET, pathParams, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); } + + /** + * To test enum parameters + * To test enum parameters + *

    400 - Invalid request + *

    404 - Not found + * @param enumHeaderStringArray Header parameter enum test (string array) + * @param enumHeaderString Header parameter enum test (string) + * @param enumQueryStringArray Query parameter enum test (string array) + * @param enumQueryString Query parameter enum test (string) + * @param enumQueryInteger Query parameter enum test (double) + * @param enumQueryDouble Query parameter enum test (double) + * @param enumFormStringArray Form parameter enum test (string array) + * @param enumFormString Form parameter enum test (string) + * @throws WebClientResponseException if an error occurs while attempting to invoke the API + */ + public Mono testEnumParameters(List enumHeaderStringArray, String enumHeaderString, List enumQueryStringArray, String enumQueryString, Integer enumQueryInteger, Double enumQueryDouble, List enumFormStringArray, String enumFormString) throws WebClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; + return testEnumParametersRequestCreation(enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble, enumFormStringArray, enumFormString).bodyToMono(localVarReturnType); + } + + public Mono> testEnumParametersWithHttpInfo(List enumHeaderStringArray, String enumHeaderString, List enumQueryStringArray, String enumQueryString, Integer enumQueryInteger, Double enumQueryDouble, List enumFormStringArray, String enumFormString) throws WebClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; + return testEnumParametersRequestCreation(enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble, enumFormStringArray, enumFormString).toEntity(localVarReturnType); + } /** * Fake endpoint to test group parameters (optional) * Fake endpoint to test group parameters (optional) @@ -466,7 +666,7 @@ public class FakeApi { * @param int64Group Integer in group parameters * @throws WebClientResponseException if an error occurs while attempting to invoke the API */ - public Mono testGroupParameters(Integer requiredStringGroup, Boolean requiredBooleanGroup, Long requiredInt64Group, Integer stringGroup, Boolean booleanGroup, Long int64Group) throws WebClientResponseException { + private ResponseSpec testGroupParametersRequestCreation(Integer requiredStringGroup, Boolean requiredBooleanGroup, Long requiredInt64Group, Integer stringGroup, Boolean booleanGroup, Long int64Group) throws WebClientResponseException { Object postBody = null; // verify the required parameter 'requiredStringGroup' is set if (requiredStringGroup == null) { @@ -507,6 +707,28 @@ public class FakeApi { ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; return apiClient.invokeAPI("/fake", HttpMethod.DELETE, pathParams, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); } + + /** + * Fake endpoint to test group parameters (optional) + * Fake endpoint to test group parameters (optional) + *

    400 - Someting wrong + * @param requiredStringGroup Required String in group parameters + * @param requiredBooleanGroup Required Boolean in group parameters + * @param requiredInt64Group Required Integer in group parameters + * @param stringGroup String in group parameters + * @param booleanGroup Boolean in group parameters + * @param int64Group Integer in group parameters + * @throws WebClientResponseException if an error occurs while attempting to invoke the API + */ + public Mono testGroupParameters(Integer requiredStringGroup, Boolean requiredBooleanGroup, Long requiredInt64Group, Integer stringGroup, Boolean booleanGroup, Long int64Group) throws WebClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; + return testGroupParametersRequestCreation(requiredStringGroup, requiredBooleanGroup, requiredInt64Group, stringGroup, booleanGroup, int64Group).bodyToMono(localVarReturnType); + } + + public Mono> testGroupParametersWithHttpInfo(Integer requiredStringGroup, Boolean requiredBooleanGroup, Long requiredInt64Group, Integer stringGroup, Boolean booleanGroup, Long int64Group) throws WebClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; + return testGroupParametersRequestCreation(requiredStringGroup, requiredBooleanGroup, requiredInt64Group, stringGroup, booleanGroup, int64Group).toEntity(localVarReturnType); + } /** * test inline additionalProperties * @@ -514,7 +736,7 @@ public class FakeApi { * @param param request body * @throws WebClientResponseException if an error occurs while attempting to invoke the API */ - public Mono testInlineAdditionalProperties(Map param) throws WebClientResponseException { + private ResponseSpec testInlineAdditionalPropertiesRequestCreation(Map param) throws WebClientResponseException { Object postBody = param; // verify the required parameter 'param' is set if (param == null) { @@ -540,6 +762,23 @@ public class FakeApi { ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; return apiClient.invokeAPI("/fake/inline-additionalProperties", HttpMethod.POST, pathParams, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); } + + /** + * test inline additionalProperties + * + *

    200 - successful operation + * @param param request body + * @throws WebClientResponseException if an error occurs while attempting to invoke the API + */ + public Mono testInlineAdditionalProperties(Map param) throws WebClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; + return testInlineAdditionalPropertiesRequestCreation(param).bodyToMono(localVarReturnType); + } + + public Mono> testInlineAdditionalPropertiesWithHttpInfo(Map param) throws WebClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; + return testInlineAdditionalPropertiesRequestCreation(param).toEntity(localVarReturnType); + } /** * test json serialization of form data * @@ -548,7 +787,7 @@ public class FakeApi { * @param param2 field2 * @throws WebClientResponseException if an error occurs while attempting to invoke the API */ - public Mono testJsonFormData(String param, String param2) throws WebClientResponseException { + private ResponseSpec testJsonFormDataRequestCreation(String param, String param2) throws WebClientResponseException { Object postBody = null; // verify the required parameter 'param' is set if (param == null) { @@ -583,6 +822,24 @@ public class FakeApi { ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; return apiClient.invokeAPI("/fake/jsonFormData", HttpMethod.GET, pathParams, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); } + + /** + * test json serialization of form data + * + *

    200 - successful operation + * @param param field1 + * @param param2 field2 + * @throws WebClientResponseException if an error occurs while attempting to invoke the API + */ + public Mono testJsonFormData(String param, String param2) throws WebClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; + return testJsonFormDataRequestCreation(param, param2).bodyToMono(localVarReturnType); + } + + public Mono> testJsonFormDataWithHttpInfo(String param, String param2) throws WebClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; + return testJsonFormDataRequestCreation(param, param2).toEntity(localVarReturnType); + } /** * * To test the collection format in query parameters @@ -594,7 +851,7 @@ public class FakeApi { * @param context The context parameter * @throws WebClientResponseException if an error occurs while attempting to invoke the API */ - public Mono testQueryParameterCollectionFormat(List pipe, List ioutil, List http, List url, List context) throws WebClientResponseException { + private ResponseSpec testQueryParameterCollectionFormatRequestCreation(List pipe, List ioutil, List http, List url, List context) throws WebClientResponseException { Object postBody = null; // verify the required parameter 'pipe' is set if (pipe == null) { @@ -640,4 +897,25 @@ public class FakeApi { ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; return apiClient.invokeAPI("/fake/test-query-paramters", HttpMethod.PUT, pathParams, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); } + + /** + * + * To test the collection format in query parameters + *

    200 - Success + * @param pipe The pipe parameter + * @param ioutil The ioutil parameter + * @param http The http parameter + * @param url The url parameter + * @param context The context parameter + * @throws WebClientResponseException if an error occurs while attempting to invoke the API + */ + public Mono testQueryParameterCollectionFormat(List pipe, List ioutil, List http, List url, List context) throws WebClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; + return testQueryParameterCollectionFormatRequestCreation(pipe, ioutil, http, url, context).bodyToMono(localVarReturnType); + } + + public Mono> testQueryParameterCollectionFormatWithHttpInfo(List pipe, List ioutil, List http, List url, List context) throws WebClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; + return testQueryParameterCollectionFormatRequestCreation(pipe, ioutil, http, url, context).toEntity(localVarReturnType); + } } diff --git a/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/api/FakeClassnameTags123Api.java b/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/api/FakeClassnameTags123Api.java index 2a2d3f3e1d8..3ccd9ca33c6 100644 --- a/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/api/FakeClassnameTags123Api.java +++ b/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/api/FakeClassnameTags123Api.java @@ -15,12 +15,14 @@ import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import org.springframework.web.util.UriComponentsBuilder; import org.springframework.core.ParameterizedTypeReference; +import org.springframework.web.reactive.function.client.WebClient.ResponseSpec; import org.springframework.web.reactive.function.client.WebClientResponseException; 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; import reactor.core.publisher.Mono; import reactor.core.publisher.Flux; @@ -53,7 +55,7 @@ public class FakeClassnameTags123Api { * @return Client * @throws WebClientResponseException if an error occurs while attempting to invoke the API */ - public Mono testClassname(Client body) throws WebClientResponseException { + private ResponseSpec testClassnameRequestCreation(Client body) throws WebClientResponseException { Object postBody = body; // verify the required parameter 'body' is set if (body == null) { @@ -81,4 +83,22 @@ public class FakeClassnameTags123Api { ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; return apiClient.invokeAPI("/fake_classname_test", HttpMethod.PATCH, pathParams, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); } + + /** + * To test class name in snake case + * To test class name in snake case + *

    200 - successful operation + * @param body client model + * @return Client + * @throws WebClientResponseException if an error occurs while attempting to invoke the API + */ + public Mono testClassname(Client body) throws WebClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; + return testClassnameRequestCreation(body).bodyToMono(localVarReturnType); + } + + public Mono> testClassnameWithHttpInfo(Client body) throws WebClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; + return testClassnameRequestCreation(body).toEntity(localVarReturnType); + } } 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 3749fe40927..7166d6b0336 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 @@ -18,12 +18,14 @@ import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import org.springframework.web.util.UriComponentsBuilder; import org.springframework.core.ParameterizedTypeReference; +import org.springframework.web.reactive.function.client.WebClient.ResponseSpec; import org.springframework.web.reactive.function.client.WebClientResponseException; 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; import reactor.core.publisher.Mono; import reactor.core.publisher.Flux; @@ -56,7 +58,7 @@ public class PetApi { * @param body Pet object that needs to be added to the store * @throws WebClientResponseException if an error occurs while attempting to invoke the API */ - public Mono addPet(Pet body) throws WebClientResponseException { + private ResponseSpec addPetRequestCreation(Pet body) throws WebClientResponseException { Object postBody = body; // verify the required parameter 'body' is set if (body == null) { @@ -82,6 +84,24 @@ public class PetApi { ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; return apiClient.invokeAPI("/pet", HttpMethod.POST, pathParams, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); } + + /** + * Add a new pet to the store + * + *

    200 - successful operation + *

    405 - Invalid input + * @param body Pet object that needs to be added to the store + * @throws WebClientResponseException if an error occurs while attempting to invoke the API + */ + public Mono addPet(Pet body) throws WebClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; + return addPetRequestCreation(body).bodyToMono(localVarReturnType); + } + + public Mono> addPetWithHttpInfo(Pet body) throws WebClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; + return addPetRequestCreation(body).toEntity(localVarReturnType); + } /** * Deletes a pet * @@ -91,7 +111,7 @@ public class PetApi { * @param apiKey The apiKey parameter * @throws WebClientResponseException if an error occurs while attempting to invoke the API */ - public Mono deletePet(Long petId, String apiKey) throws WebClientResponseException { + private ResponseSpec deletePetRequestCreation(Long petId, String apiKey) throws WebClientResponseException { Object postBody = null; // verify the required parameter 'petId' is set if (petId == null) { @@ -119,6 +139,25 @@ public class PetApi { ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; return apiClient.invokeAPI("/pet/{petId}", HttpMethod.DELETE, pathParams, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); } + + /** + * Deletes a pet + * + *

    200 - successful operation + *

    400 - Invalid pet value + * @param petId Pet id to delete + * @param apiKey The apiKey parameter + * @throws WebClientResponseException if an error occurs while attempting to invoke the API + */ + public Mono deletePet(Long petId, String apiKey) throws WebClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; + return deletePetRequestCreation(petId, apiKey).bodyToMono(localVarReturnType); + } + + public Mono> deletePetWithHttpInfo(Long petId, String apiKey) throws WebClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; + return deletePetRequestCreation(petId, apiKey).toEntity(localVarReturnType); + } /** * Finds Pets by status * Multiple status values can be provided with comma separated strings @@ -128,7 +167,7 @@ public class PetApi { * @return List<Pet> * @throws WebClientResponseException if an error occurs while attempting to invoke the API */ - public Flux findPetsByStatus(List status) throws WebClientResponseException { + private ResponseSpec findPetsByStatusRequestCreation(List status) throws WebClientResponseException { Object postBody = null; // verify the required parameter 'status' is set if (status == null) { @@ -154,7 +193,26 @@ public class PetApi { String[] localVarAuthNames = new String[] { "petstore_auth" }; ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; - return apiClient.invokeFluxAPI("/pet/findByStatus", HttpMethod.GET, pathParams, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + return apiClient.invokeAPI("/pet/findByStatus", HttpMethod.GET, pathParams, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + + /** + * Finds Pets by status + * Multiple status values can be provided with comma separated strings + *

    200 - successful operation + *

    400 - Invalid status value + * @param status Status values that need to be considered for filter + * @return List<Pet> + * @throws WebClientResponseException if an error occurs while attempting to invoke the API + */ + public Flux findPetsByStatus(List status) throws WebClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; + return findPetsByStatusRequestCreation(status).bodyToFlux(localVarReturnType); + } + + public Mono>> findPetsByStatusWithHttpInfo(List status) throws WebClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; + return findPetsByStatusRequestCreation(status).toEntityList(localVarReturnType); } /** * Finds Pets by tags @@ -165,7 +223,7 @@ public class PetApi { * @return Set<Pet> * @throws WebClientResponseException if an error occurs while attempting to invoke the API */ - public Flux findPetsByTags(Set tags) throws WebClientResponseException { + private ResponseSpec findPetsByTagsRequestCreation(Set tags) throws WebClientResponseException { Object postBody = null; // verify the required parameter 'tags' is set if (tags == null) { @@ -191,7 +249,26 @@ public class PetApi { String[] localVarAuthNames = new String[] { "petstore_auth" }; ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; - return apiClient.invokeFluxAPI("/pet/findByTags", HttpMethod.GET, pathParams, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + return apiClient.invokeAPI("/pet/findByTags", HttpMethod.GET, pathParams, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + + /** + * Finds Pets by tags + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + *

    200 - successful operation + *

    400 - Invalid tag value + * @param tags Tags to filter by + * @return Set<Pet> + * @throws WebClientResponseException if an error occurs while attempting to invoke the API + */ + public Flux findPetsByTags(Set tags) throws WebClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; + return findPetsByTagsRequestCreation(tags).bodyToFlux(localVarReturnType); + } + + public Mono>> findPetsByTagsWithHttpInfo(Set tags) throws WebClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; + return findPetsByTagsRequestCreation(tags).toEntityList(localVarReturnType); } /** * Find pet by ID @@ -203,7 +280,7 @@ public class PetApi { * @return Pet * @throws WebClientResponseException if an error occurs while attempting to invoke the API */ - public Mono getPetById(Long petId) throws WebClientResponseException { + private ResponseSpec getPetByIdRequestCreation(Long petId) throws WebClientResponseException { Object postBody = null; // verify the required parameter 'petId' is set if (petId == null) { @@ -231,6 +308,26 @@ public class PetApi { ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; return apiClient.invokeAPI("/pet/{petId}", HttpMethod.GET, pathParams, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); } + + /** + * Find pet by ID + * Returns a single pet + *

    200 - successful operation + *

    400 - Invalid ID supplied + *

    404 - Pet not found + * @param petId ID of pet to return + * @return Pet + * @throws WebClientResponseException if an error occurs while attempting to invoke the API + */ + public Mono getPetById(Long petId) throws WebClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; + return getPetByIdRequestCreation(petId).bodyToMono(localVarReturnType); + } + + public Mono> getPetByIdWithHttpInfo(Long petId) throws WebClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; + return getPetByIdRequestCreation(petId).toEntity(localVarReturnType); + } /** * Update an existing pet * @@ -241,7 +338,7 @@ public class PetApi { * @param body Pet object that needs to be added to the store * @throws WebClientResponseException if an error occurs while attempting to invoke the API */ - public Mono updatePet(Pet body) throws WebClientResponseException { + private ResponseSpec updatePetRequestCreation(Pet body) throws WebClientResponseException { Object postBody = body; // verify the required parameter 'body' is set if (body == null) { @@ -267,6 +364,26 @@ public class PetApi { ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; return apiClient.invokeAPI("/pet", HttpMethod.PUT, pathParams, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); } + + /** + * Update an existing pet + * + *

    200 - successful operation + *

    400 - Invalid ID supplied + *

    404 - Pet not found + *

    405 - Validation exception + * @param body Pet object that needs to be added to the store + * @throws WebClientResponseException if an error occurs while attempting to invoke the API + */ + public Mono updatePet(Pet body) throws WebClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; + return updatePetRequestCreation(body).bodyToMono(localVarReturnType); + } + + public Mono> updatePetWithHttpInfo(Pet body) throws WebClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; + return updatePetRequestCreation(body).toEntity(localVarReturnType); + } /** * Updates a pet in the store with form data * @@ -276,7 +393,7 @@ public class PetApi { * @param status Updated status of the pet * @throws WebClientResponseException if an error occurs while attempting to invoke the API */ - public Mono updatePetWithForm(Long petId, String name, String status) throws WebClientResponseException { + private ResponseSpec updatePetWithFormRequestCreation(Long petId, String name, String status) throws WebClientResponseException { Object postBody = null; // verify the required parameter 'petId' is set if (petId == null) { @@ -309,6 +426,25 @@ public class PetApi { ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; return apiClient.invokeAPI("/pet/{petId}", HttpMethod.POST, pathParams, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); } + + /** + * Updates a pet in the store with form data + * + *

    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 + * @throws WebClientResponseException if an error occurs while attempting to invoke the API + */ + public Mono updatePetWithForm(Long petId, String name, String status) throws WebClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; + return updatePetWithFormRequestCreation(petId, name, status).bodyToMono(localVarReturnType); + } + + public Mono> updatePetWithFormWithHttpInfo(Long petId, String name, String status) throws WebClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; + return updatePetWithFormRequestCreation(petId, name, status).toEntity(localVarReturnType); + } /** * uploads an image * @@ -319,7 +455,7 @@ public class PetApi { * @return ModelApiResponse * @throws WebClientResponseException if an error occurs while attempting to invoke the API */ - public Mono uploadFile(Long petId, String additionalMetadata, File file) throws WebClientResponseException { + private ResponseSpec uploadFileRequestCreation(Long petId, String additionalMetadata, File file) throws WebClientResponseException { Object postBody = null; // verify the required parameter 'petId' is set if (petId == null) { @@ -354,6 +490,26 @@ public class PetApi { ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; return apiClient.invokeAPI("/pet/{petId}/uploadImage", HttpMethod.POST, pathParams, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); } + + /** + * uploads an image + * + *

    200 - successful operation + * @param petId ID of pet to update + * @param additionalMetadata Additional data to pass to server + * @param file file to upload + * @return ModelApiResponse + * @throws WebClientResponseException if an error occurs while attempting to invoke the API + */ + public Mono uploadFile(Long petId, String additionalMetadata, File file) throws WebClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; + return uploadFileRequestCreation(petId, additionalMetadata, file).bodyToMono(localVarReturnType); + } + + public Mono> uploadFileWithHttpInfo(Long petId, String additionalMetadata, File file) throws WebClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; + return uploadFileRequestCreation(petId, additionalMetadata, file).toEntity(localVarReturnType); + } /** * uploads an image (required) * @@ -364,7 +520,7 @@ public class PetApi { * @return ModelApiResponse * @throws WebClientResponseException if an error occurs while attempting to invoke the API */ - public Mono uploadFileWithRequiredFile(Long petId, File requiredFile, String additionalMetadata) throws WebClientResponseException { + private ResponseSpec uploadFileWithRequiredFileRequestCreation(Long petId, File requiredFile, String additionalMetadata) throws WebClientResponseException { Object postBody = null; // verify the required parameter 'petId' is set if (petId == null) { @@ -403,4 +559,24 @@ public class PetApi { ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; return apiClient.invokeAPI("/fake/{petId}/uploadImageWithRequiredFile", HttpMethod.POST, pathParams, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); } + + /** + * uploads an image (required) + * + *

    200 - successful operation + * @param petId ID of pet to update + * @param requiredFile file to upload + * @param additionalMetadata Additional data to pass to server + * @return ModelApiResponse + * @throws WebClientResponseException if an error occurs while attempting to invoke the API + */ + public Mono uploadFileWithRequiredFile(Long petId, File requiredFile, String additionalMetadata) throws WebClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; + return uploadFileWithRequiredFileRequestCreation(petId, requiredFile, additionalMetadata).bodyToMono(localVarReturnType); + } + + public Mono> uploadFileWithRequiredFileWithHttpInfo(Long petId, File requiredFile, String additionalMetadata) throws WebClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; + return uploadFileWithRequiredFileRequestCreation(petId, requiredFile, additionalMetadata).toEntity(localVarReturnType); + } } diff --git a/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/api/StoreApi.java b/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/api/StoreApi.java index 98d603a2545..3cd8dd6270c 100644 --- a/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/api/StoreApi.java +++ b/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/api/StoreApi.java @@ -15,12 +15,14 @@ import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import org.springframework.web.util.UriComponentsBuilder; import org.springframework.core.ParameterizedTypeReference; +import org.springframework.web.reactive.function.client.WebClient.ResponseSpec; import org.springframework.web.reactive.function.client.WebClientResponseException; 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; import reactor.core.publisher.Mono; import reactor.core.publisher.Flux; @@ -53,7 +55,7 @@ public class StoreApi { * @param orderId ID of the order that needs to be deleted * @throws WebClientResponseException if an error occurs while attempting to invoke the API */ - public Mono deleteOrder(String orderId) throws WebClientResponseException { + private ResponseSpec deleteOrderRequestCreation(String orderId) throws WebClientResponseException { Object postBody = null; // verify the required parameter 'orderId' is set if (orderId == null) { @@ -79,6 +81,24 @@ public class StoreApi { ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; return apiClient.invokeAPI("/store/order/{order_id}", HttpMethod.DELETE, pathParams, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); } + + /** + * Delete purchase order by ID + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + *

    400 - Invalid ID supplied + *

    404 - Order not found + * @param orderId ID of the order that needs to be deleted + * @throws WebClientResponseException if an error occurs while attempting to invoke the API + */ + public Mono deleteOrder(String orderId) throws WebClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; + return deleteOrderRequestCreation(orderId).bodyToMono(localVarReturnType); + } + + public Mono> deleteOrderWithHttpInfo(String orderId) throws WebClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; + return deleteOrderRequestCreation(orderId).toEntity(localVarReturnType); + } /** * Returns pet inventories by status * Returns a map of status codes to quantities @@ -86,7 +106,7 @@ public class StoreApi { * @return Map<String, Integer> * @throws WebClientResponseException if an error occurs while attempting to invoke the API */ - public Mono> getInventory() throws WebClientResponseException { + private ResponseSpec getInventoryRequestCreation() throws WebClientResponseException { Object postBody = null; // create path and map variables final Map pathParams = new HashMap(); @@ -108,6 +128,23 @@ public class StoreApi { ParameterizedTypeReference> localVarReturnType = new ParameterizedTypeReference>() {}; return apiClient.invokeAPI("/store/inventory", HttpMethod.GET, pathParams, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); } + + /** + * Returns pet inventories by status + * Returns a map of status codes to quantities + *

    200 - successful operation + * @return Map<String, Integer> + * @throws WebClientResponseException if an error occurs while attempting to invoke the API + */ + public Mono> getInventory() throws WebClientResponseException { + ParameterizedTypeReference> localVarReturnType = new ParameterizedTypeReference>() {}; + return getInventoryRequestCreation().bodyToMono(localVarReturnType); + } + + public Mono>> getInventoryWithHttpInfo() throws WebClientResponseException { + ParameterizedTypeReference> localVarReturnType = new ParameterizedTypeReference>() {}; + return getInventoryRequestCreation().toEntity(localVarReturnType); + } /** * Find purchase order by ID * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions @@ -118,7 +155,7 @@ public class StoreApi { * @return Order * @throws WebClientResponseException if an error occurs while attempting to invoke the API */ - public Mono getOrderById(Long orderId) throws WebClientResponseException { + private ResponseSpec getOrderByIdRequestCreation(Long orderId) throws WebClientResponseException { Object postBody = null; // verify the required parameter 'orderId' is set if (orderId == null) { @@ -146,6 +183,26 @@ public class StoreApi { ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; return apiClient.invokeAPI("/store/order/{order_id}", HttpMethod.GET, pathParams, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); } + + /** + * Find purchase order by ID + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + *

    200 - successful operation + *

    400 - Invalid ID supplied + *

    404 - Order not found + * @param orderId ID of pet that needs to be fetched + * @return Order + * @throws WebClientResponseException if an error occurs while attempting to invoke the API + */ + public Mono getOrderById(Long orderId) throws WebClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; + return getOrderByIdRequestCreation(orderId).bodyToMono(localVarReturnType); + } + + public Mono> getOrderByIdWithHttpInfo(Long orderId) throws WebClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; + return getOrderByIdRequestCreation(orderId).toEntity(localVarReturnType); + } /** * Place an order for a pet * @@ -155,7 +212,7 @@ public class StoreApi { * @return Order * @throws WebClientResponseException if an error occurs while attempting to invoke the API */ - public Mono placeOrder(Order body) throws WebClientResponseException { + private ResponseSpec placeOrderRequestCreation(Order body) throws WebClientResponseException { Object postBody = body; // verify the required parameter 'body' is set if (body == null) { @@ -181,4 +238,23 @@ public class StoreApi { ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; return apiClient.invokeAPI("/store/order", HttpMethod.POST, pathParams, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); } + + /** + * Place an order for a pet + * + *

    200 - successful operation + *

    400 - Invalid Order + * @param body order placed for purchasing the pet + * @return Order + * @throws WebClientResponseException if an error occurs while attempting to invoke the API + */ + public Mono placeOrder(Order body) throws WebClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; + return placeOrderRequestCreation(body).bodyToMono(localVarReturnType); + } + + public Mono> placeOrderWithHttpInfo(Order body) throws WebClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; + return placeOrderRequestCreation(body).toEntity(localVarReturnType); + } } 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 62188c93a1c..38eb9e61c3b 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 @@ -15,12 +15,14 @@ import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import org.springframework.web.util.UriComponentsBuilder; import org.springframework.core.ParameterizedTypeReference; +import org.springframework.web.reactive.function.client.WebClient.ResponseSpec; import org.springframework.web.reactive.function.client.WebClientResponseException; 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; import reactor.core.publisher.Mono; import reactor.core.publisher.Flux; @@ -52,7 +54,7 @@ public class UserApi { * @param body Created user object * @throws WebClientResponseException if an error occurs while attempting to invoke the API */ - public Mono createUser(User body) throws WebClientResponseException { + private ResponseSpec createUserRequestCreation(User body) throws WebClientResponseException { Object postBody = body; // verify the required parameter 'body' is set if (body == null) { @@ -76,6 +78,23 @@ public class UserApi { ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; return apiClient.invokeAPI("/user", HttpMethod.POST, pathParams, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); } + + /** + * Create user + * This can only be done by the logged in user. + *

    0 - successful operation + * @param body Created user object + * @throws WebClientResponseException if an error occurs while attempting to invoke the API + */ + public Mono createUser(User body) throws WebClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; + return createUserRequestCreation(body).bodyToMono(localVarReturnType); + } + + public Mono> createUserWithHttpInfo(User body) throws WebClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; + return createUserRequestCreation(body).toEntity(localVarReturnType); + } /** * Creates list of users with given input array * @@ -83,7 +102,7 @@ public class UserApi { * @param body List of user object * @throws WebClientResponseException if an error occurs while attempting to invoke the API */ - public Mono createUsersWithArrayInput(List body) throws WebClientResponseException { + private ResponseSpec createUsersWithArrayInputRequestCreation(List body) throws WebClientResponseException { Object postBody = body; // verify the required parameter 'body' is set if (body == null) { @@ -107,6 +126,7 @@ public class UserApi { ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; return apiClient.invokeAPI("/user/createWithArray", HttpMethod.POST, pathParams, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); } + /** * Creates list of users with given input array * @@ -114,7 +134,23 @@ public class UserApi { * @param body List of user object * @throws WebClientResponseException if an error occurs while attempting to invoke the API */ - public Mono createUsersWithListInput(List body) throws WebClientResponseException { + public Mono createUsersWithArrayInput(List body) throws WebClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; + return createUsersWithArrayInputRequestCreation(body).bodyToMono(localVarReturnType); + } + + public Mono> createUsersWithArrayInputWithHttpInfo(List body) throws WebClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; + return createUsersWithArrayInputRequestCreation(body).toEntity(localVarReturnType); + } + /** + * Creates list of users with given input array + * + *

    0 - successful operation + * @param body List of user object + * @throws WebClientResponseException if an error occurs while attempting to invoke the API + */ + private ResponseSpec createUsersWithListInputRequestCreation(List body) throws WebClientResponseException { Object postBody = body; // verify the required parameter 'body' is set if (body == null) { @@ -138,6 +174,23 @@ public class UserApi { ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; return apiClient.invokeAPI("/user/createWithList", HttpMethod.POST, pathParams, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); } + + /** + * Creates list of users with given input array + * + *

    0 - successful operation + * @param body List of user object + * @throws WebClientResponseException if an error occurs while attempting to invoke the API + */ + public Mono createUsersWithListInput(List body) throws WebClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; + return createUsersWithListInputRequestCreation(body).bodyToMono(localVarReturnType); + } + + public Mono> createUsersWithListInputWithHttpInfo(List body) throws WebClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; + return createUsersWithListInputRequestCreation(body).toEntity(localVarReturnType); + } /** * Delete user * This can only be done by the logged in user. @@ -146,7 +199,7 @@ public class UserApi { * @param username The name that needs to be deleted * @throws WebClientResponseException if an error occurs while attempting to invoke the API */ - public Mono deleteUser(String username) throws WebClientResponseException { + private ResponseSpec deleteUserRequestCreation(String username) throws WebClientResponseException { Object postBody = null; // verify the required parameter 'username' is set if (username == null) { @@ -172,6 +225,24 @@ public class UserApi { ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; return apiClient.invokeAPI("/user/{username}", HttpMethod.DELETE, pathParams, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); } + + /** + * Delete user + * This can only be done by the logged in user. + *

    400 - Invalid username supplied + *

    404 - User not found + * @param username The name that needs to be deleted + * @throws WebClientResponseException if an error occurs while attempting to invoke the API + */ + public Mono deleteUser(String username) throws WebClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; + return deleteUserRequestCreation(username).bodyToMono(localVarReturnType); + } + + public Mono> deleteUserWithHttpInfo(String username) throws WebClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; + return deleteUserRequestCreation(username).toEntity(localVarReturnType); + } /** * Get user by user name * @@ -182,7 +253,7 @@ public class UserApi { * @return User * @throws WebClientResponseException if an error occurs while attempting to invoke the API */ - public Mono getUserByName(String username) throws WebClientResponseException { + private ResponseSpec getUserByNameRequestCreation(String username) throws WebClientResponseException { Object postBody = null; // verify the required parameter 'username' is set if (username == null) { @@ -210,6 +281,26 @@ public class UserApi { ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; return apiClient.invokeAPI("/user/{username}", HttpMethod.GET, pathParams, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); } + + /** + * Get user by user name + * + *

    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 User + * @throws WebClientResponseException if an error occurs while attempting to invoke the API + */ + public Mono getUserByName(String username) throws WebClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; + return getUserByNameRequestCreation(username).bodyToMono(localVarReturnType); + } + + public Mono> getUserByNameWithHttpInfo(String username) throws WebClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; + return getUserByNameRequestCreation(username).toEntity(localVarReturnType); + } /** * Logs user into the system * @@ -220,7 +311,7 @@ public class UserApi { * @return String * @throws WebClientResponseException if an error occurs while attempting to invoke the API */ - public Mono loginUser(String username, String password) throws WebClientResponseException { + private ResponseSpec loginUserRequestCreation(String username, String password) throws WebClientResponseException { Object postBody = null; // verify the required parameter 'username' is set if (username == null) { @@ -253,13 +344,33 @@ public class UserApi { ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; return apiClient.invokeAPI("/user/login", HttpMethod.GET, pathParams, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); } + + /** + * Logs user into the system + * + *

    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 String + * @throws WebClientResponseException if an error occurs while attempting to invoke the API + */ + public Mono loginUser(String username, String password) throws WebClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; + return loginUserRequestCreation(username, password).bodyToMono(localVarReturnType); + } + + public Mono> loginUserWithHttpInfo(String username, String password) throws WebClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; + return loginUserRequestCreation(username, password).toEntity(localVarReturnType); + } /** * Logs out current logged in user session * *

    0 - successful operation * @throws WebClientResponseException if an error occurs while attempting to invoke the API */ - public Mono logoutUser() throws WebClientResponseException { + private ResponseSpec logoutUserRequestCreation() throws WebClientResponseException { Object postBody = null; // create path and map variables final Map pathParams = new HashMap(); @@ -279,6 +390,22 @@ public class UserApi { ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; return apiClient.invokeAPI("/user/logout", HttpMethod.GET, pathParams, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); } + + /** + * Logs out current logged in user session + * + *

    0 - successful operation + * @throws WebClientResponseException if an error occurs while attempting to invoke the API + */ + public Mono logoutUser() throws WebClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; + return logoutUserRequestCreation().bodyToMono(localVarReturnType); + } + + public Mono> logoutUserWithHttpInfo() throws WebClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; + return logoutUserRequestCreation().toEntity(localVarReturnType); + } /** * Updated user * This can only be done by the logged in user. @@ -288,7 +415,7 @@ public class UserApi { * @param body Updated user object * @throws WebClientResponseException if an error occurs while attempting to invoke the API */ - public Mono updateUser(String username, User body) throws WebClientResponseException { + private ResponseSpec updateUserRequestCreation(String username, User body) throws WebClientResponseException { Object postBody = body; // verify the required parameter 'username' is set if (username == null) { @@ -318,4 +445,23 @@ public class UserApi { ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; return apiClient.invokeAPI("/user/{username}", HttpMethod.PUT, pathParams, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); } + + /** + * Updated user + * This can only be done by the logged in user. + *

    400 - Invalid user supplied + *

    404 - User not found + * @param username name that need to be deleted + * @param body Updated user object + * @throws WebClientResponseException if an error occurs while attempting to invoke the API + */ + public Mono updateUser(String username, User body) throws WebClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; + return updateUserRequestCreation(username, body).bodyToMono(localVarReturnType); + } + + public Mono> updateUserWithHttpInfo(String username, User body) throws WebClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; + return updateUserRequestCreation(username, body).toEntity(localVarReturnType); + } } diff --git a/samples/client/petstore/javascript-es6/.openapi-generator/VERSION b/samples/client/petstore/javascript-es6/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/client/petstore/javascript-es6/.openapi-generator/VERSION +++ b/samples/client/petstore/javascript-es6/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/client/petstore/javascript-es6/README.md b/samples/client/petstore/javascript-es6/README.md index 7484625b457..736594bda69 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* | [**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 | *OpenApiPetstore.FakeApi* | [**testClientModel**](docs/FakeApi.md#testClientModel) | **PATCH** /fake | To test \"client\" model diff --git a/samples/client/petstore/javascript-es6/docs/FakeApi.md b/samples/client/petstore/javascript-es6/docs/FakeApi.md index 95446d77d5e..9ba9d28131b 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 | +[**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 | [**testClientModel**](FakeApi.md#testClientModel) | **PATCH** /fake | To test \"client\" model @@ -345,13 +346,58 @@ No authorization required - **Accept**: */* +## testBodyWithBinary + +> testBodyWithBinary(body) + + + +For this test, the body has to be a binary file. + +### Example + +```javascript +import OpenApiPetstore from 'open_api_petstore'; + +let apiInstance = new OpenApiPetstore.FakeApi(); +let body = "/path/to/file"; // File | image to upload +apiInstance.testBodyWithBinary(body, (error, data, response) => { + if (error) { + console.error(error); + } else { + console.log('API called successfully.'); + } +}); +``` + +### Parameters + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | **File**| image to upload | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: image/png +- **Accept**: Not defined + + ## testBodyWithFileSchema > testBodyWithFileSchema(fileSchemaTestClass) -For this test, the body for this request much reference a schema named `File`. +For this test, the body for this request must reference a schema named `File`. ### Example diff --git a/samples/client/petstore/javascript-es6/src/api/FakeApi.js b/samples/client/petstore/javascript-es6/src/api/FakeApi.js index 33f85635f09..3b9e1509cef 100644 --- a/samples/client/petstore/javascript-es6/src/api/FakeApi.js +++ b/samples/client/petstore/javascript-es6/src/api/FakeApi.js @@ -319,6 +319,46 @@ export default class FakeApi { ); } + /** + * Callback function to receive the result of the testBodyWithBinary operation. + * @callback module:api/FakeApi~testBodyWithBinaryCallback + * @param {String} error Error message, if any. + * @param data This operation does not return a value. + * @param {String} response The complete HTTP response. + */ + + /** + * For this test, the body has to be a binary file. + * @param {File} body image to upload + * @param {module:api/FakeApi~testBodyWithBinaryCallback} callback The callback function, accepting three arguments: error, data, response + */ + testBodyWithBinary(body, callback) { + let postBody = body; + // verify the required parameter 'body' is set + if (body === undefined || body === null) { + throw new Error("Missing the required parameter 'body' when calling testBodyWithBinary"); + } + + let pathParams = { + }; + let queryParams = { + }; + let headerParams = { + }; + let formParams = { + }; + + let authNames = []; + let contentTypes = ['image/png']; + let accepts = []; + let returnType = null; + return this.apiClient.callApi( + '/fake/body-with-binary', 'PUT', + pathParams, queryParams, headerParams, formParams, postBody, + authNames, contentTypes, accepts, returnType, null, callback + ); + } + /** * Callback function to receive the result of the testBodyWithFileSchema operation. * @callback module:api/FakeApi~testBodyWithFileSchemaCallback @@ -328,7 +368,7 @@ export default class FakeApi { */ /** - * For this test, the body for this request much reference a schema named `File`. + * For this test, the body for this request must reference a schema named `File`. * @param {module:model/FileSchemaTestClass} fileSchemaTestClass * @param {module:api/FakeApi~testBodyWithFileSchemaCallback} callback The callback function, accepting three arguments: error, data, response */ @@ -774,7 +814,7 @@ export default class FakeApi { let pathParams = { }; let queryParams = { - 'pipe': this.apiClient.buildCollectionParam(pipe, 'multi'), + 'pipe': this.apiClient.buildCollectionParam(pipe, 'pipes'), 'ioutil': this.apiClient.buildCollectionParam(ioutil, 'csv'), 'http': this.apiClient.buildCollectionParam(http, 'ssv'), 'url': this.apiClient.buildCollectionParam(url, 'csv'), diff --git a/samples/client/petstore/javascript-promise-es6/.openapi-generator/VERSION b/samples/client/petstore/javascript-promise-es6/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/client/petstore/javascript-promise-es6/.openapi-generator/VERSION +++ b/samples/client/petstore/javascript-promise-es6/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/client/petstore/javascript-promise-es6/README.md b/samples/client/petstore/javascript-promise-es6/README.md index ef092423575..b13f89f2dac 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* | [**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 | *OpenApiPetstore.FakeApi* | [**testClientModel**](docs/FakeApi.md#testClientModel) | **PATCH** /fake | To test \"client\" model diff --git a/samples/client/petstore/javascript-promise-es6/docs/FakeApi.md b/samples/client/petstore/javascript-promise-es6/docs/FakeApi.md index b6c5594e0ba..a0cd0aefb42 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 | +[**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 | [**testClientModel**](FakeApi.md#testClientModel) | **PATCH** /fake | To test \"client\" model @@ -338,13 +339,57 @@ No authorization required - **Accept**: */* +## testBodyWithBinary + +> testBodyWithBinary(body) + + + +For this test, the body has to be a binary file. + +### Example + +```javascript +import OpenApiPetstore from 'open_api_petstore'; + +let apiInstance = new OpenApiPetstore.FakeApi(); +let body = "/path/to/file"; // File | image to upload +apiInstance.testBodyWithBinary(body).then(() => { + console.log('API called successfully.'); +}, (error) => { + console.error(error); +}); + +``` + +### Parameters + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | **File**| image to upload | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: image/png +- **Accept**: Not defined + + ## testBodyWithFileSchema > testBodyWithFileSchema(fileSchemaTestClass) -For this test, the body for this request much reference a schema named `File`. +For this test, the body for this request must reference a schema named `File`. ### Example 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 0902c816dc4..e635c42692c 100644 --- a/samples/client/petstore/javascript-promise-es6/src/api/FakeApi.js +++ b/samples/client/petstore/javascript-promise-es6/src/api/FakeApi.js @@ -356,7 +356,52 @@ export default class FakeApi { /** - * For this test, the body for this request much reference a schema named `File`. + * For this test, the body has to be a binary file. + * @param {File} body image to upload + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing HTTP response + */ + testBodyWithBinaryWithHttpInfo(body) { + let postBody = body; + // verify the required parameter 'body' is set + if (body === undefined || body === null) { + throw new Error("Missing the required parameter 'body' when calling testBodyWithBinary"); + } + + let pathParams = { + }; + let queryParams = { + }; + let headerParams = { + }; + let formParams = { + }; + + let authNames = []; + let contentTypes = ['image/png']; + let accepts = []; + let returnType = null; + return this.apiClient.callApi( + '/fake/body-with-binary', 'PUT', + pathParams, queryParams, headerParams, formParams, postBody, + authNames, contentTypes, accepts, returnType, null + ); + } + + /** + * For this test, the body has to be a binary file. + * @param {File} body image to upload + * @return {Promise} a {@link https://www.promisejs.org/|Promise} + */ + testBodyWithBinary(body) { + return this.testBodyWithBinaryWithHttpInfo(body) + .then(function(response_and_data) { + return response_and_data.data; + }); + } + + + /** + * For this test, the body for this request must reference a schema named `File`. * @param {module:model/FileSchemaTestClass} fileSchemaTestClass * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing HTTP response */ @@ -388,7 +433,7 @@ export default class FakeApi { } /** - * For this test, the body for this request much reference a schema named `File`. + * For this test, the body for this request must reference a schema named `File`. * @param {module:model/FileSchemaTestClass} fileSchemaTestClass * @return {Promise} a {@link https://www.promisejs.org/|Promise} */ @@ -874,7 +919,7 @@ export default class FakeApi { let pathParams = { }; let queryParams = { - 'pipe': this.apiClient.buildCollectionParam(pipe, 'multi'), + 'pipe': this.apiClient.buildCollectionParam(pipe, 'pipes'), 'ioutil': this.apiClient.buildCollectionParam(ioutil, 'csv'), 'http': this.apiClient.buildCollectionParam(http, 'ssv'), 'url': this.apiClient.buildCollectionParam(url, 'csv'), 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 d99e7162d01..6555596f931 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.0.0-SNAPSHOT \ No newline at end of file +5.2.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 e2d463a2cfe..aa59537336d 100644 --- a/samples/client/petstore/jaxrs-cxf-client-jackson/pom.xml +++ b/samples/client/petstore/jaxrs-cxf-client-jackson/pom.xml @@ -171,7 +171,7 @@ 1.5.18 9.2.9.v20150224 4.13.1 - 1.1.7 + 1.2.0 2.5 3.3.0 2.9.9 diff --git a/samples/client/petstore/jaxrs-cxf-client/.openapi-generator/VERSION b/samples/client/petstore/jaxrs-cxf-client/.openapi-generator/VERSION index d99e7162d01..6555596f931 100644 --- a/samples/client/petstore/jaxrs-cxf-client/.openapi-generator/VERSION +++ b/samples/client/petstore/jaxrs-cxf-client/.openapi-generator/VERSION @@ -1 +1 @@ -5.0.0-SNAPSHOT \ No newline at end of file +5.2.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 e3f53e0f7ba..fe612296899 100644 --- a/samples/client/petstore/jaxrs-cxf-client/pom.xml +++ b/samples/client/petstore/jaxrs-cxf-client/pom.xml @@ -170,8 +170,8 @@ ${java.version} 1.5.18 9.2.9.v20150224 - 4.13 - 1.1.7 + 4.13.1 + 1.2.0 2.5 3.3.0 2.9.9 diff --git a/samples/client/petstore/kotlin-gson/.openapi-generator/FILES b/samples/client/petstore/kotlin-gson/.openapi-generator/FILES index bf441309074..1f38d3fbe2d 100644 --- a/samples/client/petstore/kotlin-gson/.openapi-generator/FILES +++ b/samples/client/petstore/kotlin-gson/.openapi-generator/FILES @@ -20,7 +20,6 @@ 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/ApiInfrastructureResponse.kt -src/main/kotlin/org/openapitools/client/infrastructure/ApplicationDelegates.kt src/main/kotlin/org/openapitools/client/infrastructure/ByteArrayAdapter.kt src/main/kotlin/org/openapitools/client/infrastructure/DateAdapter.kt src/main/kotlin/org/openapitools/client/infrastructure/Errors.kt diff --git a/samples/client/petstore/kotlin-gson/.openapi-generator/VERSION b/samples/client/petstore/kotlin-gson/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/client/petstore/kotlin-gson/.openapi-generator/VERSION +++ b/samples/client/petstore/kotlin-gson/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/client/petstore/kotlin-gson/build.gradle b/samples/client/petstore/kotlin-gson/build.gradle index ae150592cbb..5cad8581cb6 100644 --- a/samples/client/petstore/kotlin-gson/build.gradle +++ b/samples/client/petstore/kotlin-gson/build.gradle @@ -7,7 +7,7 @@ wrapper { } buildscript { - ext.kotlin_version = '1.4.30' + ext.kotlin_version = '1.5.10' repositories { maven { url "https://repo1.maven.org/maven2" } @@ -28,8 +28,8 @@ test { } dependencies { - compile "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version" - compile "com.google.code.gson:gson:2.8.6" - compile "com.squareup.okhttp3:okhttp:4.9.0" - testCompile "io.kotlintest:kotlintest-runner-junit5:3.4.2" + implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version" + implementation "com.google.code.gson:gson:2.8.7" + implementation "com.squareup.okhttp3:okhttp:4.9.1" + testImplementation "io.kotlintest:kotlintest-runner-junit5:3.4.2" } diff --git a/samples/client/petstore/kotlin-gson/src/main/kotlin/org/openapitools/client/apis/PetApi.kt b/samples/client/petstore/kotlin-gson/src/main/kotlin/org/openapitools/client/apis/PetApi.kt index c8b93b33bf6..be50dd6c442 100644 --- a/samples/client/petstore/kotlin-gson/src/main/kotlin/org/openapitools/client/apis/PetApi.kt +++ b/samples/client/petstore/kotlin-gson/src/main/kotlin/org/openapitools/client/apis/PetApi.kt @@ -47,7 +47,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun addPet(body: Pet) : Unit { val localVariableConfig = addPetRequestConfig(body = body) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -72,20 +72,18 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param body Pet object that needs to be added to the store * @return RequestConfig */ - fun addPetRequestConfig(body: Pet) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun addPetRequestConfig(body: Pet) : RequestConfig { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/pet", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -102,7 +100,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun deletePet(petId: kotlin.Long, apiKey: kotlin.String?) : Unit { val localVariableConfig = deletePetRequestConfig(petId = petId, apiKey = apiKey) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -128,21 +126,19 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param apiKey (optional) * @return RequestConfig */ - fun deletePetRequestConfig(petId: kotlin.Long, apiKey: kotlin.String?) : RequestConfig { - val localVariableBody: kotlin.Any? = null + 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() } - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.DELETE, path = "/pet/{petId}".replace("{"+"petId"+"}", "$petId"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -159,7 +155,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun findPetsByStatus(status: kotlin.collections.List) : kotlin.collections.List { val localVariableConfig = findPetsByStatusRequestConfig(status = status) - val localVarResponse = request>( + val localVarResponse = request>( localVariableConfig ) @@ -184,23 +180,21 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param status Status values that need to be considered for filter * @return RequestConfig */ - fun findPetsByStatusRequestConfig(status: kotlin.collections.List) : RequestConfig { - val localVariableBody: kotlin.Any? = null + 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() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/pet/findByStatus", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -216,9 +210,10 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { @Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class) @Deprecated(message = "This operation is deprecated.") fun findPetsByTags(tags: kotlin.collections.List) : kotlin.collections.List { + @Suppress("DEPRECATION") val localVariableConfig = findPetsByTagsRequestConfig(tags = tags) - val localVarResponse = request>( + val localVarResponse = request>( localVariableConfig ) @@ -244,23 +239,21 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @return RequestConfig */ @Deprecated(message = "This operation is deprecated.") - fun findPetsByTagsRequestConfig(tags: kotlin.collections.List) : RequestConfig { - val localVariableBody: kotlin.Any? = null + 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() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/pet/findByTags", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -277,7 +270,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun getPetById(petId: kotlin.Long) : Pet { val localVariableConfig = getPetByIdRequestConfig(petId = petId) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -302,20 +295,18 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param petId ID of pet to return * @return RequestConfig */ - fun getPetByIdRequestConfig(petId: kotlin.Long) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun getPetByIdRequestConfig(petId: kotlin.Long) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/pet/{petId}".replace("{"+"petId"+"}", "$petId"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -331,7 +322,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun updatePet(body: Pet) : Unit { val localVariableConfig = updatePetRequestConfig(body = body) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -356,20 +347,18 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param body Pet object that needs to be added to the store * @return RequestConfig */ - fun updatePetRequestConfig(body: Pet) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun updatePetRequestConfig(body: Pet) : RequestConfig { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.PUT, path = "/pet", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -387,7 +376,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun updatePetWithForm(petId: kotlin.Long, name: kotlin.String?, status: kotlin.String?) : Unit { val localVariableConfig = updatePetWithFormRequestConfig(petId = petId, name = name, status = status) - val localVarResponse = request( + val localVarResponse = request, Unit>( localVariableConfig ) @@ -414,20 +403,18 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param status Updated status of the pet (optional) * @return RequestConfig */ - fun updatePetWithFormRequestConfig(petId: kotlin.Long, name: kotlin.String?, status: kotlin.String?) : RequestConfig { - val localVariableBody: kotlin.Any? = mapOf("name" to name, "status" to status) + fun updatePetWithFormRequestConfig(petId: kotlin.Long, name: kotlin.String?, status: kotlin.String?) : RequestConfig> { + val localVariableBody = mapOf("name" to name, "status" to status) val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf("Content-Type" to "application/x-www-form-urlencoded") - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/pet/{petId}".replace("{"+"petId"+"}", "$petId"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -446,7 +433,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun uploadFile(petId: kotlin.Long, additionalMetadata: kotlin.String?, file: java.io.File?) : ApiResponse { val localVariableConfig = uploadFileRequestConfig(petId = petId, additionalMetadata = additionalMetadata, file = file) - val localVarResponse = request( + val localVarResponse = request, ApiResponse>( localVariableConfig ) @@ -473,20 +460,18 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param file file to upload (optional) * @return RequestConfig */ - fun uploadFileRequestConfig(petId: kotlin.Long, additionalMetadata: kotlin.String?, file: java.io.File?) : RequestConfig { - val localVariableBody: kotlin.Any? = mapOf("additionalMetadata" to additionalMetadata, "file" to file) + fun uploadFileRequestConfig(petId: kotlin.Long, additionalMetadata: kotlin.String?, file: java.io.File?) : RequestConfig> { + val localVariableBody = mapOf("additionalMetadata" to additionalMetadata, "file" to file) val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf("Content-Type" to "multipart/form-data") - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/pet/{petId}/uploadImage".replace("{"+"petId"+"}", "$petId"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } } diff --git a/samples/client/petstore/kotlin-gson/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt b/samples/client/petstore/kotlin-gson/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt index 215ed63420c..56a23202f82 100644 --- a/samples/client/petstore/kotlin-gson/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt +++ b/samples/client/petstore/kotlin-gson/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt @@ -46,7 +46,7 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) fun deleteOrder(orderId: kotlin.String) : Unit { val localVariableConfig = deleteOrderRequestConfig(orderId = orderId) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -71,20 +71,18 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) * @param orderId ID of the order that needs to be deleted * @return RequestConfig */ - fun deleteOrderRequestConfig(orderId: kotlin.String) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun deleteOrderRequestConfig(orderId: kotlin.String) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.DELETE, path = "/store/order/{orderId}".replace("{"+"orderId"+"}", "$orderId"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -100,7 +98,7 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) fun getInventory() : kotlin.collections.Map { val localVariableConfig = getInventoryRequestConfig() - val localVarResponse = request>( + val localVarResponse = request>( localVariableConfig ) @@ -124,20 +122,18 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) * * @return RequestConfig */ - fun getInventoryRequestConfig() : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun getInventoryRequestConfig() : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/store/inventory", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -154,7 +150,7 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) fun getOrderById(orderId: kotlin.Long) : Order { val localVariableConfig = getOrderByIdRequestConfig(orderId = orderId) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -179,20 +175,18 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) * @param orderId ID of pet that needs to be fetched * @return RequestConfig */ - fun getOrderByIdRequestConfig(orderId: kotlin.Long) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun getOrderByIdRequestConfig(orderId: kotlin.Long) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/store/order/{orderId}".replace("{"+"orderId"+"}", "$orderId"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -209,7 +203,7 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) fun placeOrder(body: Order) : Order { val localVariableConfig = placeOrderRequestConfig(body = body) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -234,20 +228,18 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) * @param body order placed for purchasing the pet * @return RequestConfig */ - fun placeOrderRequestConfig(body: Order) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun placeOrderRequestConfig(body: Order) : RequestConfig { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/store/order", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } } diff --git a/samples/client/petstore/kotlin-gson/src/main/kotlin/org/openapitools/client/apis/UserApi.kt b/samples/client/petstore/kotlin-gson/src/main/kotlin/org/openapitools/client/apis/UserApi.kt index 53748b93463..9f93e853a12 100644 --- a/samples/client/petstore/kotlin-gson/src/main/kotlin/org/openapitools/client/apis/UserApi.kt +++ b/samples/client/petstore/kotlin-gson/src/main/kotlin/org/openapitools/client/apis/UserApi.kt @@ -46,7 +46,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun createUser(body: User) : Unit { val localVariableConfig = createUserRequestConfig(body = body) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -71,20 +71,18 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param body Created user object * @return RequestConfig */ - fun createUserRequestConfig(body: User) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun createUserRequestConfig(body: User) : RequestConfig { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/user", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -100,7 +98,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun createUsersWithArrayInput(body: kotlin.collections.List) : Unit { val localVariableConfig = createUsersWithArrayInputRequestConfig(body = body) - val localVarResponse = request( + val localVarResponse = request, Unit>( localVariableConfig ) @@ -125,20 +123,18 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param body List of user object * @return RequestConfig */ - fun createUsersWithArrayInputRequestConfig(body: kotlin.collections.List) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun createUsersWithArrayInputRequestConfig(body: kotlin.collections.List) : RequestConfig> { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/user/createWithArray", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -154,7 +150,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun createUsersWithListInput(body: kotlin.collections.List) : Unit { val localVariableConfig = createUsersWithListInputRequestConfig(body = body) - val localVarResponse = request( + val localVarResponse = request, Unit>( localVariableConfig ) @@ -179,20 +175,18 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param body List of user object * @return RequestConfig */ - fun createUsersWithListInputRequestConfig(body: kotlin.collections.List) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun createUsersWithListInputRequestConfig(body: kotlin.collections.List) : RequestConfig> { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/user/createWithList", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -208,7 +202,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun deleteUser(username: kotlin.String) : Unit { val localVariableConfig = deleteUserRequestConfig(username = username) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -233,20 +227,18 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param username The name that needs to be deleted * @return RequestConfig */ - fun deleteUserRequestConfig(username: kotlin.String) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun deleteUserRequestConfig(username: kotlin.String) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.DELETE, path = "/user/{username}".replace("{"+"username"+"}", "$username"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -263,7 +255,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun getUserByName(username: kotlin.String) : User { val localVariableConfig = getUserByNameRequestConfig(username = username) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -288,20 +280,18 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param username The name that needs to be fetched. Use user1 for testing. * @return RequestConfig */ - fun getUserByNameRequestConfig(username: kotlin.String) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun getUserByNameRequestConfig(username: kotlin.String) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/user/{username}".replace("{"+"username"+"}", "$username"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -319,7 +309,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun loginUser(username: kotlin.String, password: kotlin.String) : kotlin.String { val localVariableConfig = loginUserRequestConfig(username = username, password = password) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -345,24 +335,22 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param password The password for login in clear text * @return RequestConfig */ - fun loginUserRequestConfig(username: kotlin.String, password: kotlin.String) : RequestConfig { - val localVariableBody: kotlin.Any? = null + 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() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/user/login", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -377,7 +365,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun logoutUser() : Unit { val localVariableConfig = logoutUserRequestConfig() - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -401,20 +389,18 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * * @return RequestConfig */ - fun logoutUserRequestConfig() : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun logoutUserRequestConfig() : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/user/logout", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -431,7 +417,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun updateUser(username: kotlin.String, body: User) : Unit { val localVariableConfig = updateUserRequestConfig(username = username, body = body) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -457,20 +443,18 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param body Updated user object * @return RequestConfig */ - fun updateUserRequestConfig(username: kotlin.String, body: User) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun updateUserRequestConfig(username: kotlin.String, body: User) : RequestConfig { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.PUT, path = "/user/{username}".replace("{"+"username"+"}", "$username"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } } 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 8ffe5403596..8ba19ee8e15 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 @@ -1,6 +1,5 @@ package org.openapitools.client.infrastructure -import okhttp3.Credentials import okhttp3.OkHttpClient import okhttp3.RequestBody import okhttp3.RequestBody.Companion.asRequestBody @@ -12,17 +11,17 @@ import okhttp3.MediaType.Companion.toMediaTypeOrNull import okhttp3.Request import okhttp3.Headers import okhttp3.MultipartBody -import java.io.File import java.io.BufferedWriter +import java.io.File import java.io.FileWriter import java.net.URLConnection -import java.nio.file.Files -import java.util.Date import java.time.LocalDate import java.time.LocalDateTime import java.time.LocalTime import java.time.OffsetDateTime import java.time.OffsetTime +import java.util.Date +import java.util.Locale open class ApiClient(val baseUrl: String) { companion object { @@ -62,9 +61,7 @@ open class ApiClient(val baseUrl: String) { protected inline fun requestBody(content: T, mediaType: String = JsonMediaType): RequestBody = when { - content is File -> content.asRequestBody( - mediaType.toMediaTypeOrNull() - ) + content is File -> content.asRequestBody(mediaType.toMediaTypeOrNull()) mediaType == FormDataMediaType -> { MultipartBody.Builder() .setType(MultipartBody.FORM) @@ -119,7 +116,7 @@ open class ApiClient(val baseUrl: String) { } if (T::class.java == File::class.java) { // return tempfile - val f = Files.createTempFile("tmp.org.openapitools.client", null).toFile() + val f = java.nio.file.Files.createTempFile("tmp.org.openapitools.client", null).toFile() f.deleteOnExit() val out = BufferedWriter(FileWriter(f)) out.write(bodyContent) @@ -132,7 +129,7 @@ open class ApiClient(val baseUrl: String) { } } - protected fun updateAuthParams(requestConfig: RequestConfig) { + protected fun updateAuthParams(requestConfig: RequestConfig) { if (requestConfig.headers["api_key"].isNullOrEmpty()) { if (apiKey["api_key"] != null) { if (apiKeyPrefix["api_key"] != null) { @@ -149,7 +146,7 @@ open class ApiClient(val baseUrl: String) { } } - protected inline fun request(requestConfig: RequestConfig): ApiInfrastructureResponse { + protected inline fun request(requestConfig: RequestConfig): ApiInfrastructureResponse { val httpUrl = baseUrl.toHttpUrlOrNull() ?: throw IllegalStateException("baseUrl is invalid.") // take authMethod from operation @@ -183,7 +180,7 @@ open class ApiClient(val baseUrl: String) { } // TODO: support multiple contentType options here. - val contentType = (headers[ContentType] as String).substringBefore(";").toLowerCase() + val contentType = (headers[ContentType] as String).substringBefore(";").lowercase(Locale.getDefault()) val request = when (requestConfig.method) { RequestMethod.DELETE -> Request.Builder().url(url).delete(requestBody(requestConfig.body, contentType)) @@ -198,57 +195,46 @@ open class ApiClient(val baseUrl: String) { }.build() val response = client.newCall(request).execute() - val accept = response.header(ContentType)?.substringBefore(";")?.toLowerCase() + val accept = response.header(ContentType)?.substringBefore(";")?.lowercase(Locale.getDefault()) // TODO: handle specific mapping types. e.g. Map> - when { - response.isRedirect -> return Redirection( - response.code, - response.headers.toMultimap() + return when { + response.isRedirect -> Redirection( + response.code, + response.headers.toMultimap() ) - response.isInformational -> return Informational( - response.message, - response.code, - response.headers.toMultimap() + response.isInformational -> Informational( + response.message, + response.code, + response.headers.toMultimap() ) - response.isSuccessful -> return Success( - responseBody(response.body, accept), - response.code, - response.headers.toMultimap() + response.isSuccessful -> Success( + responseBody(response.body, accept), + response.code, + response.headers.toMultimap() ) - response.isClientError -> return ClientError( - response.message, - response.body?.string(), - response.code, - response.headers.toMultimap() + response.isClientError -> ClientError( + response.message, + response.body?.string(), + response.code, + response.headers.toMultimap() ) - else -> return ServerError( - 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 -> { - return "" - } - is Array<*> -> { - return toMultiValue(value, "csv").toString() - } - is Iterable<*> -> { - return toMultiValue(value, "csv").toString() - } - is OffsetDateTime, is OffsetTime, is LocalDateTime, is LocalDate, is LocalTime, is Date -> { - return parseDateToQueryString(value) - } - else -> { - return value.toString() - } - } + 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, is Date -> + parseDateToQueryString(value) + else -> value.toString() } protected inline fun parseDateToQueryString(value : T): String { 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 0f2790f370e..7e948e1dd07 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 @@ -8,10 +8,10 @@ package org.openapitools.client.infrastructure * NOTE: Headers is a Map because rfc2616 defines * multi-valued headers as csv-only. */ -data class RequestConfig( +data class RequestConfig( val method: RequestMethod, val path: String, val headers: MutableMap = mutableMapOf(), val query: MutableMap> = mutableMapOf(), - val body: kotlin.Any? = null + val body: T? = null ) \ No newline at end of file diff --git a/samples/client/petstore/kotlin-jackson/.openapi-generator/FILES b/samples/client/petstore/kotlin-jackson/.openapi-generator/FILES index 6bfd310bbca..816d952128d 100644 --- a/samples/client/petstore/kotlin-jackson/.openapi-generator/FILES +++ b/samples/client/petstore/kotlin-jackson/.openapi-generator/FILES @@ -20,7 +20,6 @@ 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/ApiInfrastructureResponse.kt -src/main/kotlin/org/openapitools/client/infrastructure/ApplicationDelegates.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/RequestConfig.kt diff --git a/samples/client/petstore/kotlin-jackson/.openapi-generator/VERSION b/samples/client/petstore/kotlin-jackson/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/client/petstore/kotlin-jackson/.openapi-generator/VERSION +++ b/samples/client/petstore/kotlin-jackson/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/client/petstore/kotlin-jackson/build.gradle b/samples/client/petstore/kotlin-jackson/build.gradle index 49a346f1cf9..5cbe1fb014f 100644 --- a/samples/client/petstore/kotlin-jackson/build.gradle +++ b/samples/client/petstore/kotlin-jackson/build.gradle @@ -7,7 +7,7 @@ wrapper { } buildscript { - ext.kotlin_version = '1.4.30' + ext.kotlin_version = '1.5.10' repositories { maven { url "https://repo1.maven.org/maven2" } @@ -28,10 +28,10 @@ test { } dependencies { - compile "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version" - compile "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version" - compile "com.fasterxml.jackson.module:jackson-module-kotlin:2.12.1" - compile "com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.12.1" - compile "com.squareup.okhttp3:okhttp:4.9.0" - testCompile "io.kotlintest:kotlintest-runner-junit5:3.4.2" + 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.12.3" + implementation "com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.12.3" + implementation "com.squareup.okhttp3:okhttp:4.9.1" + testImplementation "io.kotlintest:kotlintest-runner-junit5:3.4.2" } 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 c8b93b33bf6..be50dd6c442 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 @@ -47,7 +47,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun addPet(body: Pet) : Unit { val localVariableConfig = addPetRequestConfig(body = body) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -72,20 +72,18 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param body Pet object that needs to be added to the store * @return RequestConfig */ - fun addPetRequestConfig(body: Pet) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun addPetRequestConfig(body: Pet) : RequestConfig { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/pet", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -102,7 +100,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun deletePet(petId: kotlin.Long, apiKey: kotlin.String?) : Unit { val localVariableConfig = deletePetRequestConfig(petId = petId, apiKey = apiKey) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -128,21 +126,19 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param apiKey (optional) * @return RequestConfig */ - fun deletePetRequestConfig(petId: kotlin.Long, apiKey: kotlin.String?) : RequestConfig { - val localVariableBody: kotlin.Any? = null + 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() } - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.DELETE, path = "/pet/{petId}".replace("{"+"petId"+"}", "$petId"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -159,7 +155,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun findPetsByStatus(status: kotlin.collections.List) : kotlin.collections.List { val localVariableConfig = findPetsByStatusRequestConfig(status = status) - val localVarResponse = request>( + val localVarResponse = request>( localVariableConfig ) @@ -184,23 +180,21 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param status Status values that need to be considered for filter * @return RequestConfig */ - fun findPetsByStatusRequestConfig(status: kotlin.collections.List) : RequestConfig { - val localVariableBody: kotlin.Any? = null + 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() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/pet/findByStatus", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -216,9 +210,10 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { @Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class) @Deprecated(message = "This operation is deprecated.") fun findPetsByTags(tags: kotlin.collections.List) : kotlin.collections.List { + @Suppress("DEPRECATION") val localVariableConfig = findPetsByTagsRequestConfig(tags = tags) - val localVarResponse = request>( + val localVarResponse = request>( localVariableConfig ) @@ -244,23 +239,21 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @return RequestConfig */ @Deprecated(message = "This operation is deprecated.") - fun findPetsByTagsRequestConfig(tags: kotlin.collections.List) : RequestConfig { - val localVariableBody: kotlin.Any? = null + 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() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/pet/findByTags", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -277,7 +270,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun getPetById(petId: kotlin.Long) : Pet { val localVariableConfig = getPetByIdRequestConfig(petId = petId) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -302,20 +295,18 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param petId ID of pet to return * @return RequestConfig */ - fun getPetByIdRequestConfig(petId: kotlin.Long) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun getPetByIdRequestConfig(petId: kotlin.Long) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/pet/{petId}".replace("{"+"petId"+"}", "$petId"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -331,7 +322,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun updatePet(body: Pet) : Unit { val localVariableConfig = updatePetRequestConfig(body = body) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -356,20 +347,18 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param body Pet object that needs to be added to the store * @return RequestConfig */ - fun updatePetRequestConfig(body: Pet) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun updatePetRequestConfig(body: Pet) : RequestConfig { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.PUT, path = "/pet", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -387,7 +376,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun updatePetWithForm(petId: kotlin.Long, name: kotlin.String?, status: kotlin.String?) : Unit { val localVariableConfig = updatePetWithFormRequestConfig(petId = petId, name = name, status = status) - val localVarResponse = request( + val localVarResponse = request, Unit>( localVariableConfig ) @@ -414,20 +403,18 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param status Updated status of the pet (optional) * @return RequestConfig */ - fun updatePetWithFormRequestConfig(petId: kotlin.Long, name: kotlin.String?, status: kotlin.String?) : RequestConfig { - val localVariableBody: kotlin.Any? = mapOf("name" to name, "status" to status) + fun updatePetWithFormRequestConfig(petId: kotlin.Long, name: kotlin.String?, status: kotlin.String?) : RequestConfig> { + val localVariableBody = mapOf("name" to name, "status" to status) val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf("Content-Type" to "application/x-www-form-urlencoded") - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/pet/{petId}".replace("{"+"petId"+"}", "$petId"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -446,7 +433,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun uploadFile(petId: kotlin.Long, additionalMetadata: kotlin.String?, file: java.io.File?) : ApiResponse { val localVariableConfig = uploadFileRequestConfig(petId = petId, additionalMetadata = additionalMetadata, file = file) - val localVarResponse = request( + val localVarResponse = request, ApiResponse>( localVariableConfig ) @@ -473,20 +460,18 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param file file to upload (optional) * @return RequestConfig */ - fun uploadFileRequestConfig(petId: kotlin.Long, additionalMetadata: kotlin.String?, file: java.io.File?) : RequestConfig { - val localVariableBody: kotlin.Any? = mapOf("additionalMetadata" to additionalMetadata, "file" to file) + fun uploadFileRequestConfig(petId: kotlin.Long, additionalMetadata: kotlin.String?, file: java.io.File?) : RequestConfig> { + val localVariableBody = mapOf("additionalMetadata" to additionalMetadata, "file" to file) val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf("Content-Type" to "multipart/form-data") - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/pet/{petId}/uploadImage".replace("{"+"petId"+"}", "$petId"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } } diff --git a/samples/client/petstore/kotlin-jackson/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt b/samples/client/petstore/kotlin-jackson/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt index 215ed63420c..56a23202f82 100644 --- a/samples/client/petstore/kotlin-jackson/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt +++ b/samples/client/petstore/kotlin-jackson/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt @@ -46,7 +46,7 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) fun deleteOrder(orderId: kotlin.String) : Unit { val localVariableConfig = deleteOrderRequestConfig(orderId = orderId) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -71,20 +71,18 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) * @param orderId ID of the order that needs to be deleted * @return RequestConfig */ - fun deleteOrderRequestConfig(orderId: kotlin.String) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun deleteOrderRequestConfig(orderId: kotlin.String) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.DELETE, path = "/store/order/{orderId}".replace("{"+"orderId"+"}", "$orderId"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -100,7 +98,7 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) fun getInventory() : kotlin.collections.Map { val localVariableConfig = getInventoryRequestConfig() - val localVarResponse = request>( + val localVarResponse = request>( localVariableConfig ) @@ -124,20 +122,18 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) * * @return RequestConfig */ - fun getInventoryRequestConfig() : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun getInventoryRequestConfig() : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/store/inventory", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -154,7 +150,7 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) fun getOrderById(orderId: kotlin.Long) : Order { val localVariableConfig = getOrderByIdRequestConfig(orderId = orderId) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -179,20 +175,18 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) * @param orderId ID of pet that needs to be fetched * @return RequestConfig */ - fun getOrderByIdRequestConfig(orderId: kotlin.Long) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun getOrderByIdRequestConfig(orderId: kotlin.Long) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/store/order/{orderId}".replace("{"+"orderId"+"}", "$orderId"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -209,7 +203,7 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) fun placeOrder(body: Order) : Order { val localVariableConfig = placeOrderRequestConfig(body = body) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -234,20 +228,18 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) * @param body order placed for purchasing the pet * @return RequestConfig */ - fun placeOrderRequestConfig(body: Order) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun placeOrderRequestConfig(body: Order) : RequestConfig { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/store/order", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } } diff --git a/samples/client/petstore/kotlin-jackson/src/main/kotlin/org/openapitools/client/apis/UserApi.kt b/samples/client/petstore/kotlin-jackson/src/main/kotlin/org/openapitools/client/apis/UserApi.kt index 53748b93463..9f93e853a12 100644 --- a/samples/client/petstore/kotlin-jackson/src/main/kotlin/org/openapitools/client/apis/UserApi.kt +++ b/samples/client/petstore/kotlin-jackson/src/main/kotlin/org/openapitools/client/apis/UserApi.kt @@ -46,7 +46,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun createUser(body: User) : Unit { val localVariableConfig = createUserRequestConfig(body = body) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -71,20 +71,18 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param body Created user object * @return RequestConfig */ - fun createUserRequestConfig(body: User) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun createUserRequestConfig(body: User) : RequestConfig { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/user", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -100,7 +98,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun createUsersWithArrayInput(body: kotlin.collections.List) : Unit { val localVariableConfig = createUsersWithArrayInputRequestConfig(body = body) - val localVarResponse = request( + val localVarResponse = request, Unit>( localVariableConfig ) @@ -125,20 +123,18 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param body List of user object * @return RequestConfig */ - fun createUsersWithArrayInputRequestConfig(body: kotlin.collections.List) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun createUsersWithArrayInputRequestConfig(body: kotlin.collections.List) : RequestConfig> { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/user/createWithArray", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -154,7 +150,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun createUsersWithListInput(body: kotlin.collections.List) : Unit { val localVariableConfig = createUsersWithListInputRequestConfig(body = body) - val localVarResponse = request( + val localVarResponse = request, Unit>( localVariableConfig ) @@ -179,20 +175,18 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param body List of user object * @return RequestConfig */ - fun createUsersWithListInputRequestConfig(body: kotlin.collections.List) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun createUsersWithListInputRequestConfig(body: kotlin.collections.List) : RequestConfig> { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/user/createWithList", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -208,7 +202,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun deleteUser(username: kotlin.String) : Unit { val localVariableConfig = deleteUserRequestConfig(username = username) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -233,20 +227,18 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param username The name that needs to be deleted * @return RequestConfig */ - fun deleteUserRequestConfig(username: kotlin.String) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun deleteUserRequestConfig(username: kotlin.String) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.DELETE, path = "/user/{username}".replace("{"+"username"+"}", "$username"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -263,7 +255,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun getUserByName(username: kotlin.String) : User { val localVariableConfig = getUserByNameRequestConfig(username = username) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -288,20 +280,18 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param username The name that needs to be fetched. Use user1 for testing. * @return RequestConfig */ - fun getUserByNameRequestConfig(username: kotlin.String) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun getUserByNameRequestConfig(username: kotlin.String) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/user/{username}".replace("{"+"username"+"}", "$username"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -319,7 +309,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun loginUser(username: kotlin.String, password: kotlin.String) : kotlin.String { val localVariableConfig = loginUserRequestConfig(username = username, password = password) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -345,24 +335,22 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param password The password for login in clear text * @return RequestConfig */ - fun loginUserRequestConfig(username: kotlin.String, password: kotlin.String) : RequestConfig { - val localVariableBody: kotlin.Any? = null + 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() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/user/login", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -377,7 +365,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun logoutUser() : Unit { val localVariableConfig = logoutUserRequestConfig() - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -401,20 +389,18 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * * @return RequestConfig */ - fun logoutUserRequestConfig() : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun logoutUserRequestConfig() : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/user/logout", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -431,7 +417,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun updateUser(username: kotlin.String, body: User) : Unit { val localVariableConfig = updateUserRequestConfig(username = username, body = body) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -457,20 +443,18 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param body Updated user object * @return RequestConfig */ - fun updateUserRequestConfig(username: kotlin.String, body: User) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun updateUserRequestConfig(username: kotlin.String, body: User) : RequestConfig { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.PUT, path = "/user/{username}".replace("{"+"username"+"}", "$username"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } } 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 0ea33dc522c..6cf2ef9b0d1 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 @@ -1,6 +1,5 @@ package org.openapitools.client.infrastructure -import okhttp3.Credentials import okhttp3.OkHttpClient import okhttp3.RequestBody import okhttp3.RequestBody.Companion.asRequestBody @@ -12,17 +11,17 @@ import okhttp3.MediaType.Companion.toMediaTypeOrNull import okhttp3.Request import okhttp3.Headers import okhttp3.MultipartBody -import java.io.File import java.io.BufferedWriter +import java.io.File import java.io.FileWriter import java.net.URLConnection -import java.nio.file.Files -import java.util.Date import java.time.LocalDate import java.time.LocalDateTime import java.time.LocalTime import java.time.OffsetDateTime import java.time.OffsetTime +import java.util.Date +import java.util.Locale open class ApiClient(val baseUrl: String) { companion object { @@ -62,9 +61,7 @@ open class ApiClient(val baseUrl: String) { protected inline fun requestBody(content: T, mediaType: String = JsonMediaType): RequestBody = when { - content is File -> content.asRequestBody( - mediaType.toMediaTypeOrNull() - ) + content is File -> content.asRequestBody(mediaType.toMediaTypeOrNull()) mediaType == FormDataMediaType -> { MultipartBody.Builder() .setType(MultipartBody.FORM) @@ -119,7 +116,7 @@ open class ApiClient(val baseUrl: String) { } if (T::class.java == File::class.java) { // return tempfile - val f = Files.createTempFile("tmp.org.openapitools.client", null).toFile() + val f = java.nio.file.Files.createTempFile("tmp.org.openapitools.client", null).toFile() f.deleteOnExit() val out = BufferedWriter(FileWriter(f)) out.write(bodyContent) @@ -132,7 +129,7 @@ open class ApiClient(val baseUrl: String) { } } - protected fun updateAuthParams(requestConfig: RequestConfig) { + protected fun updateAuthParams(requestConfig: RequestConfig) { if (requestConfig.headers["api_key"].isNullOrEmpty()) { if (apiKey["api_key"] != null) { if (apiKeyPrefix["api_key"] != null) { @@ -149,7 +146,7 @@ open class ApiClient(val baseUrl: String) { } } - protected inline fun request(requestConfig: RequestConfig): ApiInfrastructureResponse { + protected inline fun request(requestConfig: RequestConfig): ApiInfrastructureResponse { val httpUrl = baseUrl.toHttpUrlOrNull() ?: throw IllegalStateException("baseUrl is invalid.") // take authMethod from operation @@ -183,7 +180,7 @@ open class ApiClient(val baseUrl: String) { } // TODO: support multiple contentType options here. - val contentType = (headers[ContentType] as String).substringBefore(";").toLowerCase() + val contentType = (headers[ContentType] as String).substringBefore(";").lowercase(Locale.getDefault()) val request = when (requestConfig.method) { RequestMethod.DELETE -> Request.Builder().url(url).delete(requestBody(requestConfig.body, contentType)) @@ -198,57 +195,46 @@ open class ApiClient(val baseUrl: String) { }.build() val response = client.newCall(request).execute() - val accept = response.header(ContentType)?.substringBefore(";")?.toLowerCase() + val accept = response.header(ContentType)?.substringBefore(";")?.lowercase(Locale.getDefault()) // TODO: handle specific mapping types. e.g. Map> - when { - response.isRedirect -> return Redirection( - response.code, - response.headers.toMultimap() + return when { + response.isRedirect -> Redirection( + response.code, + response.headers.toMultimap() ) - response.isInformational -> return Informational( - response.message, - response.code, - response.headers.toMultimap() + response.isInformational -> Informational( + response.message, + response.code, + response.headers.toMultimap() ) - response.isSuccessful -> return Success( - responseBody(response.body, accept), - response.code, - response.headers.toMultimap() + response.isSuccessful -> Success( + responseBody(response.body, accept), + response.code, + response.headers.toMultimap() ) - response.isClientError -> return ClientError( - response.message, - response.body?.string(), - response.code, - response.headers.toMultimap() + response.isClientError -> ClientError( + response.message, + response.body?.string(), + response.code, + response.headers.toMultimap() ) - else -> return ServerError( - 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 -> { - return "" - } - is Array<*> -> { - return toMultiValue(value, "csv").toString() - } - is Iterable<*> -> { - return toMultiValue(value, "csv").toString() - } - is OffsetDateTime, is OffsetTime, is LocalDateTime, is LocalDate, is LocalTime, is Date -> { - return parseDateToQueryString(value) - } - else -> { - return value.toString() - } - } + 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, is Date -> + parseDateToQueryString(value) + else -> value.toString() } protected inline fun parseDateToQueryString(value : T): String { 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 0f2790f370e..7e948e1dd07 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 @@ -8,10 +8,10 @@ package org.openapitools.client.infrastructure * NOTE: Headers is a Map because rfc2616 defines * multi-valued headers as csv-only. */ -data class RequestConfig( +data class RequestConfig( val method: RequestMethod, val path: String, val headers: MutableMap = mutableMapOf(), val query: MutableMap> = mutableMapOf(), - val body: kotlin.Any? = null + val body: T? = null ) \ No newline at end of file diff --git a/samples/client/petstore/kotlin-json-request-string/.openapi-generator/FILES b/samples/client/petstore/kotlin-json-request-string/.openapi-generator/FILES index 3f4610174cc..16c712325f8 100644 --- a/samples/client/petstore/kotlin-json-request-string/.openapi-generator/FILES +++ b/samples/client/petstore/kotlin-json-request-string/.openapi-generator/FILES @@ -20,7 +20,6 @@ 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/ApiInfrastructureResponse.kt -src/main/kotlin/org/openapitools/client/infrastructure/ApplicationDelegates.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 @@ -32,6 +31,7 @@ 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/ApiResponse.kt src/main/kotlin/org/openapitools/client/models/Category.kt 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 5f68295fc19..e8415097f3a 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,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/client/petstore/kotlin-json-request-string/build.gradle b/samples/client/petstore/kotlin-json-request-string/build.gradle index 4e47e29cc51..189e54f8195 100644 --- a/samples/client/petstore/kotlin-json-request-string/build.gradle +++ b/samples/client/petstore/kotlin-json-request-string/build.gradle @@ -7,7 +7,7 @@ wrapper { } buildscript { - ext.kotlin_version = '1.4.30' + ext.kotlin_version = '1.5.10' repositories { maven { url "https://repo1.maven.org/maven2" } @@ -29,9 +29,9 @@ test { } dependencies { - compile "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version" - compile "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version" - compile "com.squareup.moshi:moshi-kotlin:1.11.0" - compile "com.squareup.okhttp3:okhttp:4.9.0" - testCompile "io.kotlintest:kotlintest-runner-junit5:3.4.2" + implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version" + implementation "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version" + implementation "com.squareup.moshi:moshi-kotlin:1.12.0" + implementation "com.squareup.okhttp3:okhttp:4.9.1" + testImplementation "io.kotlintest:kotlintest-runner-junit5:3.4.2" } diff --git a/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/apis/PetApi.kt b/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/apis/PetApi.kt index d939e3d5a43..cb784ddba8b 100644 --- a/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/apis/PetApi.kt +++ b/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/apis/PetApi.kt @@ -47,7 +47,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun addPet(body: Pet) : Unit { val localVariableConfig = addPetRequestConfig(body = body) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -72,20 +72,18 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param body Pet object that needs to be added to the store * @return RequestConfig */ - fun addPetRequestConfig(body: Pet) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun addPetRequestConfig(body: Pet) : RequestConfig { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/pet", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -102,7 +100,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun deletePet(petId: kotlin.Long, apiKey: kotlin.String?) : Unit { val localVariableConfig = deletePetRequestConfig(petId = petId, apiKey = apiKey) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -128,21 +126,19 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param apiKey (optional) * @return RequestConfig */ - fun deletePetRequestConfig(petId: kotlin.Long, apiKey: kotlin.String?) : RequestConfig { - val localVariableBody: kotlin.Any? = null + 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() } - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.DELETE, path = "/pet/{petId}".replace("{"+"petId"+"}", "$petId"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -158,9 +154,10 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { @Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class) @Deprecated(message = "This operation is deprecated.") fun findPetsByTags(tags: kotlin.collections.List) : kotlin.collections.List { + @Suppress("DEPRECATION") val localVariableConfig = findPetsByTagsRequestConfig(tags = tags) - val localVarResponse = request>( + val localVarResponse = request>( localVariableConfig ) @@ -186,23 +183,21 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @return RequestConfig */ @Deprecated(message = "This operation is deprecated.") - fun findPetsByTagsRequestConfig(tags: kotlin.collections.List) : RequestConfig { - val localVariableBody: kotlin.Any? = null + 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() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/pet/findByTags", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -219,7 +214,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun getAllPets(lastUpdated: java.time.OffsetDateTime?) : kotlin.collections.List { val localVariableConfig = getAllPetsRequestConfig(lastUpdated = lastUpdated) - val localVarResponse = request>( + val localVarResponse = request>( localVariableConfig ) @@ -244,8 +239,8 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param lastUpdated When this endpoint was hit last to help indentify if the client already has the latest copy. (optional) * @return RequestConfig */ - fun getAllPetsRequestConfig(lastUpdated: java.time.OffsetDateTime?) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun getAllPetsRequestConfig(lastUpdated: java.time.OffsetDateTime?) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf>() .apply { if (lastUpdated != null) { @@ -253,16 +248,14 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { } } val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/pet/getAll", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -279,7 +272,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun getPetById(petId: kotlin.Long) : Pet { val localVariableConfig = getPetByIdRequestConfig(petId = petId) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -304,20 +297,18 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param petId ID of pet to return * @return RequestConfig */ - fun getPetByIdRequestConfig(petId: kotlin.Long) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun getPetByIdRequestConfig(petId: kotlin.Long) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/pet/{petId}".replace("{"+"petId"+"}", "$petId"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -333,7 +324,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun updatePet(body: Pet) : Unit { val localVariableConfig = updatePetRequestConfig(body = body) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -358,20 +349,18 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param body Pet object that needs to be added to the store * @return RequestConfig */ - fun updatePetRequestConfig(body: Pet) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun updatePetRequestConfig(body: Pet) : RequestConfig { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.PUT, path = "/pet", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -389,7 +378,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun updatePetWithForm(petId: kotlin.Long, name: kotlin.String?, status: kotlin.String?) : Unit { val localVariableConfig = updatePetWithFormRequestConfig(petId = petId, name = name, status = status) - val localVarResponse = request( + val localVarResponse = request, Unit>( localVariableConfig ) @@ -416,20 +405,18 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param status Updated status of the pet (optional) * @return RequestConfig */ - fun updatePetWithFormRequestConfig(petId: kotlin.Long, name: kotlin.String?, status: kotlin.String?) : RequestConfig { - val localVariableBody: kotlin.Any? = mapOf("name" to name, "status" to status) + fun updatePetWithFormRequestConfig(petId: kotlin.Long, name: kotlin.String?, status: kotlin.String?) : RequestConfig> { + val localVariableBody = mapOf("name" to name, "status" to status) val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf("Content-Type" to "application/x-www-form-urlencoded") - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/pet/{petId}".replace("{"+"petId"+"}", "$petId"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -448,7 +435,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun uploadFile(petId: kotlin.Long, additionalMetadata: kotlin.String?, file: java.io.File?) : ApiResponse { val localVariableConfig = uploadFileRequestConfig(petId = petId, additionalMetadata = additionalMetadata, file = file) - val localVarResponse = request( + val localVarResponse = request, ApiResponse>( localVariableConfig ) @@ -475,20 +462,18 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param file file to upload (optional) * @return RequestConfig */ - fun uploadFileRequestConfig(petId: kotlin.Long, additionalMetadata: kotlin.String?, file: java.io.File?) : RequestConfig { - val localVariableBody: kotlin.Any? = mapOf("additionalMetadata" to additionalMetadata, "file" to file) + fun uploadFileRequestConfig(petId: kotlin.Long, additionalMetadata: kotlin.String?, file: java.io.File?) : RequestConfig> { + val localVariableBody = mapOf("additionalMetadata" to additionalMetadata, "file" to file) val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf("Content-Type" to "multipart/form-data") - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/pet/{petId}/uploadImage".replace("{"+"petId"+"}", "$petId"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } } diff --git a/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt b/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt index 215ed63420c..56a23202f82 100644 --- a/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt +++ b/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt @@ -46,7 +46,7 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) fun deleteOrder(orderId: kotlin.String) : Unit { val localVariableConfig = deleteOrderRequestConfig(orderId = orderId) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -71,20 +71,18 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) * @param orderId ID of the order that needs to be deleted * @return RequestConfig */ - fun deleteOrderRequestConfig(orderId: kotlin.String) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun deleteOrderRequestConfig(orderId: kotlin.String) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.DELETE, path = "/store/order/{orderId}".replace("{"+"orderId"+"}", "$orderId"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -100,7 +98,7 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) fun getInventory() : kotlin.collections.Map { val localVariableConfig = getInventoryRequestConfig() - val localVarResponse = request>( + val localVarResponse = request>( localVariableConfig ) @@ -124,20 +122,18 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) * * @return RequestConfig */ - fun getInventoryRequestConfig() : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun getInventoryRequestConfig() : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/store/inventory", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -154,7 +150,7 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) fun getOrderById(orderId: kotlin.Long) : Order { val localVariableConfig = getOrderByIdRequestConfig(orderId = orderId) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -179,20 +175,18 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) * @param orderId ID of pet that needs to be fetched * @return RequestConfig */ - fun getOrderByIdRequestConfig(orderId: kotlin.Long) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun getOrderByIdRequestConfig(orderId: kotlin.Long) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/store/order/{orderId}".replace("{"+"orderId"+"}", "$orderId"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -209,7 +203,7 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) fun placeOrder(body: Order) : Order { val localVariableConfig = placeOrderRequestConfig(body = body) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -234,20 +228,18 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) * @param body order placed for purchasing the pet * @return RequestConfig */ - fun placeOrderRequestConfig(body: Order) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun placeOrderRequestConfig(body: Order) : RequestConfig { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/store/order", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } } diff --git a/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/apis/UserApi.kt b/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/apis/UserApi.kt index 53748b93463..9f93e853a12 100644 --- a/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/apis/UserApi.kt +++ b/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/apis/UserApi.kt @@ -46,7 +46,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun createUser(body: User) : Unit { val localVariableConfig = createUserRequestConfig(body = body) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -71,20 +71,18 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param body Created user object * @return RequestConfig */ - fun createUserRequestConfig(body: User) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun createUserRequestConfig(body: User) : RequestConfig { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/user", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -100,7 +98,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun createUsersWithArrayInput(body: kotlin.collections.List) : Unit { val localVariableConfig = createUsersWithArrayInputRequestConfig(body = body) - val localVarResponse = request( + val localVarResponse = request, Unit>( localVariableConfig ) @@ -125,20 +123,18 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param body List of user object * @return RequestConfig */ - fun createUsersWithArrayInputRequestConfig(body: kotlin.collections.List) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun createUsersWithArrayInputRequestConfig(body: kotlin.collections.List) : RequestConfig> { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/user/createWithArray", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -154,7 +150,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun createUsersWithListInput(body: kotlin.collections.List) : Unit { val localVariableConfig = createUsersWithListInputRequestConfig(body = body) - val localVarResponse = request( + val localVarResponse = request, Unit>( localVariableConfig ) @@ -179,20 +175,18 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param body List of user object * @return RequestConfig */ - fun createUsersWithListInputRequestConfig(body: kotlin.collections.List) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun createUsersWithListInputRequestConfig(body: kotlin.collections.List) : RequestConfig> { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/user/createWithList", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -208,7 +202,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun deleteUser(username: kotlin.String) : Unit { val localVariableConfig = deleteUserRequestConfig(username = username) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -233,20 +227,18 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param username The name that needs to be deleted * @return RequestConfig */ - fun deleteUserRequestConfig(username: kotlin.String) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun deleteUserRequestConfig(username: kotlin.String) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.DELETE, path = "/user/{username}".replace("{"+"username"+"}", "$username"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -263,7 +255,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun getUserByName(username: kotlin.String) : User { val localVariableConfig = getUserByNameRequestConfig(username = username) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -288,20 +280,18 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param username The name that needs to be fetched. Use user1 for testing. * @return RequestConfig */ - fun getUserByNameRequestConfig(username: kotlin.String) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun getUserByNameRequestConfig(username: kotlin.String) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/user/{username}".replace("{"+"username"+"}", "$username"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -319,7 +309,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun loginUser(username: kotlin.String, password: kotlin.String) : kotlin.String { val localVariableConfig = loginUserRequestConfig(username = username, password = password) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -345,24 +335,22 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param password The password for login in clear text * @return RequestConfig */ - fun loginUserRequestConfig(username: kotlin.String, password: kotlin.String) : RequestConfig { - val localVariableBody: kotlin.Any? = null + 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() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/user/login", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -377,7 +365,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun logoutUser() : Unit { val localVariableConfig = logoutUserRequestConfig() - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -401,20 +389,18 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * * @return RequestConfig */ - fun logoutUserRequestConfig() : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun logoutUserRequestConfig() : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/user/logout", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -431,7 +417,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun updateUser(username: kotlin.String, body: User) : Unit { val localVariableConfig = updateUserRequestConfig(username = username, body = body) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -457,20 +443,18 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param body Updated user object * @return RequestConfig */ - fun updateUserRequestConfig(username: kotlin.String, body: User) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun updateUserRequestConfig(username: kotlin.String, body: User) : RequestConfig { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.PUT, path = "/user/{username}".replace("{"+"username"+"}", "$username"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } } 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 cd2898923dd..fc157890883 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 @@ -1,6 +1,6 @@ package org.openapitools.client.infrastructure -import okhttp3.Credentials +import android.os.Build import okhttp3.OkHttpClient import okhttp3.RequestBody import okhttp3.RequestBody.Companion.asRequestBody @@ -12,17 +12,17 @@ import okhttp3.MediaType.Companion.toMediaTypeOrNull import okhttp3.Request import okhttp3.Headers import okhttp3.MultipartBody -import java.io.File import java.io.BufferedWriter +import java.io.File import java.io.FileWriter import java.net.URLConnection -import java.nio.file.Files -import java.util.Date import java.time.LocalDate import java.time.LocalDateTime import java.time.LocalTime import java.time.OffsetDateTime import java.time.OffsetTime +import java.util.Date +import java.util.Locale open class ApiClient(val baseUrl: String) { companion object { @@ -62,9 +62,7 @@ open class ApiClient(val baseUrl: String) { protected inline fun requestBody(content: T, mediaType: String = JsonMediaType): RequestBody = when { - content is File -> content.asRequestBody( - mediaType.toMediaTypeOrNull() - ) + content is File -> content.asRequestBody(mediaType.toMediaTypeOrNull()) mediaType == FormDataMediaType -> { MultipartBody.Builder() .setType(MultipartBody.FORM) @@ -119,7 +117,12 @@ open class ApiClient(val baseUrl: String) { } if (T::class.java == File::class.java) { // return tempfile - val f = Files.createTempFile("tmp.org.openapitools.client", null).toFile() + val f = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { + java.nio.file.Files.createTempFile("tmp.net.medicineone.teleconsultationandroid.openapi.openapicommon", null).toFile() + } else { + @Suppress("DEPRECATION") + createTempFile("tmp.net.medicineone.teleconsultationandroid.openapi.openapicommon", null) + } f.deleteOnExit() val out = BufferedWriter(FileWriter(f)) out.write(bodyContent) @@ -132,7 +135,7 @@ open class ApiClient(val baseUrl: String) { } } - protected fun updateAuthParams(requestConfig: RequestConfig) { + protected fun updateAuthParams(requestConfig: RequestConfig) { if (requestConfig.headers["api_key"].isNullOrEmpty()) { if (apiKey["api_key"] != null) { if (apiKeyPrefix["api_key"] != null) { @@ -149,7 +152,7 @@ open class ApiClient(val baseUrl: String) { } } - protected inline fun request(requestConfig: RequestConfig): ApiInfrastructureResponse { + protected inline fun request(requestConfig: RequestConfig): ApiInfrastructureResponse { val httpUrl = baseUrl.toHttpUrlOrNull() ?: throw IllegalStateException("baseUrl is invalid.") // take authMethod from operation @@ -183,7 +186,7 @@ open class ApiClient(val baseUrl: String) { } // TODO: support multiple contentType options here. - val contentType = (headers[ContentType] as String).substringBefore(";").toLowerCase() + val contentType = (headers[ContentType] as String).substringBefore(";").lowercase(Locale.getDefault()) val request = when (requestConfig.method) { RequestMethod.DELETE -> Request.Builder().url(url).delete(requestBody(requestConfig.body, contentType)) @@ -198,57 +201,46 @@ open class ApiClient(val baseUrl: String) { }.build() val response = client.newCall(request).execute() - val accept = response.header(ContentType)?.substringBefore(";")?.toLowerCase() + val accept = response.header(ContentType)?.substringBefore(";")?.lowercase(Locale.getDefault()) // TODO: handle specific mapping types. e.g. Map> - when { - response.isRedirect -> return Redirection( - response.code, - response.headers.toMultimap() + return when { + response.isRedirect -> Redirection( + response.code, + response.headers.toMultimap() ) - response.isInformational -> return Informational( - response.message, - response.code, - response.headers.toMultimap() + response.isInformational -> Informational( + response.message, + response.code, + response.headers.toMultimap() ) - response.isSuccessful -> return Success( - responseBody(response.body, accept), - response.code, - response.headers.toMultimap() + response.isSuccessful -> Success( + responseBody(response.body, accept), + response.code, + response.headers.toMultimap() ) - response.isClientError -> return ClientError( - response.message, - response.body?.string(), - response.code, - response.headers.toMultimap() + response.isClientError -> ClientError( + response.message, + response.body?.string(), + response.code, + response.headers.toMultimap() ) - else -> return ServerError( - 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 -> { - return "" - } - is Array<*> -> { - return toMultiValue(value, "csv").toString() - } - is Iterable<*> -> { - return toMultiValue(value, "csv").toString() - } - is OffsetDateTime, is OffsetTime, is LocalDateTime, is LocalDate, is LocalTime, is Date -> { - return parseDateToQueryString(value) - } - else -> { - return value.toString() - } - } + 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, is Date -> + parseDateToQueryString(value) + else -> value.toString() } protected inline fun parseDateToQueryString(value : T): String { 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 0f2790f370e..7e948e1dd07 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 @@ -8,10 +8,10 @@ package org.openapitools.client.infrastructure * NOTE: Headers is a Map because rfc2616 defines * multi-valued headers as csv-only. */ -data class RequestConfig( +data class RequestConfig( val method: RequestMethod, val path: String, val headers: MutableMap = mutableMapOf(), val query: MutableMap> = mutableMapOf(), - val body: kotlin.Any? = null + val body: T? = null ) \ No newline at end of file diff --git a/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt b/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt index 3d0a6c32566..e77581231c3 100644 --- a/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt +++ b/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt @@ -12,6 +12,7 @@ object Serializer { .add(LocalDateAdapter()) .add(UUIDAdapter()) .add(ByteArrayAdapter()) + .add(URIAdapter()) .add(KotlinJsonAdapterFactory()) .add(BigDecimalAdapter()) .add(BigIntegerAdapter()) diff --git a/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/infrastructure/URIAdapter.kt b/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/infrastructure/URIAdapter.kt new file mode 100644 index 00000000000..927522757da --- /dev/null +++ b/samples/client/petstore/kotlin-json-request-string/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-json-request-string/src/main/kotlin/org/openapitools/client/infrastructure/UUIDAdapter.kt b/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/infrastructure/UUIDAdapter.kt index a4a44cc18b7..7ccf7dc25d2 100644 --- a/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/infrastructure/UUIDAdapter.kt +++ b/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/infrastructure/UUIDAdapter.kt @@ -9,5 +9,5 @@ class UUIDAdapter { fun toJson(uuid: UUID) = uuid.toString() @FromJson - fun fromJson(s: String) = UUID.fromString(s) + fun fromJson(s: String): UUID = UUID.fromString(s) } diff --git a/samples/client/petstore/kotlin-jvm-okhttp4-coroutines/.openapi-generator/FILES b/samples/client/petstore/kotlin-jvm-okhttp4-coroutines/.openapi-generator/FILES index bf441309074..1f38d3fbe2d 100644 --- a/samples/client/petstore/kotlin-jvm-okhttp4-coroutines/.openapi-generator/FILES +++ b/samples/client/petstore/kotlin-jvm-okhttp4-coroutines/.openapi-generator/FILES @@ -20,7 +20,6 @@ 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/ApiInfrastructureResponse.kt -src/main/kotlin/org/openapitools/client/infrastructure/ApplicationDelegates.kt src/main/kotlin/org/openapitools/client/infrastructure/ByteArrayAdapter.kt src/main/kotlin/org/openapitools/client/infrastructure/DateAdapter.kt src/main/kotlin/org/openapitools/client/infrastructure/Errors.kt 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 5f68295fc19..e8415097f3a 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,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/client/petstore/kotlin-jvm-okhttp4-coroutines/build.gradle b/samples/client/petstore/kotlin-jvm-okhttp4-coroutines/build.gradle index ae150592cbb..5cad8581cb6 100644 --- a/samples/client/petstore/kotlin-jvm-okhttp4-coroutines/build.gradle +++ b/samples/client/petstore/kotlin-jvm-okhttp4-coroutines/build.gradle @@ -7,7 +7,7 @@ wrapper { } buildscript { - ext.kotlin_version = '1.4.30' + ext.kotlin_version = '1.5.10' repositories { maven { url "https://repo1.maven.org/maven2" } @@ -28,8 +28,8 @@ test { } dependencies { - compile "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version" - compile "com.google.code.gson:gson:2.8.6" - compile "com.squareup.okhttp3:okhttp:4.9.0" - testCompile "io.kotlintest:kotlintest-runner-junit5:3.4.2" + implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version" + implementation "com.google.code.gson:gson:2.8.7" + implementation "com.squareup.okhttp3:okhttp:4.9.1" + testImplementation "io.kotlintest:kotlintest-runner-junit5:3.4.2" } diff --git a/samples/client/petstore/kotlin-jvm-okhttp4-coroutines/src/main/kotlin/org/openapitools/client/apis/PetApi.kt b/samples/client/petstore/kotlin-jvm-okhttp4-coroutines/src/main/kotlin/org/openapitools/client/apis/PetApi.kt index 78223583f64..74174279b14 100644 --- a/samples/client/petstore/kotlin-jvm-okhttp4-coroutines/src/main/kotlin/org/openapitools/client/apis/PetApi.kt +++ b/samples/client/petstore/kotlin-jvm-okhttp4-coroutines/src/main/kotlin/org/openapitools/client/apis/PetApi.kt @@ -47,7 +47,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { suspend fun addPet(body: Pet) : Unit { val localVariableConfig = addPetRequestConfig(body = body) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -72,20 +72,18 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param body Pet object that needs to be added to the store * @return RequestConfig */ - fun addPetRequestConfig(body: Pet) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun addPetRequestConfig(body: Pet) : RequestConfig { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/pet", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -102,7 +100,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { suspend fun deletePet(petId: kotlin.Long, apiKey: kotlin.String?) : Unit { val localVariableConfig = deletePetRequestConfig(petId = petId, apiKey = apiKey) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -128,21 +126,19 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param apiKey (optional) * @return RequestConfig */ - fun deletePetRequestConfig(petId: kotlin.Long, apiKey: kotlin.String?) : RequestConfig { - val localVariableBody: kotlin.Any? = null + 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() } - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.DELETE, path = "/pet/{petId}".replace("{"+"petId"+"}", "$petId"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -159,7 +155,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { suspend fun findPetsByStatus(status: kotlin.collections.List) : kotlin.collections.List { val localVariableConfig = findPetsByStatusRequestConfig(status = status) - val localVarResponse = request>( + val localVarResponse = request>( localVariableConfig ) @@ -184,23 +180,21 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param status Status values that need to be considered for filter * @return RequestConfig */ - fun findPetsByStatusRequestConfig(status: kotlin.collections.List) : RequestConfig { - val localVariableBody: kotlin.Any? = null + 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() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/pet/findByStatus", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -216,9 +210,10 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { @Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class) @Deprecated(message = "This operation is deprecated.") suspend fun findPetsByTags(tags: kotlin.collections.List) : kotlin.collections.List { + @Suppress("DEPRECATION") val localVariableConfig = findPetsByTagsRequestConfig(tags = tags) - val localVarResponse = request>( + val localVarResponse = request>( localVariableConfig ) @@ -244,23 +239,21 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @return RequestConfig */ @Deprecated(message = "This operation is deprecated.") - fun findPetsByTagsRequestConfig(tags: kotlin.collections.List) : RequestConfig { - val localVariableBody: kotlin.Any? = null + 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() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/pet/findByTags", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -277,7 +270,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { suspend fun getPetById(petId: kotlin.Long) : Pet { val localVariableConfig = getPetByIdRequestConfig(petId = petId) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -302,20 +295,18 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param petId ID of pet to return * @return RequestConfig */ - fun getPetByIdRequestConfig(petId: kotlin.Long) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun getPetByIdRequestConfig(petId: kotlin.Long) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/pet/{petId}".replace("{"+"petId"+"}", "$petId"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -331,7 +322,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { suspend fun updatePet(body: Pet) : Unit { val localVariableConfig = updatePetRequestConfig(body = body) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -356,20 +347,18 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param body Pet object that needs to be added to the store * @return RequestConfig */ - fun updatePetRequestConfig(body: Pet) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun updatePetRequestConfig(body: Pet) : RequestConfig { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.PUT, path = "/pet", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -387,7 +376,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { suspend fun updatePetWithForm(petId: kotlin.Long, name: kotlin.String?, status: kotlin.String?) : Unit { val localVariableConfig = updatePetWithFormRequestConfig(petId = petId, name = name, status = status) - val localVarResponse = request( + val localVarResponse = request, Unit>( localVariableConfig ) @@ -414,20 +403,18 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param status Updated status of the pet (optional) * @return RequestConfig */ - fun updatePetWithFormRequestConfig(petId: kotlin.Long, name: kotlin.String?, status: kotlin.String?) : RequestConfig { - val localVariableBody: kotlin.Any? = mapOf("name" to name, "status" to status) + fun updatePetWithFormRequestConfig(petId: kotlin.Long, name: kotlin.String?, status: kotlin.String?) : RequestConfig> { + val localVariableBody = mapOf("name" to name, "status" to status) val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf("Content-Type" to "application/x-www-form-urlencoded") - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/pet/{petId}".replace("{"+"petId"+"}", "$petId"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -446,7 +433,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { suspend fun uploadFile(petId: kotlin.Long, additionalMetadata: kotlin.String?, file: java.io.File?) : ApiResponse { val localVariableConfig = uploadFileRequestConfig(petId = petId, additionalMetadata = additionalMetadata, file = file) - val localVarResponse = request( + val localVarResponse = request, ApiResponse>( localVariableConfig ) @@ -473,20 +460,18 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param file file to upload (optional) * @return RequestConfig */ - fun uploadFileRequestConfig(petId: kotlin.Long, additionalMetadata: kotlin.String?, file: java.io.File?) : RequestConfig { - val localVariableBody: kotlin.Any? = mapOf("additionalMetadata" to additionalMetadata, "file" to file) + fun uploadFileRequestConfig(petId: kotlin.Long, additionalMetadata: kotlin.String?, file: java.io.File?) : RequestConfig> { + val localVariableBody = mapOf("additionalMetadata" to additionalMetadata, "file" to file) val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf("Content-Type" to "multipart/form-data") - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/pet/{petId}/uploadImage".replace("{"+"petId"+"}", "$petId"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } } diff --git a/samples/client/petstore/kotlin-jvm-okhttp4-coroutines/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt b/samples/client/petstore/kotlin-jvm-okhttp4-coroutines/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt index 4ab794d6608..e4ed2245f6f 100644 --- a/samples/client/petstore/kotlin-jvm-okhttp4-coroutines/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt +++ b/samples/client/petstore/kotlin-jvm-okhttp4-coroutines/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt @@ -46,7 +46,7 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) suspend fun deleteOrder(orderId: kotlin.String) : Unit { val localVariableConfig = deleteOrderRequestConfig(orderId = orderId) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -71,20 +71,18 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) * @param orderId ID of the order that needs to be deleted * @return RequestConfig */ - fun deleteOrderRequestConfig(orderId: kotlin.String) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun deleteOrderRequestConfig(orderId: kotlin.String) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.DELETE, path = "/store/order/{orderId}".replace("{"+"orderId"+"}", "$orderId"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -100,7 +98,7 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) suspend fun getInventory() : kotlin.collections.Map { val localVariableConfig = getInventoryRequestConfig() - val localVarResponse = request>( + val localVarResponse = request>( localVariableConfig ) @@ -124,20 +122,18 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) * * @return RequestConfig */ - fun getInventoryRequestConfig() : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun getInventoryRequestConfig() : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/store/inventory", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -154,7 +150,7 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) suspend fun getOrderById(orderId: kotlin.Long) : Order { val localVariableConfig = getOrderByIdRequestConfig(orderId = orderId) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -179,20 +175,18 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) * @param orderId ID of pet that needs to be fetched * @return RequestConfig */ - fun getOrderByIdRequestConfig(orderId: kotlin.Long) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun getOrderByIdRequestConfig(orderId: kotlin.Long) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/store/order/{orderId}".replace("{"+"orderId"+"}", "$orderId"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -209,7 +203,7 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) suspend fun placeOrder(body: Order) : Order { val localVariableConfig = placeOrderRequestConfig(body = body) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -234,20 +228,18 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) * @param body order placed for purchasing the pet * @return RequestConfig */ - fun placeOrderRequestConfig(body: Order) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun placeOrderRequestConfig(body: Order) : RequestConfig { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/store/order", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } } diff --git a/samples/client/petstore/kotlin-jvm-okhttp4-coroutines/src/main/kotlin/org/openapitools/client/apis/UserApi.kt b/samples/client/petstore/kotlin-jvm-okhttp4-coroutines/src/main/kotlin/org/openapitools/client/apis/UserApi.kt index 911bbee5b6b..44f24c941f8 100644 --- a/samples/client/petstore/kotlin-jvm-okhttp4-coroutines/src/main/kotlin/org/openapitools/client/apis/UserApi.kt +++ b/samples/client/petstore/kotlin-jvm-okhttp4-coroutines/src/main/kotlin/org/openapitools/client/apis/UserApi.kt @@ -46,7 +46,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { suspend fun createUser(body: User) : Unit { val localVariableConfig = createUserRequestConfig(body = body) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -71,20 +71,18 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param body Created user object * @return RequestConfig */ - fun createUserRequestConfig(body: User) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun createUserRequestConfig(body: User) : RequestConfig { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/user", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -100,7 +98,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { suspend fun createUsersWithArrayInput(body: kotlin.collections.List) : Unit { val localVariableConfig = createUsersWithArrayInputRequestConfig(body = body) - val localVarResponse = request( + val localVarResponse = request, Unit>( localVariableConfig ) @@ -125,20 +123,18 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param body List of user object * @return RequestConfig */ - fun createUsersWithArrayInputRequestConfig(body: kotlin.collections.List) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun createUsersWithArrayInputRequestConfig(body: kotlin.collections.List) : RequestConfig> { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/user/createWithArray", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -154,7 +150,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { suspend fun createUsersWithListInput(body: kotlin.collections.List) : Unit { val localVariableConfig = createUsersWithListInputRequestConfig(body = body) - val localVarResponse = request( + val localVarResponse = request, Unit>( localVariableConfig ) @@ -179,20 +175,18 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param body List of user object * @return RequestConfig */ - fun createUsersWithListInputRequestConfig(body: kotlin.collections.List) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun createUsersWithListInputRequestConfig(body: kotlin.collections.List) : RequestConfig> { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/user/createWithList", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -208,7 +202,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { suspend fun deleteUser(username: kotlin.String) : Unit { val localVariableConfig = deleteUserRequestConfig(username = username) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -233,20 +227,18 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param username The name that needs to be deleted * @return RequestConfig */ - fun deleteUserRequestConfig(username: kotlin.String) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun deleteUserRequestConfig(username: kotlin.String) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.DELETE, path = "/user/{username}".replace("{"+"username"+"}", "$username"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -263,7 +255,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { suspend fun getUserByName(username: kotlin.String) : User { val localVariableConfig = getUserByNameRequestConfig(username = username) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -288,20 +280,18 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param username The name that needs to be fetched. Use user1 for testing. * @return RequestConfig */ - fun getUserByNameRequestConfig(username: kotlin.String) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun getUserByNameRequestConfig(username: kotlin.String) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/user/{username}".replace("{"+"username"+"}", "$username"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -319,7 +309,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { suspend fun loginUser(username: kotlin.String, password: kotlin.String) : kotlin.String { val localVariableConfig = loginUserRequestConfig(username = username, password = password) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -345,24 +335,22 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param password The password for login in clear text * @return RequestConfig */ - fun loginUserRequestConfig(username: kotlin.String, password: kotlin.String) : RequestConfig { - val localVariableBody: kotlin.Any? = null + 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() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/user/login", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -377,7 +365,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { suspend fun logoutUser() : Unit { val localVariableConfig = logoutUserRequestConfig() - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -401,20 +389,18 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * * @return RequestConfig */ - fun logoutUserRequestConfig() : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun logoutUserRequestConfig() : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/user/logout", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -431,7 +417,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { suspend fun updateUser(username: kotlin.String, body: User) : Unit { val localVariableConfig = updateUserRequestConfig(username = username, body = body) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -457,20 +443,18 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param body Updated user object * @return RequestConfig */ - fun updateUserRequestConfig(username: kotlin.String, body: User) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun updateUserRequestConfig(username: kotlin.String, body: User) : RequestConfig { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.PUT, path = "/user/{username}".replace("{"+"username"+"}", "$username"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } } 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 8ffe5403596..8ba19ee8e15 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 @@ -1,6 +1,5 @@ package org.openapitools.client.infrastructure -import okhttp3.Credentials import okhttp3.OkHttpClient import okhttp3.RequestBody import okhttp3.RequestBody.Companion.asRequestBody @@ -12,17 +11,17 @@ import okhttp3.MediaType.Companion.toMediaTypeOrNull import okhttp3.Request import okhttp3.Headers import okhttp3.MultipartBody -import java.io.File import java.io.BufferedWriter +import java.io.File import java.io.FileWriter import java.net.URLConnection -import java.nio.file.Files -import java.util.Date import java.time.LocalDate import java.time.LocalDateTime import java.time.LocalTime import java.time.OffsetDateTime import java.time.OffsetTime +import java.util.Date +import java.util.Locale open class ApiClient(val baseUrl: String) { companion object { @@ -62,9 +61,7 @@ open class ApiClient(val baseUrl: String) { protected inline fun requestBody(content: T, mediaType: String = JsonMediaType): RequestBody = when { - content is File -> content.asRequestBody( - mediaType.toMediaTypeOrNull() - ) + content is File -> content.asRequestBody(mediaType.toMediaTypeOrNull()) mediaType == FormDataMediaType -> { MultipartBody.Builder() .setType(MultipartBody.FORM) @@ -119,7 +116,7 @@ open class ApiClient(val baseUrl: String) { } if (T::class.java == File::class.java) { // return tempfile - val f = Files.createTempFile("tmp.org.openapitools.client", null).toFile() + val f = java.nio.file.Files.createTempFile("tmp.org.openapitools.client", null).toFile() f.deleteOnExit() val out = BufferedWriter(FileWriter(f)) out.write(bodyContent) @@ -132,7 +129,7 @@ open class ApiClient(val baseUrl: String) { } } - protected fun updateAuthParams(requestConfig: RequestConfig) { + protected fun updateAuthParams(requestConfig: RequestConfig) { if (requestConfig.headers["api_key"].isNullOrEmpty()) { if (apiKey["api_key"] != null) { if (apiKeyPrefix["api_key"] != null) { @@ -149,7 +146,7 @@ open class ApiClient(val baseUrl: String) { } } - protected inline fun request(requestConfig: RequestConfig): ApiInfrastructureResponse { + protected inline fun request(requestConfig: RequestConfig): ApiInfrastructureResponse { val httpUrl = baseUrl.toHttpUrlOrNull() ?: throw IllegalStateException("baseUrl is invalid.") // take authMethod from operation @@ -183,7 +180,7 @@ open class ApiClient(val baseUrl: String) { } // TODO: support multiple contentType options here. - val contentType = (headers[ContentType] as String).substringBefore(";").toLowerCase() + val contentType = (headers[ContentType] as String).substringBefore(";").lowercase(Locale.getDefault()) val request = when (requestConfig.method) { RequestMethod.DELETE -> Request.Builder().url(url).delete(requestBody(requestConfig.body, contentType)) @@ -198,57 +195,46 @@ open class ApiClient(val baseUrl: String) { }.build() val response = client.newCall(request).execute() - val accept = response.header(ContentType)?.substringBefore(";")?.toLowerCase() + val accept = response.header(ContentType)?.substringBefore(";")?.lowercase(Locale.getDefault()) // TODO: handle specific mapping types. e.g. Map> - when { - response.isRedirect -> return Redirection( - response.code, - response.headers.toMultimap() + return when { + response.isRedirect -> Redirection( + response.code, + response.headers.toMultimap() ) - response.isInformational -> return Informational( - response.message, - response.code, - response.headers.toMultimap() + response.isInformational -> Informational( + response.message, + response.code, + response.headers.toMultimap() ) - response.isSuccessful -> return Success( - responseBody(response.body, accept), - response.code, - response.headers.toMultimap() + response.isSuccessful -> Success( + responseBody(response.body, accept), + response.code, + response.headers.toMultimap() ) - response.isClientError -> return ClientError( - response.message, - response.body?.string(), - response.code, - response.headers.toMultimap() + response.isClientError -> ClientError( + response.message, + response.body?.string(), + response.code, + response.headers.toMultimap() ) - else -> return ServerError( - 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 -> { - return "" - } - is Array<*> -> { - return toMultiValue(value, "csv").toString() - } - is Iterable<*> -> { - return toMultiValue(value, "csv").toString() - } - is OffsetDateTime, is OffsetTime, is LocalDateTime, is LocalDate, is LocalTime, is Date -> { - return parseDateToQueryString(value) - } - else -> { - return value.toString() - } - } + 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, is Date -> + parseDateToQueryString(value) + else -> value.toString() } protected inline fun parseDateToQueryString(value : T): String { 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 0f2790f370e..7e948e1dd07 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 @@ -8,10 +8,10 @@ package org.openapitools.client.infrastructure * NOTE: Headers is a Map because rfc2616 defines * multi-valued headers as csv-only. */ -data class RequestConfig( +data class RequestConfig( val method: RequestMethod, val path: String, val headers: MutableMap = mutableMapOf(), val query: MutableMap> = mutableMapOf(), - val body: kotlin.Any? = null + val body: T? = null ) \ No newline at end of file diff --git a/samples/client/petstore/kotlin-moshi-codegen/.openapi-generator/FILES b/samples/client/petstore/kotlin-moshi-codegen/.openapi-generator/FILES index 3f4610174cc..16c712325f8 100644 --- a/samples/client/petstore/kotlin-moshi-codegen/.openapi-generator/FILES +++ b/samples/client/petstore/kotlin-moshi-codegen/.openapi-generator/FILES @@ -20,7 +20,6 @@ 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/ApiInfrastructureResponse.kt -src/main/kotlin/org/openapitools/client/infrastructure/ApplicationDelegates.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 @@ -32,6 +31,7 @@ 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/ApiResponse.kt src/main/kotlin/org/openapitools/client/models/Category.kt diff --git a/samples/client/petstore/kotlin-moshi-codegen/.openapi-generator/VERSION b/samples/client/petstore/kotlin-moshi-codegen/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/client/petstore/kotlin-moshi-codegen/.openapi-generator/VERSION +++ b/samples/client/petstore/kotlin-moshi-codegen/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/client/petstore/kotlin-moshi-codegen/build.gradle b/samples/client/petstore/kotlin-moshi-codegen/build.gradle index 5e86b0b1a36..ff73803f4b6 100644 --- a/samples/client/petstore/kotlin-moshi-codegen/build.gradle +++ b/samples/client/petstore/kotlin-moshi-codegen/build.gradle @@ -7,7 +7,7 @@ wrapper { } buildscript { - ext.kotlin_version = '1.4.30' + ext.kotlin_version = '1.5.10' repositories { maven { url "https://repo1.maven.org/maven2" } @@ -29,9 +29,9 @@ test { } dependencies { - compile "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version" - compile "com.squareup.moshi:moshi:1.11.0" - kapt "com.squareup.moshi:moshi-kotlin-codegen:1.11.0" - compile "com.squareup.okhttp3:okhttp:4.9.0" - testCompile "io.kotlintest:kotlintest-runner-junit5:3.4.2" + implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version" + implementation "com.squareup.moshi:moshi:1.12.0" + kapt "com.squareup.moshi:moshi-kotlin-codegen:1.12.0" + implementation "com.squareup.okhttp3:okhttp:4.9.1" + testImplementation "io.kotlintest:kotlintest-runner-junit5:3.4.2" } diff --git a/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/apis/PetApi.kt b/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/apis/PetApi.kt index c8b93b33bf6..be50dd6c442 100644 --- a/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/apis/PetApi.kt +++ b/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/apis/PetApi.kt @@ -47,7 +47,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun addPet(body: Pet) : Unit { val localVariableConfig = addPetRequestConfig(body = body) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -72,20 +72,18 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param body Pet object that needs to be added to the store * @return RequestConfig */ - fun addPetRequestConfig(body: Pet) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun addPetRequestConfig(body: Pet) : RequestConfig { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/pet", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -102,7 +100,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun deletePet(petId: kotlin.Long, apiKey: kotlin.String?) : Unit { val localVariableConfig = deletePetRequestConfig(petId = petId, apiKey = apiKey) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -128,21 +126,19 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param apiKey (optional) * @return RequestConfig */ - fun deletePetRequestConfig(petId: kotlin.Long, apiKey: kotlin.String?) : RequestConfig { - val localVariableBody: kotlin.Any? = null + 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() } - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.DELETE, path = "/pet/{petId}".replace("{"+"petId"+"}", "$petId"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -159,7 +155,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun findPetsByStatus(status: kotlin.collections.List) : kotlin.collections.List { val localVariableConfig = findPetsByStatusRequestConfig(status = status) - val localVarResponse = request>( + val localVarResponse = request>( localVariableConfig ) @@ -184,23 +180,21 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param status Status values that need to be considered for filter * @return RequestConfig */ - fun findPetsByStatusRequestConfig(status: kotlin.collections.List) : RequestConfig { - val localVariableBody: kotlin.Any? = null + 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() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/pet/findByStatus", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -216,9 +210,10 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { @Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class) @Deprecated(message = "This operation is deprecated.") fun findPetsByTags(tags: kotlin.collections.List) : kotlin.collections.List { + @Suppress("DEPRECATION") val localVariableConfig = findPetsByTagsRequestConfig(tags = tags) - val localVarResponse = request>( + val localVarResponse = request>( localVariableConfig ) @@ -244,23 +239,21 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @return RequestConfig */ @Deprecated(message = "This operation is deprecated.") - fun findPetsByTagsRequestConfig(tags: kotlin.collections.List) : RequestConfig { - val localVariableBody: kotlin.Any? = null + 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() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/pet/findByTags", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -277,7 +270,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun getPetById(petId: kotlin.Long) : Pet { val localVariableConfig = getPetByIdRequestConfig(petId = petId) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -302,20 +295,18 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param petId ID of pet to return * @return RequestConfig */ - fun getPetByIdRequestConfig(petId: kotlin.Long) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun getPetByIdRequestConfig(petId: kotlin.Long) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/pet/{petId}".replace("{"+"petId"+"}", "$petId"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -331,7 +322,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun updatePet(body: Pet) : Unit { val localVariableConfig = updatePetRequestConfig(body = body) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -356,20 +347,18 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param body Pet object that needs to be added to the store * @return RequestConfig */ - fun updatePetRequestConfig(body: Pet) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun updatePetRequestConfig(body: Pet) : RequestConfig { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.PUT, path = "/pet", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -387,7 +376,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun updatePetWithForm(petId: kotlin.Long, name: kotlin.String?, status: kotlin.String?) : Unit { val localVariableConfig = updatePetWithFormRequestConfig(petId = petId, name = name, status = status) - val localVarResponse = request( + val localVarResponse = request, Unit>( localVariableConfig ) @@ -414,20 +403,18 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param status Updated status of the pet (optional) * @return RequestConfig */ - fun updatePetWithFormRequestConfig(petId: kotlin.Long, name: kotlin.String?, status: kotlin.String?) : RequestConfig { - val localVariableBody: kotlin.Any? = mapOf("name" to name, "status" to status) + fun updatePetWithFormRequestConfig(petId: kotlin.Long, name: kotlin.String?, status: kotlin.String?) : RequestConfig> { + val localVariableBody = mapOf("name" to name, "status" to status) val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf("Content-Type" to "application/x-www-form-urlencoded") - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/pet/{petId}".replace("{"+"petId"+"}", "$petId"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -446,7 +433,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun uploadFile(petId: kotlin.Long, additionalMetadata: kotlin.String?, file: java.io.File?) : ApiResponse { val localVariableConfig = uploadFileRequestConfig(petId = petId, additionalMetadata = additionalMetadata, file = file) - val localVarResponse = request( + val localVarResponse = request, ApiResponse>( localVariableConfig ) @@ -473,20 +460,18 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param file file to upload (optional) * @return RequestConfig */ - fun uploadFileRequestConfig(petId: kotlin.Long, additionalMetadata: kotlin.String?, file: java.io.File?) : RequestConfig { - val localVariableBody: kotlin.Any? = mapOf("additionalMetadata" to additionalMetadata, "file" to file) + fun uploadFileRequestConfig(petId: kotlin.Long, additionalMetadata: kotlin.String?, file: java.io.File?) : RequestConfig> { + val localVariableBody = mapOf("additionalMetadata" to additionalMetadata, "file" to file) val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf("Content-Type" to "multipart/form-data") - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/pet/{petId}/uploadImage".replace("{"+"petId"+"}", "$petId"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } } diff --git a/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt b/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt index 215ed63420c..56a23202f82 100644 --- a/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt +++ b/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt @@ -46,7 +46,7 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) fun deleteOrder(orderId: kotlin.String) : Unit { val localVariableConfig = deleteOrderRequestConfig(orderId = orderId) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -71,20 +71,18 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) * @param orderId ID of the order that needs to be deleted * @return RequestConfig */ - fun deleteOrderRequestConfig(orderId: kotlin.String) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun deleteOrderRequestConfig(orderId: kotlin.String) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.DELETE, path = "/store/order/{orderId}".replace("{"+"orderId"+"}", "$orderId"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -100,7 +98,7 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) fun getInventory() : kotlin.collections.Map { val localVariableConfig = getInventoryRequestConfig() - val localVarResponse = request>( + val localVarResponse = request>( localVariableConfig ) @@ -124,20 +122,18 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) * * @return RequestConfig */ - fun getInventoryRequestConfig() : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun getInventoryRequestConfig() : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/store/inventory", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -154,7 +150,7 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) fun getOrderById(orderId: kotlin.Long) : Order { val localVariableConfig = getOrderByIdRequestConfig(orderId = orderId) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -179,20 +175,18 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) * @param orderId ID of pet that needs to be fetched * @return RequestConfig */ - fun getOrderByIdRequestConfig(orderId: kotlin.Long) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun getOrderByIdRequestConfig(orderId: kotlin.Long) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/store/order/{orderId}".replace("{"+"orderId"+"}", "$orderId"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -209,7 +203,7 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) fun placeOrder(body: Order) : Order { val localVariableConfig = placeOrderRequestConfig(body = body) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -234,20 +228,18 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) * @param body order placed for purchasing the pet * @return RequestConfig */ - fun placeOrderRequestConfig(body: Order) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun placeOrderRequestConfig(body: Order) : RequestConfig { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/store/order", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } } diff --git a/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/apis/UserApi.kt b/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/apis/UserApi.kt index 53748b93463..9f93e853a12 100644 --- a/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/apis/UserApi.kt +++ b/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/apis/UserApi.kt @@ -46,7 +46,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun createUser(body: User) : Unit { val localVariableConfig = createUserRequestConfig(body = body) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -71,20 +71,18 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param body Created user object * @return RequestConfig */ - fun createUserRequestConfig(body: User) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun createUserRequestConfig(body: User) : RequestConfig { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/user", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -100,7 +98,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun createUsersWithArrayInput(body: kotlin.collections.List) : Unit { val localVariableConfig = createUsersWithArrayInputRequestConfig(body = body) - val localVarResponse = request( + val localVarResponse = request, Unit>( localVariableConfig ) @@ -125,20 +123,18 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param body List of user object * @return RequestConfig */ - fun createUsersWithArrayInputRequestConfig(body: kotlin.collections.List) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun createUsersWithArrayInputRequestConfig(body: kotlin.collections.List) : RequestConfig> { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/user/createWithArray", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -154,7 +150,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun createUsersWithListInput(body: kotlin.collections.List) : Unit { val localVariableConfig = createUsersWithListInputRequestConfig(body = body) - val localVarResponse = request( + val localVarResponse = request, Unit>( localVariableConfig ) @@ -179,20 +175,18 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param body List of user object * @return RequestConfig */ - fun createUsersWithListInputRequestConfig(body: kotlin.collections.List) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun createUsersWithListInputRequestConfig(body: kotlin.collections.List) : RequestConfig> { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/user/createWithList", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -208,7 +202,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun deleteUser(username: kotlin.String) : Unit { val localVariableConfig = deleteUserRequestConfig(username = username) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -233,20 +227,18 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param username The name that needs to be deleted * @return RequestConfig */ - fun deleteUserRequestConfig(username: kotlin.String) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun deleteUserRequestConfig(username: kotlin.String) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.DELETE, path = "/user/{username}".replace("{"+"username"+"}", "$username"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -263,7 +255,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun getUserByName(username: kotlin.String) : User { val localVariableConfig = getUserByNameRequestConfig(username = username) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -288,20 +280,18 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param username The name that needs to be fetched. Use user1 for testing. * @return RequestConfig */ - fun getUserByNameRequestConfig(username: kotlin.String) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun getUserByNameRequestConfig(username: kotlin.String) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/user/{username}".replace("{"+"username"+"}", "$username"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -319,7 +309,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun loginUser(username: kotlin.String, password: kotlin.String) : kotlin.String { val localVariableConfig = loginUserRequestConfig(username = username, password = password) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -345,24 +335,22 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param password The password for login in clear text * @return RequestConfig */ - fun loginUserRequestConfig(username: kotlin.String, password: kotlin.String) : RequestConfig { - val localVariableBody: kotlin.Any? = null + 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() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/user/login", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -377,7 +365,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun logoutUser() : Unit { val localVariableConfig = logoutUserRequestConfig() - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -401,20 +389,18 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * * @return RequestConfig */ - fun logoutUserRequestConfig() : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun logoutUserRequestConfig() : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/user/logout", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -431,7 +417,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun updateUser(username: kotlin.String, body: User) : Unit { val localVariableConfig = updateUserRequestConfig(username = username, body = body) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -457,20 +443,18 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param body Updated user object * @return RequestConfig */ - fun updateUserRequestConfig(username: kotlin.String, body: User) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun updateUserRequestConfig(username: kotlin.String, body: User) : RequestConfig { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.PUT, path = "/user/{username}".replace("{"+"username"+"}", "$username"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } } 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 bc9ed02c0f1..ae6e80e9506 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 @@ -1,6 +1,5 @@ package org.openapitools.client.infrastructure -import okhttp3.Credentials import okhttp3.OkHttpClient import okhttp3.RequestBody import okhttp3.RequestBody.Companion.asRequestBody @@ -12,17 +11,17 @@ import okhttp3.MediaType.Companion.toMediaTypeOrNull import okhttp3.Request import okhttp3.Headers import okhttp3.MultipartBody -import java.io.File import java.io.BufferedWriter +import java.io.File import java.io.FileWriter import java.net.URLConnection -import java.nio.file.Files -import java.util.Date import java.time.LocalDate import java.time.LocalDateTime import java.time.LocalTime import java.time.OffsetDateTime import java.time.OffsetTime +import java.util.Date +import java.util.Locale open class ApiClient(val baseUrl: String) { companion object { @@ -62,9 +61,7 @@ open class ApiClient(val baseUrl: String) { protected inline fun requestBody(content: T, mediaType: String = JsonMediaType): RequestBody = when { - content is File -> content.asRequestBody( - mediaType.toMediaTypeOrNull() - ) + content is File -> content.asRequestBody(mediaType.toMediaTypeOrNull()) mediaType == FormDataMediaType -> { MultipartBody.Builder() .setType(MultipartBody.FORM) @@ -119,7 +116,7 @@ open class ApiClient(val baseUrl: String) { } if (T::class.java == File::class.java) { // return tempfile - val f = Files.createTempFile("tmp.org.openapitools.client", null).toFile() + val f = java.nio.file.Files.createTempFile("tmp.org.openapitools.client", null).toFile() f.deleteOnExit() val out = BufferedWriter(FileWriter(f)) out.write(bodyContent) @@ -132,7 +129,7 @@ open class ApiClient(val baseUrl: String) { } } - protected fun updateAuthParams(requestConfig: RequestConfig) { + protected fun updateAuthParams(requestConfig: RequestConfig) { if (requestConfig.headers["api_key"].isNullOrEmpty()) { if (apiKey["api_key"] != null) { if (apiKeyPrefix["api_key"] != null) { @@ -149,7 +146,7 @@ open class ApiClient(val baseUrl: String) { } } - protected inline fun request(requestConfig: RequestConfig): ApiInfrastructureResponse { + protected inline fun request(requestConfig: RequestConfig): ApiInfrastructureResponse { val httpUrl = baseUrl.toHttpUrlOrNull() ?: throw IllegalStateException("baseUrl is invalid.") // take authMethod from operation @@ -183,7 +180,7 @@ open class ApiClient(val baseUrl: String) { } // TODO: support multiple contentType options here. - val contentType = (headers[ContentType] as String).substringBefore(";").toLowerCase() + val contentType = (headers[ContentType] as String).substringBefore(";").lowercase(Locale.getDefault()) val request = when (requestConfig.method) { RequestMethod.DELETE -> Request.Builder().url(url).delete(requestBody(requestConfig.body, contentType)) @@ -198,57 +195,46 @@ open class ApiClient(val baseUrl: String) { }.build() val response = client.newCall(request).execute() - val accept = response.header(ContentType)?.substringBefore(";")?.toLowerCase() + val accept = response.header(ContentType)?.substringBefore(";")?.lowercase(Locale.getDefault()) // TODO: handle specific mapping types. e.g. Map> - when { - response.isRedirect -> return Redirection( - response.code, - response.headers.toMultimap() + return when { + response.isRedirect -> Redirection( + response.code, + response.headers.toMultimap() ) - response.isInformational -> return Informational( - response.message, - response.code, - response.headers.toMultimap() + response.isInformational -> Informational( + response.message, + response.code, + response.headers.toMultimap() ) - response.isSuccessful -> return Success( - responseBody(response.body, accept), - response.code, - response.headers.toMultimap() + response.isSuccessful -> Success( + responseBody(response.body, accept), + response.code, + response.headers.toMultimap() ) - response.isClientError -> return ClientError( - response.message, - response.body?.string(), - response.code, - response.headers.toMultimap() + response.isClientError -> ClientError( + response.message, + response.body?.string(), + response.code, + response.headers.toMultimap() ) - else -> return ServerError( - 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 -> { - return "" - } - is Array<*> -> { - return toMultiValue(value, "csv").toString() - } - is Iterable<*> -> { - return toMultiValue(value, "csv").toString() - } - is OffsetDateTime, is OffsetTime, is LocalDateTime, is LocalDate, is LocalTime, is Date -> { - return parseDateToQueryString(value) - } - else -> { - return value.toString() - } - } + 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, is Date -> + parseDateToQueryString(value) + else -> value.toString() } protected inline fun parseDateToQueryString(value : T): String { 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 0f2790f370e..7e948e1dd07 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 @@ -8,10 +8,10 @@ package org.openapitools.client.infrastructure * NOTE: Headers is a Map because rfc2616 defines * multi-valued headers as csv-only. */ -data class RequestConfig( +data class RequestConfig( val method: RequestMethod, val path: String, val headers: MutableMap = mutableMapOf(), val query: MutableMap> = mutableMapOf(), - val body: kotlin.Any? = null + val body: T? = null ) \ No newline at end of file diff --git a/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt b/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt index 1ac7a1908fa..ebd1a2a526b 100644 --- a/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt +++ b/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt @@ -11,6 +11,7 @@ object Serializer { .add(LocalDateAdapter()) .add(UUIDAdapter()) .add(ByteArrayAdapter()) + .add(URIAdapter()) .add(BigDecimalAdapter()) .add(BigIntegerAdapter()) diff --git a/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/infrastructure/URIAdapter.kt b/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/infrastructure/URIAdapter.kt new file mode 100644 index 00000000000..927522757da --- /dev/null +++ b/samples/client/petstore/kotlin-moshi-codegen/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-moshi-codegen/src/main/kotlin/org/openapitools/client/infrastructure/UUIDAdapter.kt b/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/infrastructure/UUIDAdapter.kt index a4a44cc18b7..7ccf7dc25d2 100644 --- a/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/infrastructure/UUIDAdapter.kt +++ b/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/infrastructure/UUIDAdapter.kt @@ -9,5 +9,5 @@ class UUIDAdapter { fun toJson(uuid: UUID) = uuid.toString() @FromJson - fun fromJson(s: String) = UUID.fromString(s) + fun fromJson(s: String): UUID = UUID.fromString(s) } diff --git a/samples/client/petstore/kotlin-multiplatform/.openapi-generator/FILES b/samples/client/petstore/kotlin-multiplatform/.openapi-generator/FILES index e79293ae571..d95b6af6c45 100644 --- a/samples/client/petstore/kotlin-multiplatform/.openapi-generator/FILES +++ b/samples/client/petstore/kotlin-multiplatform/.openapi-generator/FILES @@ -1,5 +1,5 @@ README.md -build.gradle +build.gradle.kts docs/ApiResponse.md docs/Category.md docs/Order.md @@ -9,7 +9,7 @@ docs/StoreApi.md docs/Tag.md docs/User.md docs/UserApi.md -settings.gradle +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 diff --git a/samples/client/petstore/kotlin-multiplatform/.openapi-generator/VERSION b/samples/client/petstore/kotlin-multiplatform/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/client/petstore/kotlin-multiplatform/.openapi-generator/VERSION +++ b/samples/client/petstore/kotlin-multiplatform/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/client/petstore/kotlin-multiplatform/README.md b/samples/client/petstore/kotlin-multiplatform/README.md index 308e8b1c99e..28a4e3f1201 100644 --- a/samples/client/petstore/kotlin-multiplatform/README.md +++ b/samples/client/petstore/kotlin-multiplatform/README.md @@ -2,7 +2,7 @@ ## Requires -* Kotlin 1.3.50 +* Kotlin 1.5.10 ## Build diff --git a/samples/client/petstore/kotlin-multiplatform/build.gradle b/samples/client/petstore/kotlin-multiplatform/build.gradle deleted file mode 100644 index 47045bb577e..00000000000 --- a/samples/client/petstore/kotlin-multiplatform/build.gradle +++ /dev/null @@ -1,161 +0,0 @@ -apply plugin: 'kotlin-multiplatform' -apply plugin: 'kotlinx-serialization' - -group 'org.openapitools' -version '1.0.0' - -ext { - kotlin_version = '1.3.50' - kotlinx_version = '1.1.0' - coroutines_version = '1.3.1' - serialization_version = '0.12.0' - ktor_version = '1.2.4' -} - -buildscript { - repositories { - jcenter() - } - dependencies { - classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.3.50" // $kotlin_version - classpath "org.jetbrains.kotlin:kotlin-serialization:1.3.50" // $kotlin_version - } -} - -repositories { - jcenter() -} - -kotlin { - jvm() - iosArm64() { binaries { framework { freeCompilerArgs.add("-Xobjc-generics") } } } - iosX64() { binaries { framework { freeCompilerArgs.add("-Xobjc-generics") } } } - js() - - sourceSets { - commonMain { - dependencies { - implementation "org.jetbrains.kotlin:kotlin-stdlib-common:$kotlin_version" - implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core-common:$coroutines_version" - implementation "org.jetbrains.kotlinx:kotlinx-serialization-runtime-common:$serialization_version" - api "io.ktor:ktor-client-core:$ktor_version" - api "io.ktor:ktor-client-json:$ktor_version" - api "io.ktor:ktor-client-serialization:$ktor_version" - } - } - - commonTest { - dependencies { - implementation "org.jetbrains.kotlin:kotlin-test-common" - implementation "org.jetbrains.kotlin:kotlin-test-annotations-common" - implementation "io.ktor:ktor-client-mock:$ktor_version" - } - } - - jvmMain { - dependsOn commonMain - dependencies { - implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version" - implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:$coroutines_version" - implementation "org.jetbrains.kotlinx:kotlinx-serialization-runtime:$serialization_version" - api "io.ktor:ktor-client-core-jvm:$ktor_version" - api "io.ktor:ktor-client-json-jvm:$ktor_version" - api "io.ktor:ktor-client-serialization-jvm:$ktor_version" - } - } - - jvmTest { - dependsOn commonTest - dependencies { - implementation "org.jetbrains.kotlin:kotlin-test" - implementation "org.jetbrains.kotlin:kotlin-test-junit" - implementation "io.ktor:ktor-client-mock-jvm:$ktor_version" - } - } - - iosMain { - dependsOn commonMain - dependencies { - implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core-native:$coroutines_version" - implementation "org.jetbrains.kotlinx:kotlinx-serialization-runtime-native:$serialization_version" - api "io.ktor:ktor-client-ios:$ktor_version" - } - } - - iosTest { - dependsOn commonTest - dependencies { - implementation "io.ktor:ktor-client-mock-native:$ktor_version" - } - } - - iosArm64().compilations.main.defaultSourceSet { - dependsOn iosMain - dependencies { - api "io.ktor:ktor-client-ios-iosarm64:$ktor_version" - api "io.ktor:ktor-client-json-iosarm64:$ktor_version" - api "io.ktor:ktor-client-serialization-iosarm64:$ktor_version" - } - } - - iosArm64().compilations.test.defaultSourceSet { - dependsOn iosTest - } - - iosX64().compilations.main.defaultSourceSet { - dependsOn iosMain - dependencies { - api "io.ktor:ktor-client-ios-iosx64:$ktor_version" - api "io.ktor:ktor-client-json-iosx64:$ktor_version" - api "io.ktor:ktor-client-serialization-iosx64:$ktor_version" - } - } - - jsMain { - dependsOn commonMain - dependencies { - implementation "org.jetbrains.kotlin:kotlin-stdlib-js:$kotlin_version" - implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core-js:$coroutines_version" - implementation "org.jetbrains.kotlinx:kotlinx-serialization-runtime-js:$serialization_version" - api "io.ktor:ktor-client-js:$ktor_version" - api "io.ktor:ktor-client-json-js:$ktor_version" - api "io.ktor:ktor-client-serialization-js:$ktor_version" - } - } - - jsTest { - dependsOn commonTest - dependencies { - implementation "io.ktor:ktor-client-mock-js:$ktor_version" - implementation "io.ktor:ktor-client-js:$ktor_version" - implementation "io.ktor:ktor-client-json:$ktor_version" - implementation "io.ktor:ktor-client-serialization-js:$ktor_version" - } - } - - iosX64().compilations.test.defaultSourceSet { - dependsOn iosTest - } - - all { - languageSettings { - useExperimentalAnnotation('kotlin.Experimental') - } - } - } -} - -task iosTest { - def device = project.findProperty("device")?.toString() ?: "iPhone 8" - dependsOn 'linkDebugTestIosX64' - group = JavaBasePlugin.VERIFICATION_GROUP - description = "Execute unit tests on ${device} simulator" - doLast { - def binary = kotlin.targets.iosX64.binaries.getTest('DEBUG') - exec { commandLine 'xcrun', 'simctl', 'spawn', device, binary.outputFile } - } -} - -configurations { // workaround for https://youtrack.jetbrains.com/issue/KT-27170 - compileClasspath -} diff --git a/samples/client/petstore/kotlin-multiplatform/build.gradle.kts b/samples/client/petstore/kotlin-multiplatform/build.gradle.kts new file mode 100644 index 00000000000..1b7fdd939c3 --- /dev/null +++ b/samples/client/petstore/kotlin-multiplatform/build.gradle.kts @@ -0,0 +1,95 @@ +import org.jetbrains.kotlin.gradle.plugin.mpp.KotlinNativeTarget + +plugins { + kotlin("multiplatform") version "1.5.10" // kotlin_version + kotlin("plugin.serialization") version "1.5.10" // kotlin_version +} + +group = "org.openapitools" +version = "1.0.0" + +val kotlin_version = "1.5.10" +val coroutines_version = "1.5.0" +val serialization_version = "1.2.1" +val ktor_version = "1.6.0" + +repositories { + mavenCentral() +} + +kotlin { + jvm() + ios { binaries { framework { freeCompilerArgs += "-Xobjc-generics" } } } + js { + browser() + nodejs() + } + + sourceSets { + val commonMain by getting { + 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-json:$ktor_version") + api("io.ktor:ktor-client-serialization:$ktor_version") + } + } + + val commonTest by getting { + dependencies { + implementation(kotlin("test")) + implementation("io.ktor:ktor-client-mock:$ktor_version") + } + } + + val jvmMain by getting { + dependencies { + implementation(kotlin("stdlib-jdk7")) + } + } + + val jvmTest by getting { + dependencies { + implementation(kotlin("test-junit")) + } + } + + val iosMain by getting { + dependencies { + api("io.ktor:ktor-client-ios:$ktor_version") + } + } + + val iosTest by getting + + val jsMain by getting { + dependencies { + api("io.ktor:ktor-client-js:$ktor_version") + } + } + + val jsTest by getting + + all { + languageSettings.apply { + useExperimentalAnnotation("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) + } + } + } +} diff --git a/samples/client/petstore/kotlin-multiplatform/settings.gradle b/samples/client/petstore/kotlin-multiplatform/settings.gradle deleted file mode 100644 index b000833f485..00000000000 --- a/samples/client/petstore/kotlin-multiplatform/settings.gradle +++ /dev/null @@ -1,2 +0,0 @@ -enableFeaturePreview('GRADLE_METADATA') -rootProject.name = 'kotlin-client-petstore-multiplatform' \ No newline at end of file diff --git a/samples/client/petstore/kotlin-multiplatform/settings.gradle.kts b/samples/client/petstore/kotlin-multiplatform/settings.gradle.kts new file mode 100644 index 00000000000..15cae2a9fd0 --- /dev/null +++ b/samples/client/petstore/kotlin-multiplatform/settings.gradle.kts @@ -0,0 +1,2 @@ +enableFeaturePreview("GRADLE_METADATA") +rootProject.name = "kotlin-client-petstore-multiplatform" \ No newline at end of file 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 e164a6cf4d0..5df1dfc40ee 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 @@ -16,27 +16,19 @@ import org.openapitools.client.models.Pet import org.openapitools.client.infrastructure.* import io.ktor.client.request.forms.formData -import kotlinx.serialization.UnstableDefault import io.ktor.client.engine.HttpClientEngine import io.ktor.client.features.json.serializer.KotlinxSerializer import kotlinx.serialization.json.Json -import kotlinx.serialization.json.JsonConfiguration import io.ktor.http.ParametersBuilder import kotlinx.serialization.* -import kotlinx.serialization.internal.StringDescriptor +import kotlinx.serialization.descriptors.* +import kotlinx.serialization.encoding.* -class PetApi @UseExperimental(UnstableDefault::class) constructor( - baseUrl: kotlin.String = "http://petstore.swagger.io/v2", +class PetApi( + baseUrl: String = ApiClient.BASE_URL, httpClientEngine: HttpClientEngine? = null, - serializer: KotlinxSerializer -) : ApiClient(baseUrl, httpClientEngine, serializer) { - - @UseExperimental(UnstableDefault::class) - constructor( - baseUrl: kotlin.String = "http://petstore.swagger.io/v2", - httpClientEngine: HttpClientEngine? = null, - jsonConfiguration: JsonConfiguration = JsonConfiguration.Default - ) : this(baseUrl, httpClientEngine, KotlinxSerializer(Json(jsonConfiguration))) + jsonSerializer: Json = ApiClient.JSON_DEFAULT +) : ApiClient(baseUrl, httpClientEngine, jsonSerializer) { /** * Add a new pet to the store @@ -54,7 +46,7 @@ class PetApi @UseExperimental(UnstableDefault::class) constructor( val localVariableHeaders = mutableMapOf() - val localVariableConfig = RequestConfig( + val localVariableConfig = RequestConfig( RequestMethod.POST, "/pet", query = localVariableQuery, @@ -89,7 +81,7 @@ class PetApi @UseExperimental(UnstableDefault::class) constructor( val localVariableHeaders = mutableMapOf() apiKey?.apply { localVariableHeaders["api_key"] = this.toString() } - val localVariableConfig = RequestConfig( + val localVariableConfig = RequestConfig( RequestMethod.DELETE, "/pet/{petId}".replace("{" + "petId" + "}", "$petId"), query = localVariableQuery, @@ -123,7 +115,7 @@ class PetApi @UseExperimental(UnstableDefault::class) constructor( val localVariableHeaders = mutableMapOf() - val localVariableConfig = RequestConfig( + val localVariableConfig = RequestConfig( RequestMethod.GET, "/pet/findByStatus", query = localVariableQuery, @@ -141,10 +133,10 @@ class PetApi @UseExperimental(UnstableDefault::class) constructor( private class FindPetsByStatusResponse(val value: List) { @Serializer(FindPetsByStatusResponse::class) companion object : KSerializer { - private val serializer: KSerializer> = Pet.serializer().list - override val descriptor = StringDescriptor.withName("FindPetsByStatusResponse") - override fun serialize(encoder: Encoder, obj: FindPetsByStatusResponse) = serializer.serialize(encoder, obj.value) - override fun deserialize(decoder: Decoder) = FindPetsByStatusResponse(serializer.deserialize(decoder)) + 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)) } } @@ -167,7 +159,7 @@ class PetApi @UseExperimental(UnstableDefault::class) constructor( val localVariableHeaders = mutableMapOf() - val localVariableConfig = RequestConfig( + val localVariableConfig = RequestConfig( RequestMethod.GET, "/pet/findByTags", query = localVariableQuery, @@ -185,10 +177,10 @@ class PetApi @UseExperimental(UnstableDefault::class) constructor( private class FindPetsByTagsResponse(val value: List) { @Serializer(FindPetsByTagsResponse::class) companion object : KSerializer { - private val serializer: KSerializer> = Pet.serializer().list - override val descriptor = StringDescriptor.withName("FindPetsByTagsResponse") - override fun serialize(encoder: Encoder, obj: FindPetsByTagsResponse) = serializer.serialize(encoder, obj.value) - override fun deserialize(decoder: Decoder) = FindPetsByTagsResponse(serializer.deserialize(decoder)) + 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)) } } @@ -210,7 +202,7 @@ class PetApi @UseExperimental(UnstableDefault::class) constructor( val localVariableHeaders = mutableMapOf() - val localVariableConfig = RequestConfig( + val localVariableConfig = RequestConfig( RequestMethod.GET, "/pet/{petId}".replace("{" + "petId" + "}", "$petId"), query = localVariableQuery, @@ -241,7 +233,7 @@ class PetApi @UseExperimental(UnstableDefault::class) constructor( val localVariableHeaders = mutableMapOf() - val localVariableConfig = RequestConfig( + val localVariableConfig = RequestConfig( RequestMethod.PUT, "/pet", query = localVariableQuery, @@ -279,7 +271,7 @@ class PetApi @UseExperimental(UnstableDefault::class) constructor( val localVariableHeaders = mutableMapOf() - val localVariableConfig = RequestConfig( + val localVariableConfig = RequestConfig( RequestMethod.POST, "/pet/{petId}".replace("{" + "petId" + "}", "$petId"), query = localVariableQuery, @@ -317,7 +309,7 @@ class PetApi @UseExperimental(UnstableDefault::class) constructor( val localVariableHeaders = mutableMapOf() - val localVariableConfig = RequestConfig( + val localVariableConfig = RequestConfig( RequestMethod.POST, "/pet/{petId}/uploadImage".replace("{" + "petId" + "}", "$petId"), query = localVariableQuery, @@ -332,13 +324,4 @@ class PetApi @UseExperimental(UnstableDefault::class) constructor( } - - companion object { - internal fun setMappers(serializer: KotlinxSerializer) { - - serializer.setMapper(FindPetsByStatusResponse::class, FindPetsByStatusResponse.serializer()) - serializer.setMapper(FindPetsByTagsResponse::class, FindPetsByTagsResponse.serializer()) - - } - } } 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 8ca30e8ca3a..345ef648864 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 @@ -15,27 +15,19 @@ import org.openapitools.client.models.Order import org.openapitools.client.infrastructure.* import io.ktor.client.request.forms.formData -import kotlinx.serialization.UnstableDefault import io.ktor.client.engine.HttpClientEngine import io.ktor.client.features.json.serializer.KotlinxSerializer import kotlinx.serialization.json.Json -import kotlinx.serialization.json.JsonConfiguration import io.ktor.http.ParametersBuilder import kotlinx.serialization.* -import kotlinx.serialization.internal.StringDescriptor +import kotlinx.serialization.descriptors.* +import kotlinx.serialization.encoding.* -class StoreApi @UseExperimental(UnstableDefault::class) constructor( - baseUrl: kotlin.String = "http://petstore.swagger.io/v2", +class StoreApi( + baseUrl: String = ApiClient.BASE_URL, httpClientEngine: HttpClientEngine? = null, - serializer: KotlinxSerializer -) : ApiClient(baseUrl, httpClientEngine, serializer) { - - @UseExperimental(UnstableDefault::class) - constructor( - baseUrl: kotlin.String = "http://petstore.swagger.io/v2", - httpClientEngine: HttpClientEngine? = null, - jsonConfiguration: JsonConfiguration = JsonConfiguration.Default - ) : this(baseUrl, httpClientEngine, KotlinxSerializer(Json(jsonConfiguration))) + jsonSerializer: Json = ApiClient.JSON_DEFAULT +) : ApiClient(baseUrl, httpClientEngine, jsonSerializer) { /** * Delete purchase order by ID @@ -54,7 +46,7 @@ class StoreApi @UseExperimental(UnstableDefault::class) constructor( val localVariableHeaders = mutableMapOf() - val localVariableConfig = RequestConfig( + val localVariableConfig = RequestConfig( RequestMethod.DELETE, "/store/order/{orderId}".replace("{" + "orderId" + "}", "$orderId"), query = localVariableQuery, @@ -86,7 +78,7 @@ class StoreApi @UseExperimental(UnstableDefault::class) constructor( val localVariableHeaders = mutableMapOf() - val localVariableConfig = RequestConfig( + val localVariableConfig = RequestConfig( RequestMethod.GET, "/store/inventory", query = localVariableQuery, @@ -104,10 +96,10 @@ class StoreApi @UseExperimental(UnstableDefault::class) constructor( private class GetInventoryResponse(val value: Map) { @Serializer(GetInventoryResponse::class) companion object : KSerializer { - private val serializer: KSerializer> = (kotlin.String.serializer() to kotlin.Int.serializer()).map - override val descriptor = StringDescriptor.withName("GetInventoryResponse") - override fun serialize(encoder: Encoder, obj: GetInventoryResponse) = serializer.serialize(encoder, obj.value) - override fun deserialize(decoder: Decoder) = GetInventoryResponse(serializer.deserialize(decoder)) + 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)) } } @@ -129,7 +121,7 @@ class StoreApi @UseExperimental(UnstableDefault::class) constructor( val localVariableHeaders = mutableMapOf() - val localVariableConfig = RequestConfig( + val localVariableConfig = RequestConfig( RequestMethod.GET, "/store/order/{orderId}".replace("{" + "orderId" + "}", "$orderId"), query = localVariableQuery, @@ -161,7 +153,7 @@ class StoreApi @UseExperimental(UnstableDefault::class) constructor( val localVariableHeaders = mutableMapOf() - val localVariableConfig = RequestConfig( + val localVariableConfig = RequestConfig( RequestMethod.POST, "/store/order", query = localVariableQuery, @@ -177,11 +169,4 @@ class StoreApi @UseExperimental(UnstableDefault::class) constructor( - - companion object { - internal fun setMappers(serializer: KotlinxSerializer) { - serializer.setMapper(GetInventoryResponse::class, GetInventoryResponse.serializer()) - - } - } } 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 88474dc9ef8..6e1f7d50f25 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 @@ -15,27 +15,19 @@ import org.openapitools.client.models.User import org.openapitools.client.infrastructure.* import io.ktor.client.request.forms.formData -import kotlinx.serialization.UnstableDefault import io.ktor.client.engine.HttpClientEngine import io.ktor.client.features.json.serializer.KotlinxSerializer import kotlinx.serialization.json.Json -import kotlinx.serialization.json.JsonConfiguration import io.ktor.http.ParametersBuilder import kotlinx.serialization.* -import kotlinx.serialization.internal.StringDescriptor +import kotlinx.serialization.descriptors.* +import kotlinx.serialization.encoding.* -class UserApi @UseExperimental(UnstableDefault::class) constructor( - baseUrl: kotlin.String = "http://petstore.swagger.io/v2", +class UserApi( + baseUrl: String = ApiClient.BASE_URL, httpClientEngine: HttpClientEngine? = null, - serializer: KotlinxSerializer -) : ApiClient(baseUrl, httpClientEngine, serializer) { - - @UseExperimental(UnstableDefault::class) - constructor( - baseUrl: kotlin.String = "http://petstore.swagger.io/v2", - httpClientEngine: HttpClientEngine? = null, - jsonConfiguration: JsonConfiguration = JsonConfiguration.Default - ) : this(baseUrl, httpClientEngine, KotlinxSerializer(Json(jsonConfiguration))) + jsonSerializer: Json = ApiClient.JSON_DEFAULT +) : ApiClient(baseUrl, httpClientEngine, jsonSerializer) { /** * Create user @@ -53,7 +45,7 @@ class UserApi @UseExperimental(UnstableDefault::class) constructor( val localVariableHeaders = mutableMapOf() - val localVariableConfig = RequestConfig( + val localVariableConfig = RequestConfig( RequestMethod.POST, "/user", query = localVariableQuery, @@ -85,7 +77,7 @@ class UserApi @UseExperimental(UnstableDefault::class) constructor( val localVariableHeaders = mutableMapOf() - val localVariableConfig = RequestConfig( + val localVariableConfig = RequestConfig( RequestMethod.POST, "/user/createWithArray", query = localVariableQuery, @@ -103,10 +95,10 @@ class UserApi @UseExperimental(UnstableDefault::class) constructor( private class CreateUsersWithArrayInputRequest(val value: List) { @Serializer(CreateUsersWithArrayInputRequest::class) companion object : KSerializer { - private val serializer: KSerializer> = User.serializer().list - override val descriptor = StringDescriptor.withName("CreateUsersWithArrayInputRequest") - override fun serialize(encoder: Encoder, obj: CreateUsersWithArrayInputRequest) = serializer.serialize(encoder, obj.value) - override fun deserialize(decoder: Decoder) = CreateUsersWithArrayInputRequest(serializer.deserialize(decoder)) + 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)) } } @@ -126,7 +118,7 @@ class UserApi @UseExperimental(UnstableDefault::class) constructor( val localVariableHeaders = mutableMapOf() - val localVariableConfig = RequestConfig( + val localVariableConfig = RequestConfig( RequestMethod.POST, "/user/createWithList", query = localVariableQuery, @@ -144,10 +136,10 @@ class UserApi @UseExperimental(UnstableDefault::class) constructor( private class CreateUsersWithListInputRequest(val value: List) { @Serializer(CreateUsersWithListInputRequest::class) companion object : KSerializer { - private val serializer: KSerializer> = User.serializer().list - override val descriptor = StringDescriptor.withName("CreateUsersWithListInputRequest") - override fun serialize(encoder: Encoder, obj: CreateUsersWithListInputRequest) = serializer.serialize(encoder, obj.value) - override fun deserialize(decoder: Decoder) = CreateUsersWithListInputRequest(serializer.deserialize(decoder)) + 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)) } } @@ -168,7 +160,7 @@ class UserApi @UseExperimental(UnstableDefault::class) constructor( val localVariableHeaders = mutableMapOf() - val localVariableConfig = RequestConfig( + val localVariableConfig = RequestConfig( RequestMethod.DELETE, "/user/{username}".replace("{" + "username" + "}", "$username"), query = localVariableQuery, @@ -201,7 +193,7 @@ class UserApi @UseExperimental(UnstableDefault::class) constructor( val localVariableHeaders = mutableMapOf() - val localVariableConfig = RequestConfig( + val localVariableConfig = RequestConfig( RequestMethod.GET, "/user/{username}".replace("{" + "username" + "}", "$username"), query = localVariableQuery, @@ -237,7 +229,7 @@ class UserApi @UseExperimental(UnstableDefault::class) constructor( val localVariableHeaders = mutableMapOf() - val localVariableConfig = RequestConfig( + val localVariableConfig = RequestConfig( RequestMethod.GET, "/user/login", query = localVariableQuery, @@ -268,7 +260,7 @@ class UserApi @UseExperimental(UnstableDefault::class) constructor( val localVariableHeaders = mutableMapOf() - val localVariableConfig = RequestConfig( + val localVariableConfig = RequestConfig( RequestMethod.GET, "/user/logout", query = localVariableQuery, @@ -300,7 +292,7 @@ class UserApi @UseExperimental(UnstableDefault::class) constructor( val localVariableHeaders = mutableMapOf() - val localVariableConfig = RequestConfig( + val localVariableConfig = RequestConfig( RequestMethod.PUT, "/user/{username}".replace("{" + "username" + "}", "$username"), query = localVariableQuery, @@ -316,13 +308,4 @@ class UserApi @UseExperimental(UnstableDefault::class) constructor( - - companion object { - internal fun setMappers(serializer: KotlinxSerializer) { - - serializer.setMapper(CreateUsersWithArrayInputRequest::class, CreateUsersWithArrayInputRequest.serializer()) - serializer.setMapper(CreateUsersWithListInputRequest::class, CreateUsersWithListInputRequest.serializer()) - - } - } } 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 fe8434be210..9f25b105953 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 @@ -2,24 +2,21 @@ package org.openapitools.client.infrastructure import io.ktor.client.HttpClient import io.ktor.client.HttpClientConfig -import io.ktor.client.call.call import io.ktor.client.engine.HttpClientEngine import io.ktor.client.features.json.JsonFeature import io.ktor.client.features.json.JsonSerializer import io.ktor.client.features.json.serializer.KotlinxSerializer -import io.ktor.client.request.accept +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.response.HttpResponse +import io.ktor.client.statement.HttpResponse import io.ktor.client.utils.EmptyContent import io.ktor.http.* import io.ktor.http.content.OutgoingContent import io.ktor.http.content.PartData -import kotlinx.serialization.UnstableDefault import kotlinx.serialization.json.Json -import kotlinx.serialization.json.JsonConfiguration import org.openapitools.client.apis.* import org.openapitools.client.models.* @@ -28,17 +25,11 @@ import org.openapitools.client.auth.* open class ApiClient( private val baseUrl: String, httpClientEngine: HttpClientEngine?, - serializer: KotlinxSerializer) { - - @UseExperimental(UnstableDefault::class) - constructor( - baseUrl: String, - httpClientEngine: HttpClientEngine?, - jsonConfiguration: JsonConfiguration) : - this(baseUrl, httpClientEngine, KotlinxSerializer(Json(jsonConfiguration))) + private val json: Json +) { private val serializer: JsonSerializer by lazy { - serializer.apply { setMappers(this) }.ignoreOutgoingContent() + KotlinxSerializer(json).ignoreOutgoingContent() } private val client: HttpClient by lazy { @@ -53,23 +44,9 @@ open class ApiClient( } companion object { + const val BASE_URL = "http://petstore.swagger.io/v2" + val JSON_DEFAULT = Json { ignoreUnknownKeys = true } protected val UNSAFE_HEADERS = listOf(HttpHeaders.ContentType) - - private fun setMappers(serializer: KotlinxSerializer) { - - PetApi.setMappers(serializer) - - StoreApi.setMappers(serializer) - - UserApi.setMappers(serializer) - - serializer.setMapper(org.openapitools.client.models.ApiResponse::class, org.openapitools.client.models.ApiResponse.serializer()) - serializer.setMapper(org.openapitools.client.models.Category::class, org.openapitools.client.models.Category.serializer()) - serializer.setMapper(org.openapitools.client.models.Order::class, org.openapitools.client.models.Order.serializer()) - serializer.setMapper(org.openapitools.client.models.Pet::class, org.openapitools.client.models.Pet.serializer()) - serializer.setMapper(org.openapitools.client.models.Tag::class, org.openapitools.client.models.Tag.serializer()) - serializer.setMapper(org.openapitools.client.models.User::class, org.openapitools.client.models.User.serializer()) - } } /** @@ -140,26 +117,26 @@ open class ApiClient( auth.bearerToken = bearerToken } - protected suspend fun multipartFormRequest(requestConfig: RequestConfig, body: kotlin.collections.List?, authNames: kotlin.collections.List): HttpResponse { + 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 { + 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 { + protected suspend fun jsonRequest(requestConfig: RequestConfig, body: Any? = null, authNames: kotlin.collections.List): HttpResponse { val contentType = (requestConfig.headers[HttpHeaders.ContentType]?.let { ContentType.parse(it) } ?: ContentType.Application.Json) return if (body != null) request(requestConfig, serializer.write(body, contentType), authNames) else request(requestConfig, authNames = authNames) } - protected suspend fun request(requestConfig: RequestConfig, body: OutgoingContent = EmptyContent, authNames: kotlin.collections.List): HttpResponse { - requestConfig.updateForAuth(authNames) + protected suspend fun request(requestConfig: RequestConfig, body: OutgoingContent = EmptyContent, authNames: kotlin.collections.List): HttpResponse { + requestConfig.updateForAuth(authNames) val headers = requestConfig.headers - return client.call { + return client.request { this.url { this.takeFrom(URLBuilder(baseUrl)) appendPath(requestConfig.path.trimStart('/').split('/')) @@ -174,10 +151,10 @@ open class ApiClient( if (requestConfig.method in listOf(RequestMethod.PUT, RequestMethod.POST, RequestMethod.PATCH)) this.body = body - }.response + } } - private fun RequestConfig.updateForAuth(authNames: kotlin.collections.List) { + 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) 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 4bc1197cf00..7c635c14fdd 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 @@ -1,13 +1,14 @@ package org.openapitools.client.infrastructure import kotlinx.serialization.* -import kotlinx.serialization.internal.StringDescriptor +import kotlinx.serialization.descriptors.* +import kotlinx.serialization.encoding.* @Serializable class Base64ByteArray(val value: ByteArray) { @Serializer(Base64ByteArray::class) companion object : KSerializer { - override val descriptor = StringDescriptor.withName("Base64ByteArray") + 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()) } 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 8a222416cf2..b8f12a08529 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 @@ -1,6 +1,6 @@ package org.openapitools.client.infrastructure -import kotlinx.io.core.* +import io.ktor.utils.io.core.* import kotlin.experimental.and private val digits = "0123456789abcdef".toCharArray() @@ -32,7 +32,7 @@ internal fun hex(bytes: ByteArray): String { result[resultIndex++] = digits[b and 0x0f] } - return String(result) + return result.concatToString() } /** diff --git a/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/HttpResponse.kt b/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/HttpResponse.kt index c457eb4bce0..61e55bc5b15 100644 --- a/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/HttpResponse.kt +++ b/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/HttpResponse.kt @@ -5,7 +5,7 @@ import io.ktor.client.call.typeInfo import io.ktor.http.Headers import io.ktor.http.isSuccess -open class HttpResponse(val response: io.ktor.client.response.HttpResponse, val provider: BodyProvider) { +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() @@ -22,29 +22,29 @@ open class HttpResponse(val response: io.ktor.client.response.HttpRespo } interface BodyProvider { - suspend fun body(response: io.ktor.client.response.HttpResponse): T - suspend fun typedBody(response: io.ktor.client.response.HttpResponse, type: TypeInfo): V + 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.response.HttpResponse): T = + override suspend fun body(response: io.ktor.client.statement.HttpResponse): T = response.call.receive(type) as T @Suppress("UNCHECKED_CAST") - override suspend fun typedBody(response: io.ktor.client.response.HttpResponse, type: TypeInfo): V = + override suspend fun typedBody(response: io.ktor.client.statement.HttpResponse, type: TypeInfo): V = response.call.receive(type) as V } class MappedBodyProvider(private val provider: BodyProvider, private val block: S.() -> T) : BodyProvider { - override suspend fun body(response: io.ktor.client.response.HttpResponse): T = + override suspend fun body(response: io.ktor.client.statement.HttpResponse): T = block(provider.body(response)) - override suspend fun typedBody(response: io.ktor.client.response.HttpResponse, type: TypeInfo): V = + override suspend fun typedBody(response: io.ktor.client.statement.HttpResponse, type: TypeInfo): V = provider.typedBody(response, type) } -inline fun io.ktor.client.response.HttpResponse.wrap(): HttpResponse = +inline fun io.ktor.client.statement.HttpResponse.wrap(): HttpResponse = HttpResponse(this, TypedBodyProvider(typeInfo())) fun HttpResponse.map(block: T.() -> V): HttpResponse = 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 735e4e6e3f6..04c88673331 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 @@ -1,13 +1,14 @@ package org.openapitools.client.infrastructure import kotlinx.serialization.* -import kotlinx.serialization.internal.StringDescriptor +import kotlinx.serialization.descriptors.* +import kotlinx.serialization.encoding.* @Serializable class OctetByteArray(val value: ByteArray) { @Serializer(OctetByteArray::class) companion object : KSerializer { - override val descriptor = StringDescriptor.withName("OctetByteArray") + 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())) } 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 0f2790f370e..7e948e1dd07 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 @@ -8,10 +8,10 @@ package org.openapitools.client.infrastructure * NOTE: Headers is a Map because rfc2616 defines * multi-valued headers as csv-only. */ -data class RequestConfig( +data class RequestConfig( val method: RequestMethod, val path: String, val headers: MutableMap = mutableMapOf(), val query: MutableMap> = mutableMapOf(), - val body: kotlin.Any? = null + val body: T? = null ) \ No newline at end of file diff --git a/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/models/ApiResponse.kt b/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/models/ApiResponse.kt index a035628a8f9..91150fbf26b 100644 --- a/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/models/ApiResponse.kt +++ b/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/models/ApiResponse.kt @@ -13,7 +13,8 @@ package org.openapitools.client.models import kotlinx.serialization.* -import kotlinx.serialization.internal.CommonEnumSerializer +import kotlinx.serialization.descriptors.* +import kotlinx.serialization.encoding.* /** * Describes the result of uploading an image resource diff --git a/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/models/Category.kt b/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/models/Category.kt index d5f9a45fd4d..8c17893935b 100644 --- a/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/models/Category.kt +++ b/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/models/Category.kt @@ -13,7 +13,8 @@ package org.openapitools.client.models import kotlinx.serialization.* -import kotlinx.serialization.internal.CommonEnumSerializer +import kotlinx.serialization.descriptors.* +import kotlinx.serialization.encoding.* /** * A category for a pet 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 0a53ba0740e..f5ae575d19e 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 @@ -13,7 +13,8 @@ package org.openapitools.client.models import kotlinx.serialization.* -import kotlinx.serialization.internal.CommonEnumSerializer +import kotlinx.serialization.descriptors.* +import kotlinx.serialization.encoding.* /** * An order for a pets from the pet store @@ -39,10 +40,11 @@ data class Order ( * Order Status * Values: placed,approved,delivered */ + @Serializable enum class Status(val value: kotlin.String) { - placed("placed"), - approved("approved"), - delivered("delivered"); + @SerialName(value = "placed") placed("placed"), + @SerialName(value = "approved") approved("approved"), + @SerialName(value = "delivered") delivered("delivered"); } } diff --git a/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/models/Pet.kt b/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/models/Pet.kt index 1649cf0fb29..55879c6c7ac 100644 --- a/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/models/Pet.kt +++ b/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/models/Pet.kt @@ -15,7 +15,8 @@ import org.openapitools.client.models.Category import org.openapitools.client.models.Tag import kotlinx.serialization.* -import kotlinx.serialization.internal.CommonEnumSerializer +import kotlinx.serialization.descriptors.* +import kotlinx.serialization.encoding.* /** * A pet for sale in the pet store @@ -41,10 +42,11 @@ data class Pet ( * pet status in the store * Values: available,pending,sold */ + @Serializable enum class Status(val value: kotlin.String) { - available("available"), - pending("pending"), - sold("sold"); + @SerialName(value = "available") available("available"), + @SerialName(value = "pending") pending("pending"), + @SerialName(value = "sold") sold("sold"); } } diff --git a/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/models/Tag.kt b/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/models/Tag.kt index 6116e50d3f9..54a4e01d29a 100644 --- a/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/models/Tag.kt +++ b/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/models/Tag.kt @@ -13,7 +13,8 @@ package org.openapitools.client.models import kotlinx.serialization.* -import kotlinx.serialization.internal.CommonEnumSerializer +import kotlinx.serialization.descriptors.* +import kotlinx.serialization.encoding.* /** * A tag for a pet diff --git a/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/models/User.kt b/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/models/User.kt index 97b53a049c1..4c69c432e2e 100644 --- a/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/models/User.kt +++ b/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/models/User.kt @@ -13,7 +13,8 @@ package org.openapitools.client.models import kotlinx.serialization.* -import kotlinx.serialization.internal.CommonEnumSerializer +import kotlinx.serialization.descriptors.* +import kotlinx.serialization.encoding.* /** * A User who is purchasing from the pet store diff --git a/samples/client/petstore/kotlin-nonpublic/.openapi-generator/FILES b/samples/client/petstore/kotlin-nonpublic/.openapi-generator/FILES index 3f4610174cc..16c712325f8 100644 --- a/samples/client/petstore/kotlin-nonpublic/.openapi-generator/FILES +++ b/samples/client/petstore/kotlin-nonpublic/.openapi-generator/FILES @@ -20,7 +20,6 @@ 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/ApiInfrastructureResponse.kt -src/main/kotlin/org/openapitools/client/infrastructure/ApplicationDelegates.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 @@ -32,6 +31,7 @@ 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/ApiResponse.kt src/main/kotlin/org/openapitools/client/models/Category.kt diff --git a/samples/client/petstore/kotlin-nonpublic/.openapi-generator/VERSION b/samples/client/petstore/kotlin-nonpublic/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/client/petstore/kotlin-nonpublic/.openapi-generator/VERSION +++ b/samples/client/petstore/kotlin-nonpublic/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/client/petstore/kotlin-nonpublic/build.gradle b/samples/client/petstore/kotlin-nonpublic/build.gradle index 60e5056e031..bb575e6e4bf 100644 --- a/samples/client/petstore/kotlin-nonpublic/build.gradle +++ b/samples/client/petstore/kotlin-nonpublic/build.gradle @@ -7,7 +7,7 @@ wrapper { } buildscript { - ext.kotlin_version = '1.4.30' + ext.kotlin_version = '1.5.10' repositories { maven { url "https://repo1.maven.org/maven2" } @@ -28,9 +28,9 @@ test { } dependencies { - compile "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version" - compile "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version" - compile "com.squareup.moshi:moshi-kotlin:1.11.0" - compile "com.squareup.okhttp3:okhttp:4.9.0" - testCompile "io.kotlintest:kotlintest-runner-junit5:3.4.2" + implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version" + implementation "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version" + implementation "com.squareup.moshi:moshi-kotlin:1.12.0" + implementation "com.squareup.okhttp3:okhttp:4.9.1" + testImplementation "io.kotlintest:kotlintest-runner-junit5:3.4.2" } diff --git a/samples/client/petstore/kotlin-nonpublic/src/main/kotlin/org/openapitools/client/apis/PetApi.kt b/samples/client/petstore/kotlin-nonpublic/src/main/kotlin/org/openapitools/client/apis/PetApi.kt index b6b38fa42f3..7919953d4b4 100644 --- a/samples/client/petstore/kotlin-nonpublic/src/main/kotlin/org/openapitools/client/apis/PetApi.kt +++ b/samples/client/petstore/kotlin-nonpublic/src/main/kotlin/org/openapitools/client/apis/PetApi.kt @@ -47,7 +47,7 @@ internal class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(bas fun addPet(body: Pet) : Unit { val localVariableConfig = addPetRequestConfig(body = body) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -72,20 +72,18 @@ internal class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(bas * @param body Pet object that needs to be added to the store * @return RequestConfig */ - fun addPetRequestConfig(body: Pet) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun addPetRequestConfig(body: Pet) : RequestConfig { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/pet", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -102,7 +100,7 @@ internal class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(bas fun deletePet(petId: kotlin.Long, apiKey: kotlin.String?) : Unit { val localVariableConfig = deletePetRequestConfig(petId = petId, apiKey = apiKey) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -128,21 +126,19 @@ internal class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(bas * @param apiKey (optional) * @return RequestConfig */ - fun deletePetRequestConfig(petId: kotlin.Long, apiKey: kotlin.String?) : RequestConfig { - val localVariableBody: kotlin.Any? = null + 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() } - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.DELETE, path = "/pet/{petId}".replace("{"+"petId"+"}", "$petId"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -159,7 +155,7 @@ internal class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(bas fun findPetsByStatus(status: kotlin.collections.List) : kotlin.collections.List { val localVariableConfig = findPetsByStatusRequestConfig(status = status) - val localVarResponse = request>( + val localVarResponse = request>( localVariableConfig ) @@ -184,23 +180,21 @@ internal class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(bas * @param status Status values that need to be considered for filter * @return RequestConfig */ - fun findPetsByStatusRequestConfig(status: kotlin.collections.List) : RequestConfig { - val localVariableBody: kotlin.Any? = null + 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() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/pet/findByStatus", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -216,9 +210,10 @@ internal class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(bas @Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class) @Deprecated(message = "This operation is deprecated.") fun findPetsByTags(tags: kotlin.collections.List) : kotlin.collections.List { + @Suppress("DEPRECATION") val localVariableConfig = findPetsByTagsRequestConfig(tags = tags) - val localVarResponse = request>( + val localVarResponse = request>( localVariableConfig ) @@ -244,23 +239,21 @@ internal class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(bas * @return RequestConfig */ @Deprecated(message = "This operation is deprecated.") - fun findPetsByTagsRequestConfig(tags: kotlin.collections.List) : RequestConfig { - val localVariableBody: kotlin.Any? = null + 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() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/pet/findByTags", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -277,7 +270,7 @@ internal class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(bas fun getPetById(petId: kotlin.Long) : Pet { val localVariableConfig = getPetByIdRequestConfig(petId = petId) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -302,20 +295,18 @@ internal class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(bas * @param petId ID of pet to return * @return RequestConfig */ - fun getPetByIdRequestConfig(petId: kotlin.Long) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun getPetByIdRequestConfig(petId: kotlin.Long) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/pet/{petId}".replace("{"+"petId"+"}", "$petId"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -331,7 +322,7 @@ internal class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(bas fun updatePet(body: Pet) : Unit { val localVariableConfig = updatePetRequestConfig(body = body) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -356,20 +347,18 @@ internal class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(bas * @param body Pet object that needs to be added to the store * @return RequestConfig */ - fun updatePetRequestConfig(body: Pet) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun updatePetRequestConfig(body: Pet) : RequestConfig { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.PUT, path = "/pet", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -387,7 +376,7 @@ internal class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(bas fun updatePetWithForm(petId: kotlin.Long, name: kotlin.String?, status: kotlin.String?) : Unit { val localVariableConfig = updatePetWithFormRequestConfig(petId = petId, name = name, status = status) - val localVarResponse = request( + val localVarResponse = request, Unit>( localVariableConfig ) @@ -414,20 +403,18 @@ internal class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(bas * @param status Updated status of the pet (optional) * @return RequestConfig */ - fun updatePetWithFormRequestConfig(petId: kotlin.Long, name: kotlin.String?, status: kotlin.String?) : RequestConfig { - val localVariableBody: kotlin.Any? = mapOf("name" to name, "status" to status) + fun updatePetWithFormRequestConfig(petId: kotlin.Long, name: kotlin.String?, status: kotlin.String?) : RequestConfig> { + val localVariableBody = mapOf("name" to name, "status" to status) val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf("Content-Type" to "application/x-www-form-urlencoded") - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/pet/{petId}".replace("{"+"petId"+"}", "$petId"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -446,7 +433,7 @@ internal class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(bas fun uploadFile(petId: kotlin.Long, additionalMetadata: kotlin.String?, file: java.io.File?) : ApiResponse { val localVariableConfig = uploadFileRequestConfig(petId = petId, additionalMetadata = additionalMetadata, file = file) - val localVarResponse = request( + val localVarResponse = request, ApiResponse>( localVariableConfig ) @@ -473,20 +460,18 @@ internal class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(bas * @param file file to upload (optional) * @return RequestConfig */ - fun uploadFileRequestConfig(petId: kotlin.Long, additionalMetadata: kotlin.String?, file: java.io.File?) : RequestConfig { - val localVariableBody: kotlin.Any? = mapOf("additionalMetadata" to additionalMetadata, "file" to file) + fun uploadFileRequestConfig(petId: kotlin.Long, additionalMetadata: kotlin.String?, file: java.io.File?) : RequestConfig> { + val localVariableBody = mapOf("additionalMetadata" to additionalMetadata, "file" to file) val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf("Content-Type" to "multipart/form-data") - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/pet/{petId}/uploadImage".replace("{"+"petId"+"}", "$petId"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } } diff --git a/samples/client/petstore/kotlin-nonpublic/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt b/samples/client/petstore/kotlin-nonpublic/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt index 19b7acdbd31..10e2b946005 100644 --- a/samples/client/petstore/kotlin-nonpublic/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt +++ b/samples/client/petstore/kotlin-nonpublic/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt @@ -46,7 +46,7 @@ internal class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(b fun deleteOrder(orderId: kotlin.String) : Unit { val localVariableConfig = deleteOrderRequestConfig(orderId = orderId) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -71,20 +71,18 @@ internal class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(b * @param orderId ID of the order that needs to be deleted * @return RequestConfig */ - fun deleteOrderRequestConfig(orderId: kotlin.String) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun deleteOrderRequestConfig(orderId: kotlin.String) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.DELETE, path = "/store/order/{orderId}".replace("{"+"orderId"+"}", "$orderId"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -100,7 +98,7 @@ internal class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(b fun getInventory() : kotlin.collections.Map { val localVariableConfig = getInventoryRequestConfig() - val localVarResponse = request>( + val localVarResponse = request>( localVariableConfig ) @@ -124,20 +122,18 @@ internal class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(b * * @return RequestConfig */ - fun getInventoryRequestConfig() : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun getInventoryRequestConfig() : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/store/inventory", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -154,7 +150,7 @@ internal class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(b fun getOrderById(orderId: kotlin.Long) : Order { val localVariableConfig = getOrderByIdRequestConfig(orderId = orderId) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -179,20 +175,18 @@ internal class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(b * @param orderId ID of pet that needs to be fetched * @return RequestConfig */ - fun getOrderByIdRequestConfig(orderId: kotlin.Long) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun getOrderByIdRequestConfig(orderId: kotlin.Long) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/store/order/{orderId}".replace("{"+"orderId"+"}", "$orderId"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -209,7 +203,7 @@ internal class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(b fun placeOrder(body: Order) : Order { val localVariableConfig = placeOrderRequestConfig(body = body) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -234,20 +228,18 @@ internal class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(b * @param body order placed for purchasing the pet * @return RequestConfig */ - fun placeOrderRequestConfig(body: Order) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun placeOrderRequestConfig(body: Order) : RequestConfig { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/store/order", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } } diff --git a/samples/client/petstore/kotlin-nonpublic/src/main/kotlin/org/openapitools/client/apis/UserApi.kt b/samples/client/petstore/kotlin-nonpublic/src/main/kotlin/org/openapitools/client/apis/UserApi.kt index 979bb1b81f8..4983dc73feb 100644 --- a/samples/client/petstore/kotlin-nonpublic/src/main/kotlin/org/openapitools/client/apis/UserApi.kt +++ b/samples/client/petstore/kotlin-nonpublic/src/main/kotlin/org/openapitools/client/apis/UserApi.kt @@ -46,7 +46,7 @@ internal class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(ba fun createUser(body: User) : Unit { val localVariableConfig = createUserRequestConfig(body = body) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -71,20 +71,18 @@ internal class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(ba * @param body Created user object * @return RequestConfig */ - fun createUserRequestConfig(body: User) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun createUserRequestConfig(body: User) : RequestConfig { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/user", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -100,7 +98,7 @@ internal class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(ba fun createUsersWithArrayInput(body: kotlin.collections.List) : Unit { val localVariableConfig = createUsersWithArrayInputRequestConfig(body = body) - val localVarResponse = request( + val localVarResponse = request, Unit>( localVariableConfig ) @@ -125,20 +123,18 @@ internal class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(ba * @param body List of user object * @return RequestConfig */ - fun createUsersWithArrayInputRequestConfig(body: kotlin.collections.List) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun createUsersWithArrayInputRequestConfig(body: kotlin.collections.List) : RequestConfig> { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/user/createWithArray", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -154,7 +150,7 @@ internal class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(ba fun createUsersWithListInput(body: kotlin.collections.List) : Unit { val localVariableConfig = createUsersWithListInputRequestConfig(body = body) - val localVarResponse = request( + val localVarResponse = request, Unit>( localVariableConfig ) @@ -179,20 +175,18 @@ internal class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(ba * @param body List of user object * @return RequestConfig */ - fun createUsersWithListInputRequestConfig(body: kotlin.collections.List) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun createUsersWithListInputRequestConfig(body: kotlin.collections.List) : RequestConfig> { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/user/createWithList", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -208,7 +202,7 @@ internal class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(ba fun deleteUser(username: kotlin.String) : Unit { val localVariableConfig = deleteUserRequestConfig(username = username) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -233,20 +227,18 @@ internal class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(ba * @param username The name that needs to be deleted * @return RequestConfig */ - fun deleteUserRequestConfig(username: kotlin.String) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun deleteUserRequestConfig(username: kotlin.String) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.DELETE, path = "/user/{username}".replace("{"+"username"+"}", "$username"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -263,7 +255,7 @@ internal class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(ba fun getUserByName(username: kotlin.String) : User { val localVariableConfig = getUserByNameRequestConfig(username = username) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -288,20 +280,18 @@ internal class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(ba * @param username The name that needs to be fetched. Use user1 for testing. * @return RequestConfig */ - fun getUserByNameRequestConfig(username: kotlin.String) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun getUserByNameRequestConfig(username: kotlin.String) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/user/{username}".replace("{"+"username"+"}", "$username"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -319,7 +309,7 @@ internal class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(ba fun loginUser(username: kotlin.String, password: kotlin.String) : kotlin.String { val localVariableConfig = loginUserRequestConfig(username = username, password = password) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -345,24 +335,22 @@ internal class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(ba * @param password The password for login in clear text * @return RequestConfig */ - fun loginUserRequestConfig(username: kotlin.String, password: kotlin.String) : RequestConfig { - val localVariableBody: kotlin.Any? = null + 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() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/user/login", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -377,7 +365,7 @@ internal class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(ba fun logoutUser() : Unit { val localVariableConfig = logoutUserRequestConfig() - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -401,20 +389,18 @@ internal class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(ba * * @return RequestConfig */ - fun logoutUserRequestConfig() : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun logoutUserRequestConfig() : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/user/logout", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -431,7 +417,7 @@ internal class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(ba fun updateUser(username: kotlin.String, body: User) : Unit { val localVariableConfig = updateUserRequestConfig(username = username, body = body) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -457,20 +443,18 @@ internal class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(ba * @param body Updated user object * @return RequestConfig */ - fun updateUserRequestConfig(username: kotlin.String, body: User) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun updateUserRequestConfig(username: kotlin.String, body: User) : RequestConfig { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.PUT, path = "/user/{username}".replace("{"+"username"+"}", "$username"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } } 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 d43c0c614d5..ed34dce2446 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 @@ -1,6 +1,5 @@ package org.openapitools.client.infrastructure -import okhttp3.Credentials import okhttp3.OkHttpClient import okhttp3.RequestBody import okhttp3.RequestBody.Companion.asRequestBody @@ -12,17 +11,17 @@ import okhttp3.MediaType.Companion.toMediaTypeOrNull import okhttp3.Request import okhttp3.Headers import okhttp3.MultipartBody -import java.io.File import java.io.BufferedWriter +import java.io.File import java.io.FileWriter import java.net.URLConnection -import java.nio.file.Files -import java.util.Date import java.time.LocalDate import java.time.LocalDateTime import java.time.LocalTime import java.time.OffsetDateTime import java.time.OffsetTime +import java.util.Date +import java.util.Locale internal open class ApiClient(val baseUrl: String) { internal companion object { @@ -62,9 +61,7 @@ internal open class ApiClient(val baseUrl: String) { protected inline fun requestBody(content: T, mediaType: String = JsonMediaType): RequestBody = when { - content is File -> content.asRequestBody( - mediaType.toMediaTypeOrNull() - ) + content is File -> content.asRequestBody(mediaType.toMediaTypeOrNull()) mediaType == FormDataMediaType -> { MultipartBody.Builder() .setType(MultipartBody.FORM) @@ -119,7 +116,7 @@ internal open class ApiClient(val baseUrl: String) { } if (T::class.java == File::class.java) { // return tempfile - val f = Files.createTempFile("tmp.org.openapitools.client", null).toFile() + val f = java.nio.file.Files.createTempFile("tmp.org.openapitools.client", null).toFile() f.deleteOnExit() val out = BufferedWriter(FileWriter(f)) out.write(bodyContent) @@ -132,7 +129,7 @@ internal open class ApiClient(val baseUrl: String) { } } - protected fun updateAuthParams(requestConfig: RequestConfig) { + protected fun updateAuthParams(requestConfig: RequestConfig) { if (requestConfig.headers["api_key"].isNullOrEmpty()) { if (apiKey["api_key"] != null) { if (apiKeyPrefix["api_key"] != null) { @@ -149,7 +146,7 @@ internal open class ApiClient(val baseUrl: String) { } } - protected inline fun request(requestConfig: RequestConfig): ApiInfrastructureResponse { + protected inline fun request(requestConfig: RequestConfig): ApiInfrastructureResponse { val httpUrl = baseUrl.toHttpUrlOrNull() ?: throw IllegalStateException("baseUrl is invalid.") // take authMethod from operation @@ -183,7 +180,7 @@ internal open class ApiClient(val baseUrl: String) { } // TODO: support multiple contentType options here. - val contentType = (headers[ContentType] as String).substringBefore(";").toLowerCase() + val contentType = (headers[ContentType] as String).substringBefore(";").lowercase(Locale.getDefault()) val request = when (requestConfig.method) { RequestMethod.DELETE -> Request.Builder().url(url).delete(requestBody(requestConfig.body, contentType)) @@ -198,57 +195,46 @@ internal open class ApiClient(val baseUrl: String) { }.build() val response = client.newCall(request).execute() - val accept = response.header(ContentType)?.substringBefore(";")?.toLowerCase() + val accept = response.header(ContentType)?.substringBefore(";")?.lowercase(Locale.getDefault()) // TODO: handle specific mapping types. e.g. Map> - when { - response.isRedirect -> return Redirection( - response.code, - response.headers.toMultimap() + return when { + response.isRedirect -> Redirection( + response.code, + response.headers.toMultimap() ) - response.isInformational -> return Informational( - response.message, - response.code, - response.headers.toMultimap() + response.isInformational -> Informational( + response.message, + response.code, + response.headers.toMultimap() ) - response.isSuccessful -> return Success( - responseBody(response.body, accept), - response.code, - response.headers.toMultimap() + response.isSuccessful -> Success( + responseBody(response.body, accept), + response.code, + response.headers.toMultimap() ) - response.isClientError -> return ClientError( - response.message, - response.body?.string(), - response.code, - response.headers.toMultimap() + response.isClientError -> ClientError( + response.message, + response.body?.string(), + response.code, + response.headers.toMultimap() ) - else -> return ServerError( - 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 -> { - return "" - } - is Array<*> -> { - return toMultiValue(value, "csv").toString() - } - is Iterable<*> -> { - return toMultiValue(value, "csv").toString() - } - is OffsetDateTime, is OffsetTime, is LocalDateTime, is LocalDate, is LocalTime, is Date -> { - return parseDateToQueryString(value) - } - else -> { - return value.toString() - } - } + 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, is Date -> + parseDateToQueryString(value) + else -> value.toString() } protected inline fun parseDateToQueryString(value : T): String { 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 68f41c5497d..70cb0b04615 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 @@ -8,10 +8,10 @@ package org.openapitools.client.infrastructure * NOTE: Headers is a Map because rfc2616 defines * multi-valued headers as csv-only. */ -internal data class RequestConfig( +internal data class RequestConfig( val method: RequestMethod, val path: String, val headers: MutableMap = mutableMapOf(), val query: MutableMap> = mutableMapOf(), - val body: kotlin.Any? = null + val body: T? = null ) \ No newline at end of file diff --git a/samples/client/petstore/kotlin-nonpublic/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt b/samples/client/petstore/kotlin-nonpublic/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt index 54e21400c43..acc0b33ae20 100644 --- a/samples/client/petstore/kotlin-nonpublic/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt +++ b/samples/client/petstore/kotlin-nonpublic/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt @@ -12,6 +12,7 @@ internal object Serializer { .add(LocalDateAdapter()) .add(UUIDAdapter()) .add(ByteArrayAdapter()) + .add(URIAdapter()) .add(KotlinJsonAdapterFactory()) .add(BigDecimalAdapter()) .add(BigIntegerAdapter()) diff --git a/samples/client/petstore/kotlin-nonpublic/src/main/kotlin/org/openapitools/client/infrastructure/URIAdapter.kt b/samples/client/petstore/kotlin-nonpublic/src/main/kotlin/org/openapitools/client/infrastructure/URIAdapter.kt new file mode 100644 index 00000000000..3e509e9a831 --- /dev/null +++ b/samples/client/petstore/kotlin-nonpublic/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 + +internal 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-nonpublic/src/main/kotlin/org/openapitools/client/infrastructure/UUIDAdapter.kt b/samples/client/petstore/kotlin-nonpublic/src/main/kotlin/org/openapitools/client/infrastructure/UUIDAdapter.kt index 02fa692b57d..b5de20257ba 100644 --- a/samples/client/petstore/kotlin-nonpublic/src/main/kotlin/org/openapitools/client/infrastructure/UUIDAdapter.kt +++ b/samples/client/petstore/kotlin-nonpublic/src/main/kotlin/org/openapitools/client/infrastructure/UUIDAdapter.kt @@ -9,5 +9,5 @@ internal class UUIDAdapter { fun toJson(uuid: UUID) = uuid.toString() @FromJson - fun fromJson(s: String) = UUID.fromString(s) + fun fromJson(s: String): UUID = UUID.fromString(s) } diff --git a/samples/client/petstore/kotlin-nullable/.openapi-generator/FILES b/samples/client/petstore/kotlin-nullable/.openapi-generator/FILES index 3f4610174cc..16c712325f8 100644 --- a/samples/client/petstore/kotlin-nullable/.openapi-generator/FILES +++ b/samples/client/petstore/kotlin-nullable/.openapi-generator/FILES @@ -20,7 +20,6 @@ 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/ApiInfrastructureResponse.kt -src/main/kotlin/org/openapitools/client/infrastructure/ApplicationDelegates.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 @@ -32,6 +31,7 @@ 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/ApiResponse.kt src/main/kotlin/org/openapitools/client/models/Category.kt diff --git a/samples/client/petstore/kotlin-nullable/.openapi-generator/VERSION b/samples/client/petstore/kotlin-nullable/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/client/petstore/kotlin-nullable/.openapi-generator/VERSION +++ b/samples/client/petstore/kotlin-nullable/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/client/petstore/kotlin-nullable/build.gradle b/samples/client/petstore/kotlin-nullable/build.gradle index 60e5056e031..bb575e6e4bf 100644 --- a/samples/client/petstore/kotlin-nullable/build.gradle +++ b/samples/client/petstore/kotlin-nullable/build.gradle @@ -7,7 +7,7 @@ wrapper { } buildscript { - ext.kotlin_version = '1.4.30' + ext.kotlin_version = '1.5.10' repositories { maven { url "https://repo1.maven.org/maven2" } @@ -28,9 +28,9 @@ test { } dependencies { - compile "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version" - compile "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version" - compile "com.squareup.moshi:moshi-kotlin:1.11.0" - compile "com.squareup.okhttp3:okhttp:4.9.0" - testCompile "io.kotlintest:kotlintest-runner-junit5:3.4.2" + implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version" + implementation "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version" + implementation "com.squareup.moshi:moshi-kotlin:1.12.0" + implementation "com.squareup.okhttp3:okhttp:4.9.1" + testImplementation "io.kotlintest:kotlintest-runner-junit5:3.4.2" } diff --git a/samples/client/petstore/kotlin-nullable/src/main/kotlin/org/openapitools/client/apis/PetApi.kt b/samples/client/petstore/kotlin-nullable/src/main/kotlin/org/openapitools/client/apis/PetApi.kt index 95f695cb9f4..401a66cf94d 100644 --- a/samples/client/petstore/kotlin-nullable/src/main/kotlin/org/openapitools/client/apis/PetApi.kt +++ b/samples/client/petstore/kotlin-nullable/src/main/kotlin/org/openapitools/client/apis/PetApi.kt @@ -47,7 +47,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun addPet(body: Pet) : Unit { val localVariableConfig = addPetRequestConfig(body = body) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -72,20 +72,18 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param body Pet object that needs to be added to the store * @return RequestConfig */ - fun addPetRequestConfig(body: Pet) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun addPetRequestConfig(body: Pet) : RequestConfig { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/pet", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -102,7 +100,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun deletePet(petId: kotlin.Long, apiKey: kotlin.String?) : Unit { val localVariableConfig = deletePetRequestConfig(petId = petId, apiKey = apiKey) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -128,21 +126,19 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param apiKey (optional) * @return RequestConfig */ - fun deletePetRequestConfig(petId: kotlin.Long, apiKey: kotlin.String?) : RequestConfig { - val localVariableBody: kotlin.Any? = null + 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() } - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.DELETE, path = "/pet/{petId}".replace("{"+"petId"+"}", "$petId"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -159,7 +155,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun findPetsByStatus(status: kotlin.collections.List) : kotlin.collections.List? { val localVariableConfig = findPetsByStatusRequestConfig(status = status) - val localVarResponse = request>( + val localVarResponse = request>( localVariableConfig ) @@ -184,23 +180,21 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param status Status values that need to be considered for filter * @return RequestConfig */ - fun findPetsByStatusRequestConfig(status: kotlin.collections.List) : RequestConfig { - val localVariableBody: kotlin.Any? = null + 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() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/pet/findByStatus", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -216,9 +210,10 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { @Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class) @Deprecated(message = "This operation is deprecated.") fun findPetsByTags(tags: kotlin.collections.List) : kotlin.collections.List? { + @Suppress("DEPRECATION") val localVariableConfig = findPetsByTagsRequestConfig(tags = tags) - val localVarResponse = request>( + val localVarResponse = request>( localVariableConfig ) @@ -244,23 +239,21 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @return RequestConfig */ @Deprecated(message = "This operation is deprecated.") - fun findPetsByTagsRequestConfig(tags: kotlin.collections.List) : RequestConfig { - val localVariableBody: kotlin.Any? = null + 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() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/pet/findByTags", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -277,7 +270,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun getPetById(petId: kotlin.Long) : Pet? { val localVariableConfig = getPetByIdRequestConfig(petId = petId) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -302,20 +295,18 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param petId ID of pet to return * @return RequestConfig */ - fun getPetByIdRequestConfig(petId: kotlin.Long) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun getPetByIdRequestConfig(petId: kotlin.Long) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/pet/{petId}".replace("{"+"petId"+"}", "$petId"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -331,7 +322,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun updatePet(body: Pet) : Unit { val localVariableConfig = updatePetRequestConfig(body = body) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -356,20 +347,18 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param body Pet object that needs to be added to the store * @return RequestConfig */ - fun updatePetRequestConfig(body: Pet) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun updatePetRequestConfig(body: Pet) : RequestConfig { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.PUT, path = "/pet", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -387,7 +376,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun updatePetWithForm(petId: kotlin.Long, name: kotlin.String?, status: kotlin.String?) : Unit { val localVariableConfig = updatePetWithFormRequestConfig(petId = petId, name = name, status = status) - val localVarResponse = request( + val localVarResponse = request, Unit>( localVariableConfig ) @@ -414,20 +403,18 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param status Updated status of the pet (optional) * @return RequestConfig */ - fun updatePetWithFormRequestConfig(petId: kotlin.Long, name: kotlin.String?, status: kotlin.String?) : RequestConfig { - val localVariableBody: kotlin.Any? = mapOf("name" to name, "status" to status) + fun updatePetWithFormRequestConfig(petId: kotlin.Long, name: kotlin.String?, status: kotlin.String?) : RequestConfig> { + val localVariableBody = mapOf("name" to name, "status" to status) val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf("Content-Type" to "application/x-www-form-urlencoded") - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/pet/{petId}".replace("{"+"petId"+"}", "$petId"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -446,7 +433,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun uploadFile(petId: kotlin.Long, additionalMetadata: kotlin.String?, file: java.io.File?) : ApiResponse? { val localVariableConfig = uploadFileRequestConfig(petId = petId, additionalMetadata = additionalMetadata, file = file) - val localVarResponse = request( + val localVarResponse = request, ApiResponse>( localVariableConfig ) @@ -473,20 +460,18 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param file file to upload (optional) * @return RequestConfig */ - fun uploadFileRequestConfig(petId: kotlin.Long, additionalMetadata: kotlin.String?, file: java.io.File?) : RequestConfig { - val localVariableBody: kotlin.Any? = mapOf("additionalMetadata" to additionalMetadata, "file" to file) + fun uploadFileRequestConfig(petId: kotlin.Long, additionalMetadata: kotlin.String?, file: java.io.File?) : RequestConfig> { + val localVariableBody = mapOf("additionalMetadata" to additionalMetadata, "file" to file) val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf("Content-Type" to "multipart/form-data") - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/pet/{petId}/uploadImage".replace("{"+"petId"+"}", "$petId"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } } diff --git a/samples/client/petstore/kotlin-nullable/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt b/samples/client/petstore/kotlin-nullable/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt index c442f866100..d8b1ad578f5 100644 --- a/samples/client/petstore/kotlin-nullable/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt +++ b/samples/client/petstore/kotlin-nullable/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt @@ -46,7 +46,7 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) fun deleteOrder(orderId: kotlin.String) : Unit { val localVariableConfig = deleteOrderRequestConfig(orderId = orderId) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -71,20 +71,18 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) * @param orderId ID of the order that needs to be deleted * @return RequestConfig */ - fun deleteOrderRequestConfig(orderId: kotlin.String) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun deleteOrderRequestConfig(orderId: kotlin.String) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.DELETE, path = "/store/order/{orderId}".replace("{"+"orderId"+"}", "$orderId"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -100,7 +98,7 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) fun getInventory() : kotlin.collections.Map? { val localVariableConfig = getInventoryRequestConfig() - val localVarResponse = request>( + val localVarResponse = request>( localVariableConfig ) @@ -124,20 +122,18 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) * * @return RequestConfig */ - fun getInventoryRequestConfig() : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun getInventoryRequestConfig() : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/store/inventory", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -154,7 +150,7 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) fun getOrderById(orderId: kotlin.Long) : Order? { val localVariableConfig = getOrderByIdRequestConfig(orderId = orderId) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -179,20 +175,18 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) * @param orderId ID of pet that needs to be fetched * @return RequestConfig */ - fun getOrderByIdRequestConfig(orderId: kotlin.Long) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun getOrderByIdRequestConfig(orderId: kotlin.Long) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/store/order/{orderId}".replace("{"+"orderId"+"}", "$orderId"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -209,7 +203,7 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) fun placeOrder(body: Order) : Order? { val localVariableConfig = placeOrderRequestConfig(body = body) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -234,20 +228,18 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) * @param body order placed for purchasing the pet * @return RequestConfig */ - fun placeOrderRequestConfig(body: Order) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun placeOrderRequestConfig(body: Order) : RequestConfig { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/store/order", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } } diff --git a/samples/client/petstore/kotlin-nullable/src/main/kotlin/org/openapitools/client/apis/UserApi.kt b/samples/client/petstore/kotlin-nullable/src/main/kotlin/org/openapitools/client/apis/UserApi.kt index 6e6c329144c..a8848130116 100644 --- a/samples/client/petstore/kotlin-nullable/src/main/kotlin/org/openapitools/client/apis/UserApi.kt +++ b/samples/client/petstore/kotlin-nullable/src/main/kotlin/org/openapitools/client/apis/UserApi.kt @@ -46,7 +46,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun createUser(body: User) : Unit { val localVariableConfig = createUserRequestConfig(body = body) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -71,20 +71,18 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param body Created user object * @return RequestConfig */ - fun createUserRequestConfig(body: User) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun createUserRequestConfig(body: User) : RequestConfig { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/user", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -100,7 +98,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun createUsersWithArrayInput(body: kotlin.collections.List) : Unit { val localVariableConfig = createUsersWithArrayInputRequestConfig(body = body) - val localVarResponse = request( + val localVarResponse = request, Unit>( localVariableConfig ) @@ -125,20 +123,18 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param body List of user object * @return RequestConfig */ - fun createUsersWithArrayInputRequestConfig(body: kotlin.collections.List) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun createUsersWithArrayInputRequestConfig(body: kotlin.collections.List) : RequestConfig> { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/user/createWithArray", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -154,7 +150,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun createUsersWithListInput(body: kotlin.collections.List) : Unit { val localVariableConfig = createUsersWithListInputRequestConfig(body = body) - val localVarResponse = request( + val localVarResponse = request, Unit>( localVariableConfig ) @@ -179,20 +175,18 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param body List of user object * @return RequestConfig */ - fun createUsersWithListInputRequestConfig(body: kotlin.collections.List) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun createUsersWithListInputRequestConfig(body: kotlin.collections.List) : RequestConfig> { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/user/createWithList", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -208,7 +202,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun deleteUser(username: kotlin.String) : Unit { val localVariableConfig = deleteUserRequestConfig(username = username) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -233,20 +227,18 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param username The name that needs to be deleted * @return RequestConfig */ - fun deleteUserRequestConfig(username: kotlin.String) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun deleteUserRequestConfig(username: kotlin.String) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.DELETE, path = "/user/{username}".replace("{"+"username"+"}", "$username"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -263,7 +255,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun getUserByName(username: kotlin.String) : User? { val localVariableConfig = getUserByNameRequestConfig(username = username) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -288,20 +280,18 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param username The name that needs to be fetched. Use user1 for testing. * @return RequestConfig */ - fun getUserByNameRequestConfig(username: kotlin.String) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun getUserByNameRequestConfig(username: kotlin.String) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/user/{username}".replace("{"+"username"+"}", "$username"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -319,7 +309,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun loginUser(username: kotlin.String, password: kotlin.String) : kotlin.String? { val localVariableConfig = loginUserRequestConfig(username = username, password = password) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -345,24 +335,22 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param password The password for login in clear text * @return RequestConfig */ - fun loginUserRequestConfig(username: kotlin.String, password: kotlin.String) : RequestConfig { - val localVariableBody: kotlin.Any? = null + 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() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/user/login", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -377,7 +365,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun logoutUser() : Unit { val localVariableConfig = logoutUserRequestConfig() - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -401,20 +389,18 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * * @return RequestConfig */ - fun logoutUserRequestConfig() : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun logoutUserRequestConfig() : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/user/logout", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -431,7 +417,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun updateUser(username: kotlin.String, body: User) : Unit { val localVariableConfig = updateUserRequestConfig(username = username, body = body) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -457,20 +443,18 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param body Updated user object * @return RequestConfig */ - fun updateUserRequestConfig(username: kotlin.String, body: User) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun updateUserRequestConfig(username: kotlin.String, body: User) : RequestConfig { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.PUT, path = "/user/{username}".replace("{"+"username"+"}", "$username"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } } 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 bc9ed02c0f1..ae6e80e9506 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 @@ -1,6 +1,5 @@ package org.openapitools.client.infrastructure -import okhttp3.Credentials import okhttp3.OkHttpClient import okhttp3.RequestBody import okhttp3.RequestBody.Companion.asRequestBody @@ -12,17 +11,17 @@ import okhttp3.MediaType.Companion.toMediaTypeOrNull import okhttp3.Request import okhttp3.Headers import okhttp3.MultipartBody -import java.io.File import java.io.BufferedWriter +import java.io.File import java.io.FileWriter import java.net.URLConnection -import java.nio.file.Files -import java.util.Date import java.time.LocalDate import java.time.LocalDateTime import java.time.LocalTime import java.time.OffsetDateTime import java.time.OffsetTime +import java.util.Date +import java.util.Locale open class ApiClient(val baseUrl: String) { companion object { @@ -62,9 +61,7 @@ open class ApiClient(val baseUrl: String) { protected inline fun requestBody(content: T, mediaType: String = JsonMediaType): RequestBody = when { - content is File -> content.asRequestBody( - mediaType.toMediaTypeOrNull() - ) + content is File -> content.asRequestBody(mediaType.toMediaTypeOrNull()) mediaType == FormDataMediaType -> { MultipartBody.Builder() .setType(MultipartBody.FORM) @@ -119,7 +116,7 @@ open class ApiClient(val baseUrl: String) { } if (T::class.java == File::class.java) { // return tempfile - val f = Files.createTempFile("tmp.org.openapitools.client", null).toFile() + val f = java.nio.file.Files.createTempFile("tmp.org.openapitools.client", null).toFile() f.deleteOnExit() val out = BufferedWriter(FileWriter(f)) out.write(bodyContent) @@ -132,7 +129,7 @@ open class ApiClient(val baseUrl: String) { } } - protected fun updateAuthParams(requestConfig: RequestConfig) { + protected fun updateAuthParams(requestConfig: RequestConfig) { if (requestConfig.headers["api_key"].isNullOrEmpty()) { if (apiKey["api_key"] != null) { if (apiKeyPrefix["api_key"] != null) { @@ -149,7 +146,7 @@ open class ApiClient(val baseUrl: String) { } } - protected inline fun request(requestConfig: RequestConfig): ApiInfrastructureResponse { + protected inline fun request(requestConfig: RequestConfig): ApiInfrastructureResponse { val httpUrl = baseUrl.toHttpUrlOrNull() ?: throw IllegalStateException("baseUrl is invalid.") // take authMethod from operation @@ -183,7 +180,7 @@ open class ApiClient(val baseUrl: String) { } // TODO: support multiple contentType options here. - val contentType = (headers[ContentType] as String).substringBefore(";").toLowerCase() + val contentType = (headers[ContentType] as String).substringBefore(";").lowercase(Locale.getDefault()) val request = when (requestConfig.method) { RequestMethod.DELETE -> Request.Builder().url(url).delete(requestBody(requestConfig.body, contentType)) @@ -198,57 +195,46 @@ open class ApiClient(val baseUrl: String) { }.build() val response = client.newCall(request).execute() - val accept = response.header(ContentType)?.substringBefore(";")?.toLowerCase() + val accept = response.header(ContentType)?.substringBefore(";")?.lowercase(Locale.getDefault()) // TODO: handle specific mapping types. e.g. Map> - when { - response.isRedirect -> return Redirection( - response.code, - response.headers.toMultimap() + return when { + response.isRedirect -> Redirection( + response.code, + response.headers.toMultimap() ) - response.isInformational -> return Informational( - response.message, - response.code, - response.headers.toMultimap() + response.isInformational -> Informational( + response.message, + response.code, + response.headers.toMultimap() ) - response.isSuccessful -> return Success( - responseBody(response.body, accept), - response.code, - response.headers.toMultimap() + response.isSuccessful -> Success( + responseBody(response.body, accept), + response.code, + response.headers.toMultimap() ) - response.isClientError -> return ClientError( - response.message, - response.body?.string(), - response.code, - response.headers.toMultimap() + response.isClientError -> ClientError( + response.message, + response.body?.string(), + response.code, + response.headers.toMultimap() ) - else -> return ServerError( - 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 -> { - return "" - } - is Array<*> -> { - return toMultiValue(value, "csv").toString() - } - is Iterable<*> -> { - return toMultiValue(value, "csv").toString() - } - is OffsetDateTime, is OffsetTime, is LocalDateTime, is LocalDate, is LocalTime, is Date -> { - return parseDateToQueryString(value) - } - else -> { - return value.toString() - } - } + 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, is Date -> + parseDateToQueryString(value) + else -> value.toString() } protected inline fun parseDateToQueryString(value : T): String { 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 0f2790f370e..7e948e1dd07 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 @@ -8,10 +8,10 @@ package org.openapitools.client.infrastructure * NOTE: Headers is a Map because rfc2616 defines * multi-valued headers as csv-only. */ -data class RequestConfig( +data class RequestConfig( val method: RequestMethod, val path: String, val headers: MutableMap = mutableMapOf(), val query: MutableMap> = mutableMapOf(), - val body: kotlin.Any? = null + val body: T? = null ) \ No newline at end of file diff --git a/samples/client/petstore/kotlin-nullable/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt b/samples/client/petstore/kotlin-nullable/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt index 3d0a6c32566..e77581231c3 100644 --- a/samples/client/petstore/kotlin-nullable/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt +++ b/samples/client/petstore/kotlin-nullable/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt @@ -12,6 +12,7 @@ object Serializer { .add(LocalDateAdapter()) .add(UUIDAdapter()) .add(ByteArrayAdapter()) + .add(URIAdapter()) .add(KotlinJsonAdapterFactory()) .add(BigDecimalAdapter()) .add(BigIntegerAdapter()) diff --git a/samples/client/petstore/kotlin-nullable/src/main/kotlin/org/openapitools/client/infrastructure/URIAdapter.kt b/samples/client/petstore/kotlin-nullable/src/main/kotlin/org/openapitools/client/infrastructure/URIAdapter.kt new file mode 100644 index 00000000000..927522757da --- /dev/null +++ b/samples/client/petstore/kotlin-nullable/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-nullable/src/main/kotlin/org/openapitools/client/infrastructure/UUIDAdapter.kt b/samples/client/petstore/kotlin-nullable/src/main/kotlin/org/openapitools/client/infrastructure/UUIDAdapter.kt index a4a44cc18b7..7ccf7dc25d2 100644 --- a/samples/client/petstore/kotlin-nullable/src/main/kotlin/org/openapitools/client/infrastructure/UUIDAdapter.kt +++ b/samples/client/petstore/kotlin-nullable/src/main/kotlin/org/openapitools/client/infrastructure/UUIDAdapter.kt @@ -9,5 +9,5 @@ class UUIDAdapter { fun toJson(uuid: UUID) = uuid.toString() @FromJson - fun fromJson(s: String) = UUID.fromString(s) + fun fromJson(s: String): UUID = UUID.fromString(s) } diff --git a/samples/client/petstore/kotlin-okhttp3/.openapi-generator/FILES b/samples/client/petstore/kotlin-okhttp3/.openapi-generator/FILES index 3f4610174cc..16c712325f8 100644 --- a/samples/client/petstore/kotlin-okhttp3/.openapi-generator/FILES +++ b/samples/client/petstore/kotlin-okhttp3/.openapi-generator/FILES @@ -20,7 +20,6 @@ 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/ApiInfrastructureResponse.kt -src/main/kotlin/org/openapitools/client/infrastructure/ApplicationDelegates.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 @@ -32,6 +31,7 @@ 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/ApiResponse.kt src/main/kotlin/org/openapitools/client/models/Category.kt diff --git a/samples/client/petstore/kotlin-okhttp3/.openapi-generator/VERSION b/samples/client/petstore/kotlin-okhttp3/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/client/petstore/kotlin-okhttp3/.openapi-generator/VERSION +++ b/samples/client/petstore/kotlin-okhttp3/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/client/petstore/kotlin-okhttp3/build.gradle b/samples/client/petstore/kotlin-okhttp3/build.gradle index 1da4409df35..4d9f2f630d4 100644 --- a/samples/client/petstore/kotlin-okhttp3/build.gradle +++ b/samples/client/petstore/kotlin-okhttp3/build.gradle @@ -7,7 +7,7 @@ wrapper { } buildscript { - ext.kotlin_version = '1.4.30' + ext.kotlin_version = '1.5.10' repositories { maven { url "https://repo1.maven.org/maven2" } @@ -28,9 +28,9 @@ test { } dependencies { - compile "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version" - compile "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version" - compile "com.squareup.moshi:moshi-kotlin:1.11.0" - compile "com.squareup.okhttp3:okhttp:3.12.13" - testCompile "io.kotlintest:kotlintest-runner-junit5:3.4.2" + implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version" + implementation "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version" + implementation "com.squareup.moshi:moshi-kotlin:1.12.0" + implementation "com.squareup.okhttp3:okhttp:3.12.13" + testImplementation "io.kotlintest:kotlintest-runner-junit5:3.4.2" } diff --git a/samples/client/petstore/kotlin-okhttp3/src/main/kotlin/org/openapitools/client/apis/PetApi.kt b/samples/client/petstore/kotlin-okhttp3/src/main/kotlin/org/openapitools/client/apis/PetApi.kt index c8b93b33bf6..be50dd6c442 100644 --- a/samples/client/petstore/kotlin-okhttp3/src/main/kotlin/org/openapitools/client/apis/PetApi.kt +++ b/samples/client/petstore/kotlin-okhttp3/src/main/kotlin/org/openapitools/client/apis/PetApi.kt @@ -47,7 +47,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun addPet(body: Pet) : Unit { val localVariableConfig = addPetRequestConfig(body = body) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -72,20 +72,18 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param body Pet object that needs to be added to the store * @return RequestConfig */ - fun addPetRequestConfig(body: Pet) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun addPetRequestConfig(body: Pet) : RequestConfig { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/pet", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -102,7 +100,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun deletePet(petId: kotlin.Long, apiKey: kotlin.String?) : Unit { val localVariableConfig = deletePetRequestConfig(petId = petId, apiKey = apiKey) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -128,21 +126,19 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param apiKey (optional) * @return RequestConfig */ - fun deletePetRequestConfig(petId: kotlin.Long, apiKey: kotlin.String?) : RequestConfig { - val localVariableBody: kotlin.Any? = null + 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() } - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.DELETE, path = "/pet/{petId}".replace("{"+"petId"+"}", "$petId"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -159,7 +155,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun findPetsByStatus(status: kotlin.collections.List) : kotlin.collections.List { val localVariableConfig = findPetsByStatusRequestConfig(status = status) - val localVarResponse = request>( + val localVarResponse = request>( localVariableConfig ) @@ -184,23 +180,21 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param status Status values that need to be considered for filter * @return RequestConfig */ - fun findPetsByStatusRequestConfig(status: kotlin.collections.List) : RequestConfig { - val localVariableBody: kotlin.Any? = null + 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() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/pet/findByStatus", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -216,9 +210,10 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { @Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class) @Deprecated(message = "This operation is deprecated.") fun findPetsByTags(tags: kotlin.collections.List) : kotlin.collections.List { + @Suppress("DEPRECATION") val localVariableConfig = findPetsByTagsRequestConfig(tags = tags) - val localVarResponse = request>( + val localVarResponse = request>( localVariableConfig ) @@ -244,23 +239,21 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @return RequestConfig */ @Deprecated(message = "This operation is deprecated.") - fun findPetsByTagsRequestConfig(tags: kotlin.collections.List) : RequestConfig { - val localVariableBody: kotlin.Any? = null + 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() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/pet/findByTags", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -277,7 +270,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun getPetById(petId: kotlin.Long) : Pet { val localVariableConfig = getPetByIdRequestConfig(petId = petId) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -302,20 +295,18 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param petId ID of pet to return * @return RequestConfig */ - fun getPetByIdRequestConfig(petId: kotlin.Long) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun getPetByIdRequestConfig(petId: kotlin.Long) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/pet/{petId}".replace("{"+"petId"+"}", "$petId"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -331,7 +322,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun updatePet(body: Pet) : Unit { val localVariableConfig = updatePetRequestConfig(body = body) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -356,20 +347,18 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param body Pet object that needs to be added to the store * @return RequestConfig */ - fun updatePetRequestConfig(body: Pet) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun updatePetRequestConfig(body: Pet) : RequestConfig { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.PUT, path = "/pet", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -387,7 +376,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun updatePetWithForm(petId: kotlin.Long, name: kotlin.String?, status: kotlin.String?) : Unit { val localVariableConfig = updatePetWithFormRequestConfig(petId = petId, name = name, status = status) - val localVarResponse = request( + val localVarResponse = request, Unit>( localVariableConfig ) @@ -414,20 +403,18 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param status Updated status of the pet (optional) * @return RequestConfig */ - fun updatePetWithFormRequestConfig(petId: kotlin.Long, name: kotlin.String?, status: kotlin.String?) : RequestConfig { - val localVariableBody: kotlin.Any? = mapOf("name" to name, "status" to status) + fun updatePetWithFormRequestConfig(petId: kotlin.Long, name: kotlin.String?, status: kotlin.String?) : RequestConfig> { + val localVariableBody = mapOf("name" to name, "status" to status) val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf("Content-Type" to "application/x-www-form-urlencoded") - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/pet/{petId}".replace("{"+"petId"+"}", "$petId"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -446,7 +433,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun uploadFile(petId: kotlin.Long, additionalMetadata: kotlin.String?, file: java.io.File?) : ApiResponse { val localVariableConfig = uploadFileRequestConfig(petId = petId, additionalMetadata = additionalMetadata, file = file) - val localVarResponse = request( + val localVarResponse = request, ApiResponse>( localVariableConfig ) @@ -473,20 +460,18 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param file file to upload (optional) * @return RequestConfig */ - fun uploadFileRequestConfig(petId: kotlin.Long, additionalMetadata: kotlin.String?, file: java.io.File?) : RequestConfig { - val localVariableBody: kotlin.Any? = mapOf("additionalMetadata" to additionalMetadata, "file" to file) + fun uploadFileRequestConfig(petId: kotlin.Long, additionalMetadata: kotlin.String?, file: java.io.File?) : RequestConfig> { + val localVariableBody = mapOf("additionalMetadata" to additionalMetadata, "file" to file) val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf("Content-Type" to "multipart/form-data") - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/pet/{petId}/uploadImage".replace("{"+"petId"+"}", "$petId"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } } diff --git a/samples/client/petstore/kotlin-okhttp3/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt b/samples/client/petstore/kotlin-okhttp3/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt index 215ed63420c..56a23202f82 100644 --- a/samples/client/petstore/kotlin-okhttp3/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt +++ b/samples/client/petstore/kotlin-okhttp3/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt @@ -46,7 +46,7 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) fun deleteOrder(orderId: kotlin.String) : Unit { val localVariableConfig = deleteOrderRequestConfig(orderId = orderId) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -71,20 +71,18 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) * @param orderId ID of the order that needs to be deleted * @return RequestConfig */ - fun deleteOrderRequestConfig(orderId: kotlin.String) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun deleteOrderRequestConfig(orderId: kotlin.String) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.DELETE, path = "/store/order/{orderId}".replace("{"+"orderId"+"}", "$orderId"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -100,7 +98,7 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) fun getInventory() : kotlin.collections.Map { val localVariableConfig = getInventoryRequestConfig() - val localVarResponse = request>( + val localVarResponse = request>( localVariableConfig ) @@ -124,20 +122,18 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) * * @return RequestConfig */ - fun getInventoryRequestConfig() : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun getInventoryRequestConfig() : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/store/inventory", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -154,7 +150,7 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) fun getOrderById(orderId: kotlin.Long) : Order { val localVariableConfig = getOrderByIdRequestConfig(orderId = orderId) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -179,20 +175,18 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) * @param orderId ID of pet that needs to be fetched * @return RequestConfig */ - fun getOrderByIdRequestConfig(orderId: kotlin.Long) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun getOrderByIdRequestConfig(orderId: kotlin.Long) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/store/order/{orderId}".replace("{"+"orderId"+"}", "$orderId"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -209,7 +203,7 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) fun placeOrder(body: Order) : Order { val localVariableConfig = placeOrderRequestConfig(body = body) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -234,20 +228,18 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) * @param body order placed for purchasing the pet * @return RequestConfig */ - fun placeOrderRequestConfig(body: Order) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun placeOrderRequestConfig(body: Order) : RequestConfig { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/store/order", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } } diff --git a/samples/client/petstore/kotlin-okhttp3/src/main/kotlin/org/openapitools/client/apis/UserApi.kt b/samples/client/petstore/kotlin-okhttp3/src/main/kotlin/org/openapitools/client/apis/UserApi.kt index 53748b93463..9f93e853a12 100644 --- a/samples/client/petstore/kotlin-okhttp3/src/main/kotlin/org/openapitools/client/apis/UserApi.kt +++ b/samples/client/petstore/kotlin-okhttp3/src/main/kotlin/org/openapitools/client/apis/UserApi.kt @@ -46,7 +46,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun createUser(body: User) : Unit { val localVariableConfig = createUserRequestConfig(body = body) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -71,20 +71,18 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param body Created user object * @return RequestConfig */ - fun createUserRequestConfig(body: User) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun createUserRequestConfig(body: User) : RequestConfig { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/user", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -100,7 +98,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun createUsersWithArrayInput(body: kotlin.collections.List) : Unit { val localVariableConfig = createUsersWithArrayInputRequestConfig(body = body) - val localVarResponse = request( + val localVarResponse = request, Unit>( localVariableConfig ) @@ -125,20 +123,18 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param body List of user object * @return RequestConfig */ - fun createUsersWithArrayInputRequestConfig(body: kotlin.collections.List) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun createUsersWithArrayInputRequestConfig(body: kotlin.collections.List) : RequestConfig> { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/user/createWithArray", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -154,7 +150,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun createUsersWithListInput(body: kotlin.collections.List) : Unit { val localVariableConfig = createUsersWithListInputRequestConfig(body = body) - val localVarResponse = request( + val localVarResponse = request, Unit>( localVariableConfig ) @@ -179,20 +175,18 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param body List of user object * @return RequestConfig */ - fun createUsersWithListInputRequestConfig(body: kotlin.collections.List) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun createUsersWithListInputRequestConfig(body: kotlin.collections.List) : RequestConfig> { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/user/createWithList", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -208,7 +202,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun deleteUser(username: kotlin.String) : Unit { val localVariableConfig = deleteUserRequestConfig(username = username) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -233,20 +227,18 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param username The name that needs to be deleted * @return RequestConfig */ - fun deleteUserRequestConfig(username: kotlin.String) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun deleteUserRequestConfig(username: kotlin.String) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.DELETE, path = "/user/{username}".replace("{"+"username"+"}", "$username"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -263,7 +255,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun getUserByName(username: kotlin.String) : User { val localVariableConfig = getUserByNameRequestConfig(username = username) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -288,20 +280,18 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param username The name that needs to be fetched. Use user1 for testing. * @return RequestConfig */ - fun getUserByNameRequestConfig(username: kotlin.String) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun getUserByNameRequestConfig(username: kotlin.String) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/user/{username}".replace("{"+"username"+"}", "$username"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -319,7 +309,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun loginUser(username: kotlin.String, password: kotlin.String) : kotlin.String { val localVariableConfig = loginUserRequestConfig(username = username, password = password) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -345,24 +335,22 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param password The password for login in clear text * @return RequestConfig */ - fun loginUserRequestConfig(username: kotlin.String, password: kotlin.String) : RequestConfig { - val localVariableBody: kotlin.Any? = null + 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() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/user/login", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -377,7 +365,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun logoutUser() : Unit { val localVariableConfig = logoutUserRequestConfig() - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -401,20 +389,18 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * * @return RequestConfig */ - fun logoutUserRequestConfig() : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun logoutUserRequestConfig() : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/user/logout", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -431,7 +417,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun updateUser(username: kotlin.String, body: User) : Unit { val localVariableConfig = updateUserRequestConfig(username = username, body = body) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -457,20 +443,18 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param body Updated user object * @return RequestConfig */ - fun updateUserRequestConfig(username: kotlin.String, body: User) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun updateUserRequestConfig(username: kotlin.String, body: User) : RequestConfig { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.PUT, path = "/user/{username}".replace("{"+"username"+"}", "$username"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } } 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 8fad7b08960..538c66cec2e 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 @@ -1,6 +1,5 @@ package org.openapitools.client.infrastructure -import okhttp3.Credentials import okhttp3.OkHttpClient import okhttp3.RequestBody import okhttp3.MediaType @@ -10,17 +9,17 @@ import okhttp3.ResponseBody import okhttp3.Request import okhttp3.Headers import okhttp3.MultipartBody -import java.io.File import java.io.BufferedWriter +import java.io.File import java.io.FileWriter import java.net.URLConnection -import java.nio.file.Files -import java.util.Date import java.time.LocalDate import java.time.LocalDateTime import java.time.LocalTime import java.time.OffsetDateTime import java.time.OffsetTime +import java.util.Date +import java.util.Locale open class ApiClient(val baseUrl: String) { companion object { @@ -60,9 +59,7 @@ open class ApiClient(val baseUrl: String) { protected inline fun requestBody(content: T, mediaType: String = JsonMediaType): RequestBody = when { - content is File -> RequestBody.create( - MediaType.parse(mediaType), content - ) + content is File -> RequestBody.create(MediaType.parse(mediaType), content) mediaType == FormDataMediaType -> { MultipartBody.Builder() .setType(MultipartBody.FORM) @@ -117,7 +114,7 @@ open class ApiClient(val baseUrl: String) { } if (T::class.java == File::class.java) { // return tempfile - val f = Files.createTempFile("tmp.org.openapitools.client", null).toFile() + val f = java.nio.file.Files.createTempFile("tmp.org.openapitools.client", null).toFile() f.deleteOnExit() val out = BufferedWriter(FileWriter(f)) out.write(bodyContent) @@ -130,7 +127,7 @@ open class ApiClient(val baseUrl: String) { } } - protected fun updateAuthParams(requestConfig: RequestConfig) { + protected fun updateAuthParams(requestConfig: RequestConfig) { if (requestConfig.headers["api_key"].isNullOrEmpty()) { if (apiKey["api_key"] != null) { if (apiKeyPrefix["api_key"] != null) { @@ -147,7 +144,7 @@ open class ApiClient(val baseUrl: String) { } } - protected inline fun request(requestConfig: RequestConfig): ApiInfrastructureResponse { + protected inline fun request(requestConfig: RequestConfig): ApiInfrastructureResponse { val httpUrl = HttpUrl.parse(baseUrl) ?: throw IllegalStateException("baseUrl is invalid.") // take authMethod from operation @@ -181,7 +178,7 @@ open class ApiClient(val baseUrl: String) { } // TODO: support multiple contentType options here. - val contentType = (headers[ContentType] as String).substringBefore(";").toLowerCase() + val contentType = (headers[ContentType] as String).substringBefore(";").lowercase(Locale.getDefault()) val request = when (requestConfig.method) { RequestMethod.DELETE -> Request.Builder().url(url).delete(requestBody(requestConfig.body, contentType)) @@ -196,57 +193,46 @@ open class ApiClient(val baseUrl: String) { }.build() val response = client.newCall(request).execute() - val accept = response.header(ContentType)?.substringBefore(";")?.toLowerCase() + val accept = response.header(ContentType)?.substringBefore(";")?.lowercase(Locale.getDefault()) // TODO: handle specific mapping types. e.g. Map> - when { - response.isRedirect -> return Redirection( - response.code(), - response.headers().toMultimap() + return when { + response.isRedirect -> Redirection( + response.code(), + response.headers().toMultimap() ) - response.isInformational -> return Informational( - response.message(), - response.code(), - response.headers().toMultimap() + response.isInformational -> Informational( + response.message(), + response.code(), + response.headers().toMultimap() ) - response.isSuccessful -> return Success( - responseBody(response.body(), accept), - response.code(), - response.headers().toMultimap() + response.isSuccessful -> Success( + responseBody(response.body(), accept), + response.code(), + response.headers().toMultimap() ) - response.isClientError -> return ClientError( - response.message(), - response.body()?.string(), - response.code(), - response.headers().toMultimap() + response.isClientError -> ClientError( + response.message(), + response.body()?.string(), + response.code(), + response.headers().toMultimap() ) - else -> return ServerError( - 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 -> { - return "" - } - is Array<*> -> { - return toMultiValue(value, "csv").toString() - } - is Iterable<*> -> { - return toMultiValue(value, "csv").toString() - } - is OffsetDateTime, is OffsetTime, is LocalDateTime, is LocalDate, is LocalTime, is Date -> { - return parseDateToQueryString(value) - } - else -> { - return value.toString() - } - } + 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, is Date -> + parseDateToQueryString(value) + else -> value.toString() } protected inline fun parseDateToQueryString(value : T): String { 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 0f2790f370e..7e948e1dd07 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 @@ -8,10 +8,10 @@ package org.openapitools.client.infrastructure * NOTE: Headers is a Map because rfc2616 defines * multi-valued headers as csv-only. */ -data class RequestConfig( +data class RequestConfig( val method: RequestMethod, val path: String, val headers: MutableMap = mutableMapOf(), val query: MutableMap> = mutableMapOf(), - val body: kotlin.Any? = null + val body: T? = null ) \ No newline at end of file diff --git a/samples/client/petstore/kotlin-okhttp3/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt b/samples/client/petstore/kotlin-okhttp3/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt index 3d0a6c32566..e77581231c3 100644 --- a/samples/client/petstore/kotlin-okhttp3/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt +++ b/samples/client/petstore/kotlin-okhttp3/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt @@ -12,6 +12,7 @@ object Serializer { .add(LocalDateAdapter()) .add(UUIDAdapter()) .add(ByteArrayAdapter()) + .add(URIAdapter()) .add(KotlinJsonAdapterFactory()) .add(BigDecimalAdapter()) .add(BigIntegerAdapter()) diff --git a/samples/client/petstore/kotlin-okhttp3/src/main/kotlin/org/openapitools/client/infrastructure/URIAdapter.kt b/samples/client/petstore/kotlin-okhttp3/src/main/kotlin/org/openapitools/client/infrastructure/URIAdapter.kt new file mode 100644 index 00000000000..927522757da --- /dev/null +++ b/samples/client/petstore/kotlin-okhttp3/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-okhttp3/src/main/kotlin/org/openapitools/client/infrastructure/UUIDAdapter.kt b/samples/client/petstore/kotlin-okhttp3/src/main/kotlin/org/openapitools/client/infrastructure/UUIDAdapter.kt index a4a44cc18b7..7ccf7dc25d2 100644 --- a/samples/client/petstore/kotlin-okhttp3/src/main/kotlin/org/openapitools/client/infrastructure/UUIDAdapter.kt +++ b/samples/client/petstore/kotlin-okhttp3/src/main/kotlin/org/openapitools/client/infrastructure/UUIDAdapter.kt @@ -9,5 +9,5 @@ class UUIDAdapter { fun toJson(uuid: UUID) = uuid.toString() @FromJson - fun fromJson(s: String) = UUID.fromString(s) + fun fromJson(s: String): UUID = UUID.fromString(s) } 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 5f68295fc19..e8415097f3a 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,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/build.gradle b/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/build.gradle index dce987e0201..60257e31601 100644 --- a/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/build.gradle +++ b/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/build.gradle @@ -7,8 +7,8 @@ wrapper { } buildscript { - ext.kotlin_version = '1.4.30' - ext.retrofitVersion = '2.7.2' + ext.kotlin_version = '1.5.10' + ext.retrofitVersion = '2.9.0' repositories { maven { url "https://repo1.maven.org/maven2" } @@ -31,14 +31,14 @@ test { } dependencies { - compile "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version" - compile "org.jetbrains.kotlinx:kotlinx-serialization-json:1.1.0" - compile "org.apache.oltu.oauth2:org.apache.oltu.oauth2.client:1.0.0" - compile "com.squareup.okhttp3:logging-interceptor:4.9.0" - compile "com.squareup.retrofit2:retrofit:$retrofitVersion" - compile "com.jakewharton.retrofit:retrofit2-kotlinx-serialization-converter:0.8.0" - compile "com.squareup.retrofit2:converter-scalars:$retrofitVersion" - testCompile "io.kotlintest:kotlintest-runner-junit5:3.4.2" + implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version" + implementation "org.jetbrains.kotlinx:kotlinx-serialization-json:1.2.1" + implementation "org.apache.oltu.oauth2:org.apache.oltu.oauth2.client:1.0.2" + implementation "com.squareup.okhttp3:logging-interceptor:4.9.1" + implementation "com.squareup.retrofit2:retrofit:$retrofitVersion" + implementation "com.jakewharton.retrofit:retrofit2-kotlinx-serialization-converter:0.8.0" + implementation "com.squareup.retrofit2:converter-scalars:$retrofitVersion" + testImplementation "io.kotlintest:kotlintest-runner-junit5:3.4.2" } tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinCompile).configureEach { diff --git a/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/src/main/kotlin/org/openapitools/client/apis/PetApi.kt b/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/src/main/kotlin/org/openapitools/client/apis/PetApi.kt index 3b2a4128209..d30336f02e9 100644 --- a/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/src/main/kotlin/org/openapitools/client/apis/PetApi.kt +++ b/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/src/main/kotlin/org/openapitools/client/apis/PetApi.kt @@ -34,7 +34,7 @@ interface PetApi { * @return [Call]<[Unit]> */ @DELETE("pet/{petId}") - fun deletePet(@Path("petId") petId: kotlin.Long, @Header("api_key") apiKey: kotlin.String): Call + fun deletePet(@Path("petId") petId: kotlin.Long, @Header("api_key") apiKey: kotlin.String? = null): Call /** * Finds Pets by status diff --git a/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/src/main/kotlin/org/openapitools/client/auth/OAuthOkHttpClient.kt b/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/src/main/kotlin/org/openapitools/client/auth/OAuthOkHttpClient.kt index 93adbda3fc9..aa70ca9d2f1 100644 --- a/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/src/main/kotlin/org/openapitools/client/auth/OAuthOkHttpClient.kt +++ b/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/src/main/kotlin/org/openapitools/client/auth/OAuthOkHttpClient.kt @@ -13,14 +13,13 @@ 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 + private var client: OkHttpClient = OkHttpClient() ) : HttpClient { - constructor() : this(OkHttpClient()) - @Throws(OAuthSystemException::class, OAuthProblemException::class) override fun execute( request: OAuthClientRequest, @@ -39,7 +38,7 @@ class OAuthOkHttpClient( } } - val body: RequestBody? = if (request.body != null) RequestBody.create(mediaType, request.body) else null + val body: RequestBody? = if (request.body != null) request.body.toRequestBody(mediaType) else null requestBuilder.method(requestMethod, body) try { @@ -48,6 +47,7 @@ class OAuthOkHttpClient( response.body?.string(), response.body?.contentType()?.toString(), response.code, + response.headers.toMultimap(), responseClass) } catch (e: IOException) { throw OAuthSystemException(e) 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 a5aaa332be8..3bb7d9c4d66 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 @@ -7,6 +7,7 @@ import org.openapitools.client.auth.OAuth import org.openapitools.client.auth.OAuth.AccessTokenListener import org.openapitools.client.auth.OAuthFlow +import okhttp3.Call import okhttp3.Interceptor import okhttp3.OkHttpClient import retrofit2.Retrofit @@ -21,7 +22,7 @@ import okhttp3.MediaType.Companion.toMediaType class ApiClient( private var baseUrl: String = defaultBasePath, private val okHttpClientBuilder: OkHttpClient.Builder? = null, - private val okHttpClient : OkHttpClient? = null, + private val callFactory : Call.Factory? = null, private val converterFactory: Converter.Factory? = null, ) { private val apiAuthorizations = mutableMapOf() @@ -180,8 +181,8 @@ class ApiClient( } fun createService(serviceClass: Class): S { - val usedClient = this.okHttpClient ?: clientBuilder.build() - return retrofitBuilder.client(usedClient).build().create(serviceClass) + val usedCallFactory = this.callFactory ?: clientBuilder.build() + return retrofitBuilder.callFactory(usedCallFactory).build().create(serviceClass) } private fun normalizeBaseUrl() { diff --git a/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt b/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt index 624053c3074..e769dec78ea 100644 --- a/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt +++ b/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt @@ -28,8 +28,8 @@ object Serializer { contextual(AtomicInteger::class, AtomicIntegerAdapter) contextual(AtomicLong::class, AtomicLongAdapter) contextual(AtomicBoolean::class, AtomicBooleanAdapter) - contextual(URI::class, UriAdapter) - contextual(URL::class, UrlAdapter) + contextual(URI::class, URIAdapter) + contextual(URL::class, URLAdapter) contextual(StringBuilder::class, StringBuilderAdapter) } diff --git a/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/src/main/kotlin/org/openapitools/client/infrastructure/URIAdapter.kt b/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/src/main/kotlin/org/openapitools/client/infrastructure/URIAdapter.kt index ef3c2b387be..0856c99813c 100644 --- a/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/src/main/kotlin/org/openapitools/client/infrastructure/URIAdapter.kt +++ b/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/src/main/kotlin/org/openapitools/client/infrastructure/URIAdapter.kt @@ -10,7 +10,7 @@ import kotlinx.serialization.descriptors.SerialDescriptor import java.net.URI @Serializer(forClass = URI::class) -object UriAdapter : KSerializer { +object URIAdapter : KSerializer { override fun serialize(encoder: Encoder, value: URI) { encoder.encodeString(value.toASCIIString()) } @@ -18,4 +18,4 @@ object UriAdapter : KSerializer { override fun deserialize(decoder: Decoder): URI = URI(decoder.decodeString()) override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("URI", PrimitiveKind.STRING) -} \ No newline at end of file +} diff --git a/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/src/main/kotlin/org/openapitools/client/infrastructure/URLAdapter.kt b/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/src/main/kotlin/org/openapitools/client/infrastructure/URLAdapter.kt index 29546fc3ce9..2df3308b76a 100644 --- a/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/src/main/kotlin/org/openapitools/client/infrastructure/URLAdapter.kt +++ b/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/src/main/kotlin/org/openapitools/client/infrastructure/URLAdapter.kt @@ -10,7 +10,7 @@ import kotlinx.serialization.descriptors.SerialDescriptor import java.net.URL @Serializer(forClass = URL::class) -object UrlAdapter : KSerializer { +object URLAdapter : KSerializer { override fun serialize(encoder: Encoder, value: URL) { encoder.encodeString(value.toExternalForm()) } diff --git a/samples/client/petstore/kotlin-retrofit2-rx3/.openapi-generator/FILES b/samples/client/petstore/kotlin-retrofit2-rx3/.openapi-generator/FILES index 871f0c1d09c..04b505d1f17 100644 --- a/samples/client/petstore/kotlin-retrofit2-rx3/.openapi-generator/FILES +++ b/samples/client/petstore/kotlin-retrofit2-rx3/.openapi-generator/FILES @@ -31,6 +31,7 @@ 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/ResponseExt.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/ApiResponse.kt src/main/kotlin/org/openapitools/client/models/Category.kt diff --git a/samples/client/petstore/kotlin-retrofit2-rx3/.openapi-generator/VERSION b/samples/client/petstore/kotlin-retrofit2-rx3/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/client/petstore/kotlin-retrofit2-rx3/.openapi-generator/VERSION +++ b/samples/client/petstore/kotlin-retrofit2-rx3/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/client/petstore/kotlin-retrofit2-rx3/build.gradle b/samples/client/petstore/kotlin-retrofit2-rx3/build.gradle index b55dfb35245..2f5e94a4fcd 100644 --- a/samples/client/petstore/kotlin-retrofit2-rx3/build.gradle +++ b/samples/client/petstore/kotlin-retrofit2-rx3/build.gradle @@ -7,9 +7,9 @@ wrapper { } buildscript { - ext.kotlin_version = '1.4.30' - ext.retrofitVersion = '2.7.2' - ext.rxJava3Version = '3.0.10' + ext.kotlin_version = '1.5.10' + ext.retrofitVersion = '2.9.0' + ext.rxJava3Version = '3.0.12' repositories { maven { url "https://repo1.maven.org/maven2" } @@ -30,15 +30,15 @@ test { } dependencies { - compile "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version" - compile "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version" - compile "com.squareup.moshi:moshi-kotlin:1.11.0" - compile "org.apache.oltu.oauth2:org.apache.oltu.oauth2.client:1.0.0" - compile "com.squareup.okhttp3:logging-interceptor:4.9.0" - compile "io.reactivex.rxjava3:rxjava:$rxJava3Version" - compile "com.squareup.retrofit2:adapter-rxjava3:2.9.0" - compile "com.squareup.retrofit2:retrofit:$retrofitVersion" - compile "com.squareup.retrofit2:converter-moshi:$retrofitVersion" - compile "com.squareup.retrofit2:converter-scalars:$retrofitVersion" - testCompile "io.kotlintest:kotlintest-runner-junit5:3.4.2" + implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version" + implementation "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version" + implementation "com.squareup.moshi:moshi-kotlin:1.12.0" + implementation "org.apache.oltu.oauth2:org.apache.oltu.oauth2.client:1.0.2" + implementation "com.squareup.okhttp3:logging-interceptor:4.9.1" + implementation "io.reactivex.rxjava3:rxjava:$rxJava3Version" + implementation "com.squareup.retrofit2:adapter-rxjava3:2.9.0" + implementation "com.squareup.retrofit2:retrofit:$retrofitVersion" + implementation "com.squareup.retrofit2:converter-moshi:$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-rx3/src/main/kotlin/org/openapitools/client/apis/PetApi.kt b/samples/client/petstore/kotlin-retrofit2-rx3/src/main/kotlin/org/openapitools/client/apis/PetApi.kt index 8162b6dc448..d90c3c85f92 100644 --- a/samples/client/petstore/kotlin-retrofit2-rx3/src/main/kotlin/org/openapitools/client/apis/PetApi.kt +++ b/samples/client/petstore/kotlin-retrofit2-rx3/src/main/kotlin/org/openapitools/client/apis/PetApi.kt @@ -35,7 +35,7 @@ interface PetApi { * @return [Call]<[Unit]> */ @DELETE("pet/{petId}") - fun deletePet(@Path("petId") petId: kotlin.Long, @Header("api_key") apiKey: kotlin.String): Completable + fun deletePet(@Path("petId") petId: kotlin.Long, @Header("api_key") apiKey: kotlin.String? = null): Completable /** * Finds Pets by status diff --git a/samples/client/petstore/kotlin-retrofit2-rx3/src/main/kotlin/org/openapitools/client/auth/OAuthOkHttpClient.kt b/samples/client/petstore/kotlin-retrofit2-rx3/src/main/kotlin/org/openapitools/client/auth/OAuthOkHttpClient.kt index 93adbda3fc9..aa70ca9d2f1 100644 --- a/samples/client/petstore/kotlin-retrofit2-rx3/src/main/kotlin/org/openapitools/client/auth/OAuthOkHttpClient.kt +++ b/samples/client/petstore/kotlin-retrofit2-rx3/src/main/kotlin/org/openapitools/client/auth/OAuthOkHttpClient.kt @@ -13,14 +13,13 @@ 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 + private var client: OkHttpClient = OkHttpClient() ) : HttpClient { - constructor() : this(OkHttpClient()) - @Throws(OAuthSystemException::class, OAuthProblemException::class) override fun execute( request: OAuthClientRequest, @@ -39,7 +38,7 @@ class OAuthOkHttpClient( } } - val body: RequestBody? = if (request.body != null) RequestBody.create(mediaType, request.body) else null + val body: RequestBody? = if (request.body != null) request.body.toRequestBody(mediaType) else null requestBuilder.method(requestMethod, body) try { @@ -48,6 +47,7 @@ class OAuthOkHttpClient( response.body?.string(), response.body?.contentType()?.toString(), response.code, + response.headers.toMultimap(), responseClass) } catch (e: IOException) { throw OAuthSystemException(e) 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 cc63b570177..51a186e48fa 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 @@ -7,6 +7,7 @@ import org.openapitools.client.auth.OAuth import org.openapitools.client.auth.OAuth.AccessTokenListener import org.openapitools.client.auth.OAuthFlow +import okhttp3.Call import okhttp3.Interceptor import okhttp3.OkHttpClient import retrofit2.Retrofit @@ -22,7 +23,7 @@ class ApiClient( private var baseUrl: String = defaultBasePath, private val okHttpClientBuilder: OkHttpClient.Builder? = null, private val serializerBuilder: Moshi.Builder = Serializer.moshiBuilder, - private val okHttpClient : OkHttpClient? = null, + private val callFactory : Call.Factory? = null, private val converterFactory: Converter.Factory? = null, ) { private val apiAuthorizations = mutableMapOf() @@ -183,8 +184,8 @@ class ApiClient( } fun createService(serviceClass: Class): S { - val usedClient = this.okHttpClient ?: clientBuilder.build() - return retrofitBuilder.client(usedClient).build().create(serviceClass) + val usedCallFactory = this.callFactory ?: clientBuilder.build() + return retrofitBuilder.callFactory(usedCallFactory).build().create(serviceClass) } private fun normalizeBaseUrl() { diff --git a/samples/client/petstore/kotlin-retrofit2-rx3/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt b/samples/client/petstore/kotlin-retrofit2-rx3/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt index 3d0a6c32566..e77581231c3 100644 --- a/samples/client/petstore/kotlin-retrofit2-rx3/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt +++ b/samples/client/petstore/kotlin-retrofit2-rx3/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt @@ -12,6 +12,7 @@ object Serializer { .add(LocalDateAdapter()) .add(UUIDAdapter()) .add(ByteArrayAdapter()) + .add(URIAdapter()) .add(KotlinJsonAdapterFactory()) .add(BigDecimalAdapter()) .add(BigIntegerAdapter()) diff --git a/samples/client/petstore/kotlin-retrofit2-rx3/src/main/kotlin/org/openapitools/client/infrastructure/URIAdapter.kt b/samples/client/petstore/kotlin-retrofit2-rx3/src/main/kotlin/org/openapitools/client/infrastructure/URIAdapter.kt new file mode 100644 index 00000000000..927522757da --- /dev/null +++ b/samples/client/petstore/kotlin-retrofit2-rx3/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-retrofit2-rx3/src/main/kotlin/org/openapitools/client/infrastructure/UUIDAdapter.kt b/samples/client/petstore/kotlin-retrofit2-rx3/src/main/kotlin/org/openapitools/client/infrastructure/UUIDAdapter.kt index a4a44cc18b7..7ccf7dc25d2 100644 --- a/samples/client/petstore/kotlin-retrofit2-rx3/src/main/kotlin/org/openapitools/client/infrastructure/UUIDAdapter.kt +++ b/samples/client/petstore/kotlin-retrofit2-rx3/src/main/kotlin/org/openapitools/client/infrastructure/UUIDAdapter.kt @@ -9,5 +9,5 @@ class UUIDAdapter { fun toJson(uuid: UUID) = uuid.toString() @FromJson - fun fromJson(s: String) = UUID.fromString(s) + fun fromJson(s: String): UUID = UUID.fromString(s) } diff --git a/samples/client/petstore/kotlin-retrofit2/.openapi-generator/FILES b/samples/client/petstore/kotlin-retrofit2/.openapi-generator/FILES index 871f0c1d09c..04b505d1f17 100644 --- a/samples/client/petstore/kotlin-retrofit2/.openapi-generator/FILES +++ b/samples/client/petstore/kotlin-retrofit2/.openapi-generator/FILES @@ -31,6 +31,7 @@ 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/ResponseExt.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/ApiResponse.kt src/main/kotlin/org/openapitools/client/models/Category.kt diff --git a/samples/client/petstore/kotlin-retrofit2/.openapi-generator/VERSION b/samples/client/petstore/kotlin-retrofit2/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/client/petstore/kotlin-retrofit2/.openapi-generator/VERSION +++ b/samples/client/petstore/kotlin-retrofit2/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/client/petstore/kotlin-retrofit2/build.gradle b/samples/client/petstore/kotlin-retrofit2/build.gradle index 109eb2ca069..ec9a8e9ac24 100644 --- a/samples/client/petstore/kotlin-retrofit2/build.gradle +++ b/samples/client/petstore/kotlin-retrofit2/build.gradle @@ -7,8 +7,8 @@ wrapper { } buildscript { - ext.kotlin_version = '1.4.30' - ext.retrofitVersion = '2.7.2' + ext.kotlin_version = '1.5.10' + ext.retrofitVersion = '2.9.0' repositories { maven { url "https://repo1.maven.org/maven2" } @@ -29,13 +29,13 @@ test { } dependencies { - compile "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version" - compile "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version" - compile "com.squareup.moshi:moshi-kotlin:1.11.0" - compile "org.apache.oltu.oauth2:org.apache.oltu.oauth2.client:1.0.0" - compile "com.squareup.okhttp3:logging-interceptor:4.9.0" - compile "com.squareup.retrofit2:retrofit:$retrofitVersion" - compile "com.squareup.retrofit2:converter-moshi:$retrofitVersion" - compile "com.squareup.retrofit2:converter-scalars:$retrofitVersion" - testCompile "io.kotlintest:kotlintest-runner-junit5:3.4.2" + implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version" + implementation "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version" + implementation "com.squareup.moshi:moshi-kotlin:1.12.0" + implementation "org.apache.oltu.oauth2:org.apache.oltu.oauth2.client:1.0.2" + implementation "com.squareup.okhttp3:logging-interceptor:4.9.1" + implementation "com.squareup.retrofit2:retrofit:$retrofitVersion" + implementation "com.squareup.retrofit2:converter-moshi:$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/src/main/kotlin/org/openapitools/client/apis/PetApi.kt b/samples/client/petstore/kotlin-retrofit2/src/main/kotlin/org/openapitools/client/apis/PetApi.kt index 3b2a4128209..d30336f02e9 100644 --- a/samples/client/petstore/kotlin-retrofit2/src/main/kotlin/org/openapitools/client/apis/PetApi.kt +++ b/samples/client/petstore/kotlin-retrofit2/src/main/kotlin/org/openapitools/client/apis/PetApi.kt @@ -34,7 +34,7 @@ interface PetApi { * @return [Call]<[Unit]> */ @DELETE("pet/{petId}") - fun deletePet(@Path("petId") petId: kotlin.Long, @Header("api_key") apiKey: kotlin.String): Call + fun deletePet(@Path("petId") petId: kotlin.Long, @Header("api_key") apiKey: kotlin.String? = null): Call /** * Finds Pets by status diff --git a/samples/client/petstore/kotlin-retrofit2/src/main/kotlin/org/openapitools/client/auth/OAuthOkHttpClient.kt b/samples/client/petstore/kotlin-retrofit2/src/main/kotlin/org/openapitools/client/auth/OAuthOkHttpClient.kt index 93adbda3fc9..aa70ca9d2f1 100644 --- a/samples/client/petstore/kotlin-retrofit2/src/main/kotlin/org/openapitools/client/auth/OAuthOkHttpClient.kt +++ b/samples/client/petstore/kotlin-retrofit2/src/main/kotlin/org/openapitools/client/auth/OAuthOkHttpClient.kt @@ -13,14 +13,13 @@ 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 + private var client: OkHttpClient = OkHttpClient() ) : HttpClient { - constructor() : this(OkHttpClient()) - @Throws(OAuthSystemException::class, OAuthProblemException::class) override fun execute( request: OAuthClientRequest, @@ -39,7 +38,7 @@ class OAuthOkHttpClient( } } - val body: RequestBody? = if (request.body != null) RequestBody.create(mediaType, request.body) else null + val body: RequestBody? = if (request.body != null) request.body.toRequestBody(mediaType) else null requestBuilder.method(requestMethod, body) try { @@ -48,6 +47,7 @@ class OAuthOkHttpClient( response.body?.string(), response.body?.contentType()?.toString(), response.code, + response.headers.toMultimap(), responseClass) } catch (e: IOException) { throw OAuthSystemException(e) 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 bee954129e6..4aa4323fc5b 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 @@ -7,6 +7,7 @@ import org.openapitools.client.auth.OAuth import org.openapitools.client.auth.OAuth.AccessTokenListener import org.openapitools.client.auth.OAuthFlow +import okhttp3.Call import okhttp3.Interceptor import okhttp3.OkHttpClient import retrofit2.Retrofit @@ -21,7 +22,7 @@ class ApiClient( private var baseUrl: String = defaultBasePath, private val okHttpClientBuilder: OkHttpClient.Builder? = null, private val serializerBuilder: Moshi.Builder = Serializer.moshiBuilder, - private val okHttpClient : OkHttpClient? = null, + private val callFactory : Call.Factory? = null, private val converterFactory: Converter.Factory? = null, ) { private val apiAuthorizations = mutableMapOf() @@ -180,8 +181,8 @@ class ApiClient( } fun createService(serviceClass: Class): S { - val usedClient = this.okHttpClient ?: clientBuilder.build() - return retrofitBuilder.client(usedClient).build().create(serviceClass) + val usedCallFactory = this.callFactory ?: clientBuilder.build() + return retrofitBuilder.callFactory(usedCallFactory).build().create(serviceClass) } private fun normalizeBaseUrl() { diff --git a/samples/client/petstore/kotlin-retrofit2/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt b/samples/client/petstore/kotlin-retrofit2/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt index 3d0a6c32566..e77581231c3 100644 --- a/samples/client/petstore/kotlin-retrofit2/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt +++ b/samples/client/petstore/kotlin-retrofit2/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt @@ -12,6 +12,7 @@ object Serializer { .add(LocalDateAdapter()) .add(UUIDAdapter()) .add(ByteArrayAdapter()) + .add(URIAdapter()) .add(KotlinJsonAdapterFactory()) .add(BigDecimalAdapter()) .add(BigIntegerAdapter()) diff --git a/samples/client/petstore/kotlin-retrofit2/src/main/kotlin/org/openapitools/client/infrastructure/URIAdapter.kt b/samples/client/petstore/kotlin-retrofit2/src/main/kotlin/org/openapitools/client/infrastructure/URIAdapter.kt new file mode 100644 index 00000000000..927522757da --- /dev/null +++ b/samples/client/petstore/kotlin-retrofit2/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-retrofit2/src/main/kotlin/org/openapitools/client/infrastructure/UUIDAdapter.kt b/samples/client/petstore/kotlin-retrofit2/src/main/kotlin/org/openapitools/client/infrastructure/UUIDAdapter.kt index a4a44cc18b7..7ccf7dc25d2 100644 --- a/samples/client/petstore/kotlin-retrofit2/src/main/kotlin/org/openapitools/client/infrastructure/UUIDAdapter.kt +++ b/samples/client/petstore/kotlin-retrofit2/src/main/kotlin/org/openapitools/client/infrastructure/UUIDAdapter.kt @@ -9,5 +9,5 @@ class UUIDAdapter { fun toJson(uuid: UUID) = uuid.toString() @FromJson - fun fromJson(s: String) = UUID.fromString(s) + fun fromJson(s: String): UUID = UUID.fromString(s) } diff --git a/samples/client/petstore/kotlin-string/.openapi-generator/FILES b/samples/client/petstore/kotlin-string/.openapi-generator/FILES index 3f4610174cc..16c712325f8 100644 --- a/samples/client/petstore/kotlin-string/.openapi-generator/FILES +++ b/samples/client/petstore/kotlin-string/.openapi-generator/FILES @@ -20,7 +20,6 @@ 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/ApiInfrastructureResponse.kt -src/main/kotlin/org/openapitools/client/infrastructure/ApplicationDelegates.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 @@ -32,6 +31,7 @@ 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/ApiResponse.kt src/main/kotlin/org/openapitools/client/models/Category.kt diff --git a/samples/client/petstore/kotlin-string/.openapi-generator/VERSION b/samples/client/petstore/kotlin-string/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/client/petstore/kotlin-string/.openapi-generator/VERSION +++ b/samples/client/petstore/kotlin-string/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/client/petstore/kotlin-string/build.gradle b/samples/client/petstore/kotlin-string/build.gradle index 60e5056e031..bb575e6e4bf 100644 --- a/samples/client/petstore/kotlin-string/build.gradle +++ b/samples/client/petstore/kotlin-string/build.gradle @@ -7,7 +7,7 @@ wrapper { } buildscript { - ext.kotlin_version = '1.4.30' + ext.kotlin_version = '1.5.10' repositories { maven { url "https://repo1.maven.org/maven2" } @@ -28,9 +28,9 @@ test { } dependencies { - compile "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version" - compile "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version" - compile "com.squareup.moshi:moshi-kotlin:1.11.0" - compile "com.squareup.okhttp3:okhttp:4.9.0" - testCompile "io.kotlintest:kotlintest-runner-junit5:3.4.2" + implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version" + implementation "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version" + implementation "com.squareup.moshi:moshi-kotlin:1.12.0" + implementation "com.squareup.okhttp3:okhttp:4.9.1" + testImplementation "io.kotlintest:kotlintest-runner-junit5:3.4.2" } diff --git a/samples/client/petstore/kotlin-string/src/main/kotlin/org/openapitools/client/apis/PetApi.kt b/samples/client/petstore/kotlin-string/src/main/kotlin/org/openapitools/client/apis/PetApi.kt index 4fbeccdbc00..fde3a1918c9 100644 --- a/samples/client/petstore/kotlin-string/src/main/kotlin/org/openapitools/client/apis/PetApi.kt +++ b/samples/client/petstore/kotlin-string/src/main/kotlin/org/openapitools/client/apis/PetApi.kt @@ -47,7 +47,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun addPet(body: Pet) : Unit { val localVariableConfig = addPetRequestConfig(body = body) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -72,20 +72,18 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param body Pet object that needs to be added to the store * @return RequestConfig */ - fun addPetRequestConfig(body: Pet) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun addPetRequestConfig(body: Pet) : RequestConfig { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/pet", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -102,7 +100,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun deletePet(apiKey: kotlin.String?, petId: kotlin.Long) : Unit { val localVariableConfig = deletePetRequestConfig(apiKey = apiKey, petId = petId) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -128,21 +126,19 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param petId Pet id to delete * @return RequestConfig */ - fun deletePetRequestConfig(apiKey: kotlin.String?, petId: kotlin.Long) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun deletePetRequestConfig(apiKey: kotlin.String?, petId: kotlin.Long) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() apiKey?.apply { localVariableHeaders["api_key"] = this.toString() } - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.DELETE, path = "/pet/{petId}".replace("{"+"petId"+"}", "$petId"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -159,7 +155,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun findPetsByStatus(status: kotlin.collections.List) : kotlin.collections.List { val localVariableConfig = findPetsByStatusRequestConfig(status = status) - val localVarResponse = request>( + val localVarResponse = request>( localVariableConfig ) @@ -184,23 +180,21 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param status Status values that need to be considered for filter * @return RequestConfig */ - fun findPetsByStatusRequestConfig(status: kotlin.collections.List) : RequestConfig { - val localVariableBody: kotlin.Any? = null + 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() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/pet/findByStatus", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -216,9 +210,10 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { @Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class) @Deprecated(message = "This operation is deprecated.") fun findPetsByTags(tags: kotlin.collections.List) : kotlin.collections.List { + @Suppress("DEPRECATION") val localVariableConfig = findPetsByTagsRequestConfig(tags = tags) - val localVarResponse = request>( + val localVarResponse = request>( localVariableConfig ) @@ -244,23 +239,21 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @return RequestConfig */ @Deprecated(message = "This operation is deprecated.") - fun findPetsByTagsRequestConfig(tags: kotlin.collections.List) : RequestConfig { - val localVariableBody: kotlin.Any? = null + 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() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/pet/findByTags", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -277,7 +270,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun getPetById(petId: kotlin.Long) : Pet { val localVariableConfig = getPetByIdRequestConfig(petId = petId) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -302,20 +295,18 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param petId ID of pet to return * @return RequestConfig */ - fun getPetByIdRequestConfig(petId: kotlin.Long) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun getPetByIdRequestConfig(petId: kotlin.Long) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/pet/{petId}".replace("{"+"petId"+"}", "$petId"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -331,7 +322,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun updatePet(body: Pet) : Unit { val localVariableConfig = updatePetRequestConfig(body = body) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -356,20 +347,18 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param body Pet object that needs to be added to the store * @return RequestConfig */ - fun updatePetRequestConfig(body: Pet) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun updatePetRequestConfig(body: Pet) : RequestConfig { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.PUT, path = "/pet", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -387,7 +376,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun updatePetWithForm(petId: kotlin.Long, name: kotlin.String?, status: kotlin.String?) : Unit { val localVariableConfig = updatePetWithFormRequestConfig(petId = petId, name = name, status = status) - val localVarResponse = request( + val localVarResponse = request, Unit>( localVariableConfig ) @@ -414,20 +403,18 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param status Updated status of the pet (optional) * @return RequestConfig */ - fun updatePetWithFormRequestConfig(petId: kotlin.Long, name: kotlin.String?, status: kotlin.String?) : RequestConfig { - val localVariableBody: kotlin.Any? = mapOf("name" to name, "status" to status) + fun updatePetWithFormRequestConfig(petId: kotlin.Long, name: kotlin.String?, status: kotlin.String?) : RequestConfig> { + val localVariableBody = mapOf("name" to name, "status" to status) val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf("Content-Type" to "application/x-www-form-urlencoded") - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/pet/{petId}".replace("{"+"petId"+"}", "$petId"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -446,7 +433,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun uploadFile(petId: kotlin.Long, additionalMetadata: kotlin.String?, file: java.io.File?) : ApiResponse { val localVariableConfig = uploadFileRequestConfig(petId = petId, additionalMetadata = additionalMetadata, file = file) - val localVarResponse = request( + val localVarResponse = request, ApiResponse>( localVariableConfig ) @@ -473,20 +460,18 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param file file to upload (optional) * @return RequestConfig */ - fun uploadFileRequestConfig(petId: kotlin.Long, additionalMetadata: kotlin.String?, file: java.io.File?) : RequestConfig { - val localVariableBody: kotlin.Any? = mapOf("additionalMetadata" to additionalMetadata, "file" to file) + fun uploadFileRequestConfig(petId: kotlin.Long, additionalMetadata: kotlin.String?, file: java.io.File?) : RequestConfig> { + val localVariableBody = mapOf("additionalMetadata" to additionalMetadata, "file" to file) val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf("Content-Type" to "multipart/form-data") - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/pet/{petId}/uploadImage".replace("{"+"petId"+"}", "$petId"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } } diff --git a/samples/client/petstore/kotlin-string/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt b/samples/client/petstore/kotlin-string/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt index 215ed63420c..56a23202f82 100644 --- a/samples/client/petstore/kotlin-string/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt +++ b/samples/client/petstore/kotlin-string/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt @@ -46,7 +46,7 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) fun deleteOrder(orderId: kotlin.String) : Unit { val localVariableConfig = deleteOrderRequestConfig(orderId = orderId) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -71,20 +71,18 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) * @param orderId ID of the order that needs to be deleted * @return RequestConfig */ - fun deleteOrderRequestConfig(orderId: kotlin.String) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun deleteOrderRequestConfig(orderId: kotlin.String) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.DELETE, path = "/store/order/{orderId}".replace("{"+"orderId"+"}", "$orderId"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -100,7 +98,7 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) fun getInventory() : kotlin.collections.Map { val localVariableConfig = getInventoryRequestConfig() - val localVarResponse = request>( + val localVarResponse = request>( localVariableConfig ) @@ -124,20 +122,18 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) * * @return RequestConfig */ - fun getInventoryRequestConfig() : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun getInventoryRequestConfig() : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/store/inventory", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -154,7 +150,7 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) fun getOrderById(orderId: kotlin.Long) : Order { val localVariableConfig = getOrderByIdRequestConfig(orderId = orderId) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -179,20 +175,18 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) * @param orderId ID of pet that needs to be fetched * @return RequestConfig */ - fun getOrderByIdRequestConfig(orderId: kotlin.Long) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun getOrderByIdRequestConfig(orderId: kotlin.Long) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/store/order/{orderId}".replace("{"+"orderId"+"}", "$orderId"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -209,7 +203,7 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) fun placeOrder(body: Order) : Order { val localVariableConfig = placeOrderRequestConfig(body = body) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -234,20 +228,18 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) * @param body order placed for purchasing the pet * @return RequestConfig */ - fun placeOrderRequestConfig(body: Order) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun placeOrderRequestConfig(body: Order) : RequestConfig { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/store/order", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } } diff --git a/samples/client/petstore/kotlin-string/src/main/kotlin/org/openapitools/client/apis/UserApi.kt b/samples/client/petstore/kotlin-string/src/main/kotlin/org/openapitools/client/apis/UserApi.kt index 53748b93463..9f93e853a12 100644 --- a/samples/client/petstore/kotlin-string/src/main/kotlin/org/openapitools/client/apis/UserApi.kt +++ b/samples/client/petstore/kotlin-string/src/main/kotlin/org/openapitools/client/apis/UserApi.kt @@ -46,7 +46,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun createUser(body: User) : Unit { val localVariableConfig = createUserRequestConfig(body = body) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -71,20 +71,18 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param body Created user object * @return RequestConfig */ - fun createUserRequestConfig(body: User) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun createUserRequestConfig(body: User) : RequestConfig { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/user", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -100,7 +98,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun createUsersWithArrayInput(body: kotlin.collections.List) : Unit { val localVariableConfig = createUsersWithArrayInputRequestConfig(body = body) - val localVarResponse = request( + val localVarResponse = request, Unit>( localVariableConfig ) @@ -125,20 +123,18 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param body List of user object * @return RequestConfig */ - fun createUsersWithArrayInputRequestConfig(body: kotlin.collections.List) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun createUsersWithArrayInputRequestConfig(body: kotlin.collections.List) : RequestConfig> { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/user/createWithArray", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -154,7 +150,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun createUsersWithListInput(body: kotlin.collections.List) : Unit { val localVariableConfig = createUsersWithListInputRequestConfig(body = body) - val localVarResponse = request( + val localVarResponse = request, Unit>( localVariableConfig ) @@ -179,20 +175,18 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param body List of user object * @return RequestConfig */ - fun createUsersWithListInputRequestConfig(body: kotlin.collections.List) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun createUsersWithListInputRequestConfig(body: kotlin.collections.List) : RequestConfig> { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/user/createWithList", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -208,7 +202,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun deleteUser(username: kotlin.String) : Unit { val localVariableConfig = deleteUserRequestConfig(username = username) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -233,20 +227,18 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param username The name that needs to be deleted * @return RequestConfig */ - fun deleteUserRequestConfig(username: kotlin.String) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun deleteUserRequestConfig(username: kotlin.String) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.DELETE, path = "/user/{username}".replace("{"+"username"+"}", "$username"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -263,7 +255,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun getUserByName(username: kotlin.String) : User { val localVariableConfig = getUserByNameRequestConfig(username = username) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -288,20 +280,18 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param username The name that needs to be fetched. Use user1 for testing. * @return RequestConfig */ - fun getUserByNameRequestConfig(username: kotlin.String) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun getUserByNameRequestConfig(username: kotlin.String) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/user/{username}".replace("{"+"username"+"}", "$username"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -319,7 +309,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun loginUser(username: kotlin.String, password: kotlin.String) : kotlin.String { val localVariableConfig = loginUserRequestConfig(username = username, password = password) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -345,24 +335,22 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param password The password for login in clear text * @return RequestConfig */ - fun loginUserRequestConfig(username: kotlin.String, password: kotlin.String) : RequestConfig { - val localVariableBody: kotlin.Any? = null + 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() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/user/login", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -377,7 +365,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun logoutUser() : Unit { val localVariableConfig = logoutUserRequestConfig() - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -401,20 +389,18 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * * @return RequestConfig */ - fun logoutUserRequestConfig() : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun logoutUserRequestConfig() : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/user/logout", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -431,7 +417,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun updateUser(username: kotlin.String, body: User) : Unit { val localVariableConfig = updateUserRequestConfig(username = username, body = body) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -457,20 +443,18 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param body Updated user object * @return RequestConfig */ - fun updateUserRequestConfig(username: kotlin.String, body: User) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun updateUserRequestConfig(username: kotlin.String, body: User) : RequestConfig { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.PUT, path = "/user/{username}".replace("{"+"username"+"}", "$username"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } } 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 bc9ed02c0f1..ae6e80e9506 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 @@ -1,6 +1,5 @@ package org.openapitools.client.infrastructure -import okhttp3.Credentials import okhttp3.OkHttpClient import okhttp3.RequestBody import okhttp3.RequestBody.Companion.asRequestBody @@ -12,17 +11,17 @@ import okhttp3.MediaType.Companion.toMediaTypeOrNull import okhttp3.Request import okhttp3.Headers import okhttp3.MultipartBody -import java.io.File import java.io.BufferedWriter +import java.io.File import java.io.FileWriter import java.net.URLConnection -import java.nio.file.Files -import java.util.Date import java.time.LocalDate import java.time.LocalDateTime import java.time.LocalTime import java.time.OffsetDateTime import java.time.OffsetTime +import java.util.Date +import java.util.Locale open class ApiClient(val baseUrl: String) { companion object { @@ -62,9 +61,7 @@ open class ApiClient(val baseUrl: String) { protected inline fun requestBody(content: T, mediaType: String = JsonMediaType): RequestBody = when { - content is File -> content.asRequestBody( - mediaType.toMediaTypeOrNull() - ) + content is File -> content.asRequestBody(mediaType.toMediaTypeOrNull()) mediaType == FormDataMediaType -> { MultipartBody.Builder() .setType(MultipartBody.FORM) @@ -119,7 +116,7 @@ open class ApiClient(val baseUrl: String) { } if (T::class.java == File::class.java) { // return tempfile - val f = Files.createTempFile("tmp.org.openapitools.client", null).toFile() + val f = java.nio.file.Files.createTempFile("tmp.org.openapitools.client", null).toFile() f.deleteOnExit() val out = BufferedWriter(FileWriter(f)) out.write(bodyContent) @@ -132,7 +129,7 @@ open class ApiClient(val baseUrl: String) { } } - protected fun updateAuthParams(requestConfig: RequestConfig) { + protected fun updateAuthParams(requestConfig: RequestConfig) { if (requestConfig.headers["api_key"].isNullOrEmpty()) { if (apiKey["api_key"] != null) { if (apiKeyPrefix["api_key"] != null) { @@ -149,7 +146,7 @@ open class ApiClient(val baseUrl: String) { } } - protected inline fun request(requestConfig: RequestConfig): ApiInfrastructureResponse { + protected inline fun request(requestConfig: RequestConfig): ApiInfrastructureResponse { val httpUrl = baseUrl.toHttpUrlOrNull() ?: throw IllegalStateException("baseUrl is invalid.") // take authMethod from operation @@ -183,7 +180,7 @@ open class ApiClient(val baseUrl: String) { } // TODO: support multiple contentType options here. - val contentType = (headers[ContentType] as String).substringBefore(";").toLowerCase() + val contentType = (headers[ContentType] as String).substringBefore(";").lowercase(Locale.getDefault()) val request = when (requestConfig.method) { RequestMethod.DELETE -> Request.Builder().url(url).delete(requestBody(requestConfig.body, contentType)) @@ -198,57 +195,46 @@ open class ApiClient(val baseUrl: String) { }.build() val response = client.newCall(request).execute() - val accept = response.header(ContentType)?.substringBefore(";")?.toLowerCase() + val accept = response.header(ContentType)?.substringBefore(";")?.lowercase(Locale.getDefault()) // TODO: handle specific mapping types. e.g. Map> - when { - response.isRedirect -> return Redirection( - response.code, - response.headers.toMultimap() + return when { + response.isRedirect -> Redirection( + response.code, + response.headers.toMultimap() ) - response.isInformational -> return Informational( - response.message, - response.code, - response.headers.toMultimap() + response.isInformational -> Informational( + response.message, + response.code, + response.headers.toMultimap() ) - response.isSuccessful -> return Success( - responseBody(response.body, accept), - response.code, - response.headers.toMultimap() + response.isSuccessful -> Success( + responseBody(response.body, accept), + response.code, + response.headers.toMultimap() ) - response.isClientError -> return ClientError( - response.message, - response.body?.string(), - response.code, - response.headers.toMultimap() + response.isClientError -> ClientError( + response.message, + response.body?.string(), + response.code, + response.headers.toMultimap() ) - else -> return ServerError( - 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 -> { - return "" - } - is Array<*> -> { - return toMultiValue(value, "csv").toString() - } - is Iterable<*> -> { - return toMultiValue(value, "csv").toString() - } - is OffsetDateTime, is OffsetTime, is LocalDateTime, is LocalDate, is LocalTime, is Date -> { - return parseDateToQueryString(value) - } - else -> { - return value.toString() - } - } + 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, is Date -> + parseDateToQueryString(value) + else -> value.toString() } protected inline fun parseDateToQueryString(value : T): String { 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 0f2790f370e..7e948e1dd07 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 @@ -8,10 +8,10 @@ package org.openapitools.client.infrastructure * NOTE: Headers is a Map because rfc2616 defines * multi-valued headers as csv-only. */ -data class RequestConfig( +data class RequestConfig( val method: RequestMethod, val path: String, val headers: MutableMap = mutableMapOf(), val query: MutableMap> = mutableMapOf(), - val body: kotlin.Any? = null + val body: T? = null ) \ No newline at end of file diff --git a/samples/client/petstore/kotlin-string/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt b/samples/client/petstore/kotlin-string/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt index 3d0a6c32566..e77581231c3 100644 --- a/samples/client/petstore/kotlin-string/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt +++ b/samples/client/petstore/kotlin-string/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt @@ -12,6 +12,7 @@ object Serializer { .add(LocalDateAdapter()) .add(UUIDAdapter()) .add(ByteArrayAdapter()) + .add(URIAdapter()) .add(KotlinJsonAdapterFactory()) .add(BigDecimalAdapter()) .add(BigIntegerAdapter()) diff --git a/samples/client/petstore/kotlin-string/src/main/kotlin/org/openapitools/client/infrastructure/URIAdapter.kt b/samples/client/petstore/kotlin-string/src/main/kotlin/org/openapitools/client/infrastructure/URIAdapter.kt new file mode 100644 index 00000000000..927522757da --- /dev/null +++ b/samples/client/petstore/kotlin-string/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-string/src/main/kotlin/org/openapitools/client/infrastructure/UUIDAdapter.kt b/samples/client/petstore/kotlin-string/src/main/kotlin/org/openapitools/client/infrastructure/UUIDAdapter.kt index a4a44cc18b7..7ccf7dc25d2 100644 --- a/samples/client/petstore/kotlin-string/src/main/kotlin/org/openapitools/client/infrastructure/UUIDAdapter.kt +++ b/samples/client/petstore/kotlin-string/src/main/kotlin/org/openapitools/client/infrastructure/UUIDAdapter.kt @@ -9,5 +9,5 @@ class UUIDAdapter { fun toJson(uuid: UUID) = uuid.toString() @FromJson - fun fromJson(s: String) = UUID.fromString(s) + fun fromJson(s: String): UUID = UUID.fromString(s) } diff --git a/samples/client/petstore/kotlin-threetenbp/.openapi-generator/FILES b/samples/client/petstore/kotlin-threetenbp/.openapi-generator/FILES index 3f4610174cc..16c712325f8 100644 --- a/samples/client/petstore/kotlin-threetenbp/.openapi-generator/FILES +++ b/samples/client/petstore/kotlin-threetenbp/.openapi-generator/FILES @@ -20,7 +20,6 @@ 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/ApiInfrastructureResponse.kt -src/main/kotlin/org/openapitools/client/infrastructure/ApplicationDelegates.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 @@ -32,6 +31,7 @@ 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/ApiResponse.kt src/main/kotlin/org/openapitools/client/models/Category.kt diff --git a/samples/client/petstore/kotlin-threetenbp/.openapi-generator/VERSION b/samples/client/petstore/kotlin-threetenbp/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/client/petstore/kotlin-threetenbp/.openapi-generator/VERSION +++ b/samples/client/petstore/kotlin-threetenbp/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/client/petstore/kotlin-threetenbp/build.gradle b/samples/client/petstore/kotlin-threetenbp/build.gradle index 87605daa9d2..b4e0d0acc7a 100644 --- a/samples/client/petstore/kotlin-threetenbp/build.gradle +++ b/samples/client/petstore/kotlin-threetenbp/build.gradle @@ -7,7 +7,7 @@ wrapper { } buildscript { - ext.kotlin_version = '1.4.30' + ext.kotlin_version = '1.5.10' repositories { maven { url "https://repo1.maven.org/maven2" } @@ -28,10 +28,10 @@ test { } dependencies { - compile "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version" - compile "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version" - compile "com.squareup.moshi:moshi-kotlin:1.11.0" - compile "com.squareup.okhttp3:okhttp:4.9.0" - compile "org.threeten:threetenbp:1.5.0" - testCompile "io.kotlintest:kotlintest-runner-junit5:3.4.2" + implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version" + implementation "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version" + implementation "com.squareup.moshi:moshi-kotlin:1.12.0" + implementation "com.squareup.okhttp3:okhttp:4.9.1" + implementation "org.threeten:threetenbp:1.5.1" + testImplementation "io.kotlintest:kotlintest-runner-junit5:3.4.2" } diff --git a/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/org/openapitools/client/apis/PetApi.kt b/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/org/openapitools/client/apis/PetApi.kt index c8b93b33bf6..be50dd6c442 100644 --- a/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/org/openapitools/client/apis/PetApi.kt +++ b/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/org/openapitools/client/apis/PetApi.kt @@ -47,7 +47,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun addPet(body: Pet) : Unit { val localVariableConfig = addPetRequestConfig(body = body) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -72,20 +72,18 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param body Pet object that needs to be added to the store * @return RequestConfig */ - fun addPetRequestConfig(body: Pet) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun addPetRequestConfig(body: Pet) : RequestConfig { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/pet", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -102,7 +100,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun deletePet(petId: kotlin.Long, apiKey: kotlin.String?) : Unit { val localVariableConfig = deletePetRequestConfig(petId = petId, apiKey = apiKey) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -128,21 +126,19 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param apiKey (optional) * @return RequestConfig */ - fun deletePetRequestConfig(petId: kotlin.Long, apiKey: kotlin.String?) : RequestConfig { - val localVariableBody: kotlin.Any? = null + 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() } - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.DELETE, path = "/pet/{petId}".replace("{"+"petId"+"}", "$petId"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -159,7 +155,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun findPetsByStatus(status: kotlin.collections.List) : kotlin.collections.List { val localVariableConfig = findPetsByStatusRequestConfig(status = status) - val localVarResponse = request>( + val localVarResponse = request>( localVariableConfig ) @@ -184,23 +180,21 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param status Status values that need to be considered for filter * @return RequestConfig */ - fun findPetsByStatusRequestConfig(status: kotlin.collections.List) : RequestConfig { - val localVariableBody: kotlin.Any? = null + 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() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/pet/findByStatus", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -216,9 +210,10 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { @Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class) @Deprecated(message = "This operation is deprecated.") fun findPetsByTags(tags: kotlin.collections.List) : kotlin.collections.List { + @Suppress("DEPRECATION") val localVariableConfig = findPetsByTagsRequestConfig(tags = tags) - val localVarResponse = request>( + val localVarResponse = request>( localVariableConfig ) @@ -244,23 +239,21 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @return RequestConfig */ @Deprecated(message = "This operation is deprecated.") - fun findPetsByTagsRequestConfig(tags: kotlin.collections.List) : RequestConfig { - val localVariableBody: kotlin.Any? = null + 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() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/pet/findByTags", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -277,7 +270,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun getPetById(petId: kotlin.Long) : Pet { val localVariableConfig = getPetByIdRequestConfig(petId = petId) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -302,20 +295,18 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param petId ID of pet to return * @return RequestConfig */ - fun getPetByIdRequestConfig(petId: kotlin.Long) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun getPetByIdRequestConfig(petId: kotlin.Long) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/pet/{petId}".replace("{"+"petId"+"}", "$petId"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -331,7 +322,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun updatePet(body: Pet) : Unit { val localVariableConfig = updatePetRequestConfig(body = body) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -356,20 +347,18 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param body Pet object that needs to be added to the store * @return RequestConfig */ - fun updatePetRequestConfig(body: Pet) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun updatePetRequestConfig(body: Pet) : RequestConfig { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.PUT, path = "/pet", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -387,7 +376,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun updatePetWithForm(petId: kotlin.Long, name: kotlin.String?, status: kotlin.String?) : Unit { val localVariableConfig = updatePetWithFormRequestConfig(petId = petId, name = name, status = status) - val localVarResponse = request( + val localVarResponse = request, Unit>( localVariableConfig ) @@ -414,20 +403,18 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param status Updated status of the pet (optional) * @return RequestConfig */ - fun updatePetWithFormRequestConfig(petId: kotlin.Long, name: kotlin.String?, status: kotlin.String?) : RequestConfig { - val localVariableBody: kotlin.Any? = mapOf("name" to name, "status" to status) + fun updatePetWithFormRequestConfig(petId: kotlin.Long, name: kotlin.String?, status: kotlin.String?) : RequestConfig> { + val localVariableBody = mapOf("name" to name, "status" to status) val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf("Content-Type" to "application/x-www-form-urlencoded") - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/pet/{petId}".replace("{"+"petId"+"}", "$petId"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -446,7 +433,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun uploadFile(petId: kotlin.Long, additionalMetadata: kotlin.String?, file: java.io.File?) : ApiResponse { val localVariableConfig = uploadFileRequestConfig(petId = petId, additionalMetadata = additionalMetadata, file = file) - val localVarResponse = request( + val localVarResponse = request, ApiResponse>( localVariableConfig ) @@ -473,20 +460,18 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param file file to upload (optional) * @return RequestConfig */ - fun uploadFileRequestConfig(petId: kotlin.Long, additionalMetadata: kotlin.String?, file: java.io.File?) : RequestConfig { - val localVariableBody: kotlin.Any? = mapOf("additionalMetadata" to additionalMetadata, "file" to file) + fun uploadFileRequestConfig(petId: kotlin.Long, additionalMetadata: kotlin.String?, file: java.io.File?) : RequestConfig> { + val localVariableBody = mapOf("additionalMetadata" to additionalMetadata, "file" to file) val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf("Content-Type" to "multipart/form-data") - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/pet/{petId}/uploadImage".replace("{"+"petId"+"}", "$petId"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } } diff --git a/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt b/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt index 215ed63420c..56a23202f82 100644 --- a/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt +++ b/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt @@ -46,7 +46,7 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) fun deleteOrder(orderId: kotlin.String) : Unit { val localVariableConfig = deleteOrderRequestConfig(orderId = orderId) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -71,20 +71,18 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) * @param orderId ID of the order that needs to be deleted * @return RequestConfig */ - fun deleteOrderRequestConfig(orderId: kotlin.String) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun deleteOrderRequestConfig(orderId: kotlin.String) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.DELETE, path = "/store/order/{orderId}".replace("{"+"orderId"+"}", "$orderId"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -100,7 +98,7 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) fun getInventory() : kotlin.collections.Map { val localVariableConfig = getInventoryRequestConfig() - val localVarResponse = request>( + val localVarResponse = request>( localVariableConfig ) @@ -124,20 +122,18 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) * * @return RequestConfig */ - fun getInventoryRequestConfig() : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun getInventoryRequestConfig() : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/store/inventory", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -154,7 +150,7 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) fun getOrderById(orderId: kotlin.Long) : Order { val localVariableConfig = getOrderByIdRequestConfig(orderId = orderId) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -179,20 +175,18 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) * @param orderId ID of pet that needs to be fetched * @return RequestConfig */ - fun getOrderByIdRequestConfig(orderId: kotlin.Long) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun getOrderByIdRequestConfig(orderId: kotlin.Long) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/store/order/{orderId}".replace("{"+"orderId"+"}", "$orderId"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -209,7 +203,7 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) fun placeOrder(body: Order) : Order { val localVariableConfig = placeOrderRequestConfig(body = body) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -234,20 +228,18 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) * @param body order placed for purchasing the pet * @return RequestConfig */ - fun placeOrderRequestConfig(body: Order) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun placeOrderRequestConfig(body: Order) : RequestConfig { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/store/order", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } } diff --git a/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/org/openapitools/client/apis/UserApi.kt b/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/org/openapitools/client/apis/UserApi.kt index 53748b93463..9f93e853a12 100644 --- a/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/org/openapitools/client/apis/UserApi.kt +++ b/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/org/openapitools/client/apis/UserApi.kt @@ -46,7 +46,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun createUser(body: User) : Unit { val localVariableConfig = createUserRequestConfig(body = body) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -71,20 +71,18 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param body Created user object * @return RequestConfig */ - fun createUserRequestConfig(body: User) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun createUserRequestConfig(body: User) : RequestConfig { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/user", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -100,7 +98,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun createUsersWithArrayInput(body: kotlin.collections.List) : Unit { val localVariableConfig = createUsersWithArrayInputRequestConfig(body = body) - val localVarResponse = request( + val localVarResponse = request, Unit>( localVariableConfig ) @@ -125,20 +123,18 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param body List of user object * @return RequestConfig */ - fun createUsersWithArrayInputRequestConfig(body: kotlin.collections.List) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun createUsersWithArrayInputRequestConfig(body: kotlin.collections.List) : RequestConfig> { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/user/createWithArray", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -154,7 +150,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun createUsersWithListInput(body: kotlin.collections.List) : Unit { val localVariableConfig = createUsersWithListInputRequestConfig(body = body) - val localVarResponse = request( + val localVarResponse = request, Unit>( localVariableConfig ) @@ -179,20 +175,18 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param body List of user object * @return RequestConfig */ - fun createUsersWithListInputRequestConfig(body: kotlin.collections.List) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun createUsersWithListInputRequestConfig(body: kotlin.collections.List) : RequestConfig> { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/user/createWithList", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -208,7 +202,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun deleteUser(username: kotlin.String) : Unit { val localVariableConfig = deleteUserRequestConfig(username = username) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -233,20 +227,18 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param username The name that needs to be deleted * @return RequestConfig */ - fun deleteUserRequestConfig(username: kotlin.String) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun deleteUserRequestConfig(username: kotlin.String) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.DELETE, path = "/user/{username}".replace("{"+"username"+"}", "$username"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -263,7 +255,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun getUserByName(username: kotlin.String) : User { val localVariableConfig = getUserByNameRequestConfig(username = username) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -288,20 +280,18 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param username The name that needs to be fetched. Use user1 for testing. * @return RequestConfig */ - fun getUserByNameRequestConfig(username: kotlin.String) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun getUserByNameRequestConfig(username: kotlin.String) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/user/{username}".replace("{"+"username"+"}", "$username"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -319,7 +309,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun loginUser(username: kotlin.String, password: kotlin.String) : kotlin.String { val localVariableConfig = loginUserRequestConfig(username = username, password = password) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -345,24 +335,22 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param password The password for login in clear text * @return RequestConfig */ - fun loginUserRequestConfig(username: kotlin.String, password: kotlin.String) : RequestConfig { - val localVariableBody: kotlin.Any? = null + 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() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/user/login", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -377,7 +365,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun logoutUser() : Unit { val localVariableConfig = logoutUserRequestConfig() - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -401,20 +389,18 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * * @return RequestConfig */ - fun logoutUserRequestConfig() : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun logoutUserRequestConfig() : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/user/logout", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -431,7 +417,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun updateUser(username: kotlin.String, body: User) : Unit { val localVariableConfig = updateUserRequestConfig(username = username, body = body) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -457,20 +443,18 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param body Updated user object * @return RequestConfig */ - fun updateUserRequestConfig(username: kotlin.String, body: User) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun updateUserRequestConfig(username: kotlin.String, body: User) : RequestConfig { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.PUT, path = "/user/{username}".replace("{"+"username"+"}", "$username"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } } 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 bd683341896..ad394bbefb0 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 @@ -1,6 +1,5 @@ package org.openapitools.client.infrastructure -import okhttp3.Credentials import okhttp3.OkHttpClient import okhttp3.RequestBody import okhttp3.RequestBody.Companion.asRequestBody @@ -12,12 +11,12 @@ import okhttp3.MediaType.Companion.toMediaTypeOrNull import okhttp3.Request import okhttp3.Headers import okhttp3.MultipartBody -import java.io.File import java.io.BufferedWriter +import java.io.File import java.io.FileWriter import java.net.URLConnection -import java.nio.file.Files import java.util.Date +import java.util.Locale import org.threeten.bp.LocalDate import org.threeten.bp.LocalDateTime import org.threeten.bp.LocalTime @@ -62,9 +61,7 @@ open class ApiClient(val baseUrl: String) { protected inline fun requestBody(content: T, mediaType: String = JsonMediaType): RequestBody = when { - content is File -> content.asRequestBody( - mediaType.toMediaTypeOrNull() - ) + content is File -> content.asRequestBody(mediaType.toMediaTypeOrNull()) mediaType == FormDataMediaType -> { MultipartBody.Builder() .setType(MultipartBody.FORM) @@ -119,7 +116,7 @@ open class ApiClient(val baseUrl: String) { } if (T::class.java == File::class.java) { // return tempfile - val f = Files.createTempFile("tmp.org.openapitools.client", null).toFile() + val f = java.nio.file.Files.createTempFile("tmp.org.openapitools.client", null).toFile() f.deleteOnExit() val out = BufferedWriter(FileWriter(f)) out.write(bodyContent) @@ -132,7 +129,7 @@ open class ApiClient(val baseUrl: String) { } } - protected fun updateAuthParams(requestConfig: RequestConfig) { + protected fun updateAuthParams(requestConfig: RequestConfig) { if (requestConfig.headers["api_key"].isNullOrEmpty()) { if (apiKey["api_key"] != null) { if (apiKeyPrefix["api_key"] != null) { @@ -149,7 +146,7 @@ open class ApiClient(val baseUrl: String) { } } - protected inline fun request(requestConfig: RequestConfig): ApiInfrastructureResponse { + protected inline fun request(requestConfig: RequestConfig): ApiInfrastructureResponse { val httpUrl = baseUrl.toHttpUrlOrNull() ?: throw IllegalStateException("baseUrl is invalid.") // take authMethod from operation @@ -183,7 +180,7 @@ open class ApiClient(val baseUrl: String) { } // TODO: support multiple contentType options here. - val contentType = (headers[ContentType] as String).substringBefore(";").toLowerCase() + val contentType = (headers[ContentType] as String).substringBefore(";").lowercase(Locale.getDefault()) val request = when (requestConfig.method) { RequestMethod.DELETE -> Request.Builder().url(url).delete(requestBody(requestConfig.body, contentType)) @@ -198,57 +195,46 @@ open class ApiClient(val baseUrl: String) { }.build() val response = client.newCall(request).execute() - val accept = response.header(ContentType)?.substringBefore(";")?.toLowerCase() + val accept = response.header(ContentType)?.substringBefore(";")?.lowercase(Locale.getDefault()) // TODO: handle specific mapping types. e.g. Map> - when { - response.isRedirect -> return Redirection( - response.code, - response.headers.toMultimap() + return when { + response.isRedirect -> Redirection( + response.code, + response.headers.toMultimap() ) - response.isInformational -> return Informational( - response.message, - response.code, - response.headers.toMultimap() + response.isInformational -> Informational( + response.message, + response.code, + response.headers.toMultimap() ) - response.isSuccessful -> return Success( - responseBody(response.body, accept), - response.code, - response.headers.toMultimap() + response.isSuccessful -> Success( + responseBody(response.body, accept), + response.code, + response.headers.toMultimap() ) - response.isClientError -> return ClientError( - response.message, - response.body?.string(), - response.code, - response.headers.toMultimap() + response.isClientError -> ClientError( + response.message, + response.body?.string(), + response.code, + response.headers.toMultimap() ) - else -> return ServerError( - 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 -> { - return "" - } - is Array<*> -> { - return toMultiValue(value, "csv").toString() - } - is Iterable<*> -> { - return toMultiValue(value, "csv").toString() - } - is OffsetDateTime, is OffsetTime, is LocalDateTime, is LocalDate, is LocalTime, is Date -> { - return parseDateToQueryString(value) - } - else -> { - return value.toString() - } - } + 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, is Date -> + parseDateToQueryString(value) + else -> value.toString() } protected inline fun parseDateToQueryString(value : T): String { 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 0f2790f370e..7e948e1dd07 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 @@ -8,10 +8,10 @@ package org.openapitools.client.infrastructure * NOTE: Headers is a Map because rfc2616 defines * multi-valued headers as csv-only. */ -data class RequestConfig( +data class RequestConfig( val method: RequestMethod, val path: String, val headers: MutableMap = mutableMapOf(), val query: MutableMap> = mutableMapOf(), - val body: kotlin.Any? = null + val body: T? = null ) \ No newline at end of file diff --git a/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt b/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt index 3d0a6c32566..e77581231c3 100644 --- a/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt +++ b/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt @@ -12,6 +12,7 @@ object Serializer { .add(LocalDateAdapter()) .add(UUIDAdapter()) .add(ByteArrayAdapter()) + .add(URIAdapter()) .add(KotlinJsonAdapterFactory()) .add(BigDecimalAdapter()) .add(BigIntegerAdapter()) diff --git a/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/org/openapitools/client/infrastructure/URIAdapter.kt b/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/org/openapitools/client/infrastructure/URIAdapter.kt new file mode 100644 index 00000000000..927522757da --- /dev/null +++ b/samples/client/petstore/kotlin-threetenbp/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-threetenbp/src/main/kotlin/org/openapitools/client/infrastructure/UUIDAdapter.kt b/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/org/openapitools/client/infrastructure/UUIDAdapter.kt index a4a44cc18b7..7ccf7dc25d2 100644 --- a/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/org/openapitools/client/infrastructure/UUIDAdapter.kt +++ b/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/org/openapitools/client/infrastructure/UUIDAdapter.kt @@ -9,5 +9,5 @@ class UUIDAdapter { fun toJson(uuid: UUID) = uuid.toString() @FromJson - fun fromJson(s: String) = UUID.fromString(s) + fun fromJson(s: String): UUID = UUID.fromString(s) } diff --git a/samples/client/petstore/kotlin-uppercase-enum/.openapi-generator/FILES b/samples/client/petstore/kotlin-uppercase-enum/.openapi-generator/FILES index 7619fbe8f8e..c817d802484 100644 --- a/samples/client/petstore/kotlin-uppercase-enum/.openapi-generator/FILES +++ b/samples/client/petstore/kotlin-uppercase-enum/.openapi-generator/FILES @@ -11,7 +11,6 @@ src/main/kotlin/org/openapitools/client/apis/EnumApi.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/ApiInfrastructureResponse.kt -src/main/kotlin/org/openapitools/client/infrastructure/ApplicationDelegates.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 @@ -23,5 +22,6 @@ 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/PetEnum.kt diff --git a/samples/client/petstore/kotlin-uppercase-enum/.openapi-generator/VERSION b/samples/client/petstore/kotlin-uppercase-enum/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/client/petstore/kotlin-uppercase-enum/.openapi-generator/VERSION +++ b/samples/client/petstore/kotlin-uppercase-enum/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/client/petstore/kotlin-uppercase-enum/build.gradle b/samples/client/petstore/kotlin-uppercase-enum/build.gradle index 60e5056e031..bb575e6e4bf 100644 --- a/samples/client/petstore/kotlin-uppercase-enum/build.gradle +++ b/samples/client/petstore/kotlin-uppercase-enum/build.gradle @@ -7,7 +7,7 @@ wrapper { } buildscript { - ext.kotlin_version = '1.4.30' + ext.kotlin_version = '1.5.10' repositories { maven { url "https://repo1.maven.org/maven2" } @@ -28,9 +28,9 @@ test { } dependencies { - compile "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version" - compile "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version" - compile "com.squareup.moshi:moshi-kotlin:1.11.0" - compile "com.squareup.okhttp3:okhttp:4.9.0" - testCompile "io.kotlintest:kotlintest-runner-junit5:3.4.2" + implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version" + implementation "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version" + implementation "com.squareup.moshi:moshi-kotlin:1.12.0" + implementation "com.squareup.okhttp3:okhttp:4.9.1" + testImplementation "io.kotlintest:kotlintest-runner-junit5:3.4.2" } diff --git a/samples/client/petstore/kotlin-uppercase-enum/src/main/kotlin/org/openapitools/client/apis/EnumApi.kt b/samples/client/petstore/kotlin-uppercase-enum/src/main/kotlin/org/openapitools/client/apis/EnumApi.kt index e504c876ce6..59cebc5d4b9 100644 --- a/samples/client/petstore/kotlin-uppercase-enum/src/main/kotlin/org/openapitools/client/apis/EnumApi.kt +++ b/samples/client/petstore/kotlin-uppercase-enum/src/main/kotlin/org/openapitools/client/apis/EnumApi.kt @@ -46,7 +46,7 @@ class EnumApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun getEnum() : PetEnum { val localVariableConfig = getEnumRequestConfig() - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -70,20 +70,18 @@ class EnumApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * * @return RequestConfig */ - fun getEnumRequestConfig() : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun getEnumRequestConfig() : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/enum", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } } 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 a9f5f6ce2a2..e65bce97f7e 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 @@ -1,6 +1,5 @@ package org.openapitools.client.infrastructure -import okhttp3.Credentials import okhttp3.OkHttpClient import okhttp3.RequestBody import okhttp3.RequestBody.Companion.asRequestBody @@ -12,17 +11,17 @@ import okhttp3.MediaType.Companion.toMediaTypeOrNull import okhttp3.Request import okhttp3.Headers import okhttp3.MultipartBody -import java.io.File import java.io.BufferedWriter +import java.io.File import java.io.FileWriter import java.net.URLConnection -import java.nio.file.Files -import java.util.Date import java.time.LocalDate import java.time.LocalDateTime import java.time.LocalTime import java.time.OffsetDateTime import java.time.OffsetTime +import java.util.Date +import java.util.Locale open class ApiClient(val baseUrl: String) { companion object { @@ -62,9 +61,7 @@ open class ApiClient(val baseUrl: String) { protected inline fun requestBody(content: T, mediaType: String = JsonMediaType): RequestBody = when { - content is File -> content.asRequestBody( - mediaType.toMediaTypeOrNull() - ) + content is File -> content.asRequestBody(mediaType.toMediaTypeOrNull()) mediaType == FormDataMediaType -> { MultipartBody.Builder() .setType(MultipartBody.FORM) @@ -119,7 +116,7 @@ open class ApiClient(val baseUrl: String) { } if (T::class.java == File::class.java) { // return tempfile - val f = Files.createTempFile("tmp.org.openapitools.client", null).toFile() + val f = java.nio.file.Files.createTempFile("tmp.org.openapitools.client", null).toFile() f.deleteOnExit() val out = BufferedWriter(FileWriter(f)) out.write(bodyContent) @@ -133,7 +130,7 @@ open class ApiClient(val baseUrl: String) { } - protected inline fun request(requestConfig: RequestConfig): ApiInfrastructureResponse { + protected inline fun request(requestConfig: RequestConfig): ApiInfrastructureResponse { val httpUrl = baseUrl.toHttpUrlOrNull() ?: throw IllegalStateException("baseUrl is invalid.") val url = httpUrl.newBuilder() @@ -164,7 +161,7 @@ open class ApiClient(val baseUrl: String) { } // TODO: support multiple contentType options here. - val contentType = (headers[ContentType] as String).substringBefore(";").toLowerCase() + val contentType = (headers[ContentType] as String).substringBefore(";").lowercase(Locale.getDefault()) val request = when (requestConfig.method) { RequestMethod.DELETE -> Request.Builder().url(url).delete(requestBody(requestConfig.body, contentType)) @@ -179,57 +176,46 @@ open class ApiClient(val baseUrl: String) { }.build() val response = client.newCall(request).execute() - val accept = response.header(ContentType)?.substringBefore(";")?.toLowerCase() + val accept = response.header(ContentType)?.substringBefore(";")?.lowercase(Locale.getDefault()) // TODO: handle specific mapping types. e.g. Map> - when { - response.isRedirect -> return Redirection( - response.code, - response.headers.toMultimap() + return when { + response.isRedirect -> Redirection( + response.code, + response.headers.toMultimap() ) - response.isInformational -> return Informational( - response.message, - response.code, - response.headers.toMultimap() + response.isInformational -> Informational( + response.message, + response.code, + response.headers.toMultimap() ) - response.isSuccessful -> return Success( - responseBody(response.body, accept), - response.code, - response.headers.toMultimap() + response.isSuccessful -> Success( + responseBody(response.body, accept), + response.code, + response.headers.toMultimap() ) - response.isClientError -> return ClientError( - response.message, - response.body?.string(), - response.code, - response.headers.toMultimap() + response.isClientError -> ClientError( + response.message, + response.body?.string(), + response.code, + response.headers.toMultimap() ) - else -> return ServerError( - 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 -> { - return "" - } - is Array<*> -> { - return toMultiValue(value, "csv").toString() - } - is Iterable<*> -> { - return toMultiValue(value, "csv").toString() - } - is OffsetDateTime, is OffsetTime, is LocalDateTime, is LocalDate, is LocalTime, is Date -> { - return parseDateToQueryString(value) - } - else -> { - return value.toString() - } - } + 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, is Date -> + parseDateToQueryString(value) + else -> value.toString() } protected inline fun parseDateToQueryString(value : T): String { 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 0f2790f370e..7e948e1dd07 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 @@ -8,10 +8,10 @@ package org.openapitools.client.infrastructure * NOTE: Headers is a Map because rfc2616 defines * multi-valued headers as csv-only. */ -data class RequestConfig( +data class RequestConfig( val method: RequestMethod, val path: String, val headers: MutableMap = mutableMapOf(), val query: MutableMap> = mutableMapOf(), - val body: kotlin.Any? = null + val body: T? = null ) \ No newline at end of file diff --git a/samples/client/petstore/kotlin-uppercase-enum/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt b/samples/client/petstore/kotlin-uppercase-enum/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt index 3d0a6c32566..e77581231c3 100644 --- a/samples/client/petstore/kotlin-uppercase-enum/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt +++ b/samples/client/petstore/kotlin-uppercase-enum/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt @@ -12,6 +12,7 @@ object Serializer { .add(LocalDateAdapter()) .add(UUIDAdapter()) .add(ByteArrayAdapter()) + .add(URIAdapter()) .add(KotlinJsonAdapterFactory()) .add(BigDecimalAdapter()) .add(BigIntegerAdapter()) diff --git a/samples/client/petstore/kotlin-uppercase-enum/src/main/kotlin/org/openapitools/client/infrastructure/URIAdapter.kt b/samples/client/petstore/kotlin-uppercase-enum/src/main/kotlin/org/openapitools/client/infrastructure/URIAdapter.kt new file mode 100644 index 00000000000..927522757da --- /dev/null +++ b/samples/client/petstore/kotlin-uppercase-enum/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-uppercase-enum/src/main/kotlin/org/openapitools/client/infrastructure/UUIDAdapter.kt b/samples/client/petstore/kotlin-uppercase-enum/src/main/kotlin/org/openapitools/client/infrastructure/UUIDAdapter.kt index a4a44cc18b7..7ccf7dc25d2 100644 --- a/samples/client/petstore/kotlin-uppercase-enum/src/main/kotlin/org/openapitools/client/infrastructure/UUIDAdapter.kt +++ b/samples/client/petstore/kotlin-uppercase-enum/src/main/kotlin/org/openapitools/client/infrastructure/UUIDAdapter.kt @@ -9,5 +9,5 @@ class UUIDAdapter { fun toJson(uuid: UUID) = uuid.toString() @FromJson - fun fromJson(s: String) = UUID.fromString(s) + fun fromJson(s: String): UUID = UUID.fromString(s) } diff --git a/samples/client/petstore/kotlin-uppercase-enum/src/main/kotlin/org/openapitools/client/models/PetEnum.kt b/samples/client/petstore/kotlin-uppercase-enum/src/main/kotlin/org/openapitools/client/models/PetEnum.kt index 9e1d0b06d7b..0bc84e75f73 100644 --- a/samples/client/petstore/kotlin-uppercase-enum/src/main/kotlin/org/openapitools/client/models/PetEnum.kt +++ b/samples/client/petstore/kotlin-uppercase-enum/src/main/kotlin/org/openapitools/client/models/PetEnum.kt @@ -19,6 +19,7 @@ import com.squareup.moshi.Json * Values: MY_FIRST_VALUE,MY_SECOND_VALUE */ + enum class PetEnum(val value: kotlin.String) { diff --git a/samples/client/petstore/kotlin/.openapi-generator/FILES b/samples/client/petstore/kotlin/.openapi-generator/FILES index 3f4610174cc..16c712325f8 100644 --- a/samples/client/petstore/kotlin/.openapi-generator/FILES +++ b/samples/client/petstore/kotlin/.openapi-generator/FILES @@ -20,7 +20,6 @@ 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/ApiInfrastructureResponse.kt -src/main/kotlin/org/openapitools/client/infrastructure/ApplicationDelegates.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 @@ -32,6 +31,7 @@ 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/ApiResponse.kt src/main/kotlin/org/openapitools/client/models/Category.kt diff --git a/samples/client/petstore/kotlin/.openapi-generator/VERSION b/samples/client/petstore/kotlin/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/client/petstore/kotlin/.openapi-generator/VERSION +++ b/samples/client/petstore/kotlin/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/client/petstore/kotlin/build.gradle b/samples/client/petstore/kotlin/build.gradle index 60e5056e031..bb575e6e4bf 100644 --- a/samples/client/petstore/kotlin/build.gradle +++ b/samples/client/petstore/kotlin/build.gradle @@ -7,7 +7,7 @@ wrapper { } buildscript { - ext.kotlin_version = '1.4.30' + ext.kotlin_version = '1.5.10' repositories { maven { url "https://repo1.maven.org/maven2" } @@ -28,9 +28,9 @@ test { } dependencies { - compile "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version" - compile "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version" - compile "com.squareup.moshi:moshi-kotlin:1.11.0" - compile "com.squareup.okhttp3:okhttp:4.9.0" - testCompile "io.kotlintest:kotlintest-runner-junit5:3.4.2" + implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version" + implementation "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version" + implementation "com.squareup.moshi:moshi-kotlin:1.12.0" + implementation "com.squareup.okhttp3:okhttp:4.9.1" + testImplementation "io.kotlintest:kotlintest-runner-junit5:3.4.2" } diff --git a/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/apis/PetApi.kt b/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/apis/PetApi.kt index c8b93b33bf6..be50dd6c442 100644 --- a/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/apis/PetApi.kt +++ b/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/apis/PetApi.kt @@ -47,7 +47,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun addPet(body: Pet) : Unit { val localVariableConfig = addPetRequestConfig(body = body) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -72,20 +72,18 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param body Pet object that needs to be added to the store * @return RequestConfig */ - fun addPetRequestConfig(body: Pet) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun addPetRequestConfig(body: Pet) : RequestConfig { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/pet", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -102,7 +100,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun deletePet(petId: kotlin.Long, apiKey: kotlin.String?) : Unit { val localVariableConfig = deletePetRequestConfig(petId = petId, apiKey = apiKey) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -128,21 +126,19 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param apiKey (optional) * @return RequestConfig */ - fun deletePetRequestConfig(petId: kotlin.Long, apiKey: kotlin.String?) : RequestConfig { - val localVariableBody: kotlin.Any? = null + 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() } - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.DELETE, path = "/pet/{petId}".replace("{"+"petId"+"}", "$petId"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -159,7 +155,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun findPetsByStatus(status: kotlin.collections.List) : kotlin.collections.List { val localVariableConfig = findPetsByStatusRequestConfig(status = status) - val localVarResponse = request>( + val localVarResponse = request>( localVariableConfig ) @@ -184,23 +180,21 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param status Status values that need to be considered for filter * @return RequestConfig */ - fun findPetsByStatusRequestConfig(status: kotlin.collections.List) : RequestConfig { - val localVariableBody: kotlin.Any? = null + 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() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/pet/findByStatus", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -216,9 +210,10 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { @Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class) @Deprecated(message = "This operation is deprecated.") fun findPetsByTags(tags: kotlin.collections.List) : kotlin.collections.List { + @Suppress("DEPRECATION") val localVariableConfig = findPetsByTagsRequestConfig(tags = tags) - val localVarResponse = request>( + val localVarResponse = request>( localVariableConfig ) @@ -244,23 +239,21 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @return RequestConfig */ @Deprecated(message = "This operation is deprecated.") - fun findPetsByTagsRequestConfig(tags: kotlin.collections.List) : RequestConfig { - val localVariableBody: kotlin.Any? = null + 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() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/pet/findByTags", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -277,7 +270,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun getPetById(petId: kotlin.Long) : Pet { val localVariableConfig = getPetByIdRequestConfig(petId = petId) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -302,20 +295,18 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param petId ID of pet to return * @return RequestConfig */ - fun getPetByIdRequestConfig(petId: kotlin.Long) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun getPetByIdRequestConfig(petId: kotlin.Long) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/pet/{petId}".replace("{"+"petId"+"}", "$petId"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -331,7 +322,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun updatePet(body: Pet) : Unit { val localVariableConfig = updatePetRequestConfig(body = body) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -356,20 +347,18 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param body Pet object that needs to be added to the store * @return RequestConfig */ - fun updatePetRequestConfig(body: Pet) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun updatePetRequestConfig(body: Pet) : RequestConfig { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.PUT, path = "/pet", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -387,7 +376,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun updatePetWithForm(petId: kotlin.Long, name: kotlin.String?, status: kotlin.String?) : Unit { val localVariableConfig = updatePetWithFormRequestConfig(petId = petId, name = name, status = status) - val localVarResponse = request( + val localVarResponse = request, Unit>( localVariableConfig ) @@ -414,20 +403,18 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param status Updated status of the pet (optional) * @return RequestConfig */ - fun updatePetWithFormRequestConfig(petId: kotlin.Long, name: kotlin.String?, status: kotlin.String?) : RequestConfig { - val localVariableBody: kotlin.Any? = mapOf("name" to name, "status" to status) + fun updatePetWithFormRequestConfig(petId: kotlin.Long, name: kotlin.String?, status: kotlin.String?) : RequestConfig> { + val localVariableBody = mapOf("name" to name, "status" to status) val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf("Content-Type" to "application/x-www-form-urlencoded") - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/pet/{petId}".replace("{"+"petId"+"}", "$petId"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -446,7 +433,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun uploadFile(petId: kotlin.Long, additionalMetadata: kotlin.String?, file: java.io.File?) : ApiResponse { val localVariableConfig = uploadFileRequestConfig(petId = petId, additionalMetadata = additionalMetadata, file = file) - val localVarResponse = request( + val localVarResponse = request, ApiResponse>( localVariableConfig ) @@ -473,20 +460,18 @@ class PetApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param file file to upload (optional) * @return RequestConfig */ - fun uploadFileRequestConfig(petId: kotlin.Long, additionalMetadata: kotlin.String?, file: java.io.File?) : RequestConfig { - val localVariableBody: kotlin.Any? = mapOf("additionalMetadata" to additionalMetadata, "file" to file) + fun uploadFileRequestConfig(petId: kotlin.Long, additionalMetadata: kotlin.String?, file: java.io.File?) : RequestConfig> { + val localVariableBody = mapOf("additionalMetadata" to additionalMetadata, "file" to file) val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf("Content-Type" to "multipart/form-data") - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/pet/{petId}/uploadImage".replace("{"+"petId"+"}", "$petId"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } } diff --git a/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt b/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt index 215ed63420c..56a23202f82 100644 --- a/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt +++ b/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt @@ -46,7 +46,7 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) fun deleteOrder(orderId: kotlin.String) : Unit { val localVariableConfig = deleteOrderRequestConfig(orderId = orderId) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -71,20 +71,18 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) * @param orderId ID of the order that needs to be deleted * @return RequestConfig */ - fun deleteOrderRequestConfig(orderId: kotlin.String) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun deleteOrderRequestConfig(orderId: kotlin.String) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.DELETE, path = "/store/order/{orderId}".replace("{"+"orderId"+"}", "$orderId"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -100,7 +98,7 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) fun getInventory() : kotlin.collections.Map { val localVariableConfig = getInventoryRequestConfig() - val localVarResponse = request>( + val localVarResponse = request>( localVariableConfig ) @@ -124,20 +122,18 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) * * @return RequestConfig */ - fun getInventoryRequestConfig() : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun getInventoryRequestConfig() : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/store/inventory", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -154,7 +150,7 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) fun getOrderById(orderId: kotlin.Long) : Order { val localVariableConfig = getOrderByIdRequestConfig(orderId = orderId) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -179,20 +175,18 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) * @param orderId ID of pet that needs to be fetched * @return RequestConfig */ - fun getOrderByIdRequestConfig(orderId: kotlin.Long) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun getOrderByIdRequestConfig(orderId: kotlin.Long) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/store/order/{orderId}".replace("{"+"orderId"+"}", "$orderId"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -209,7 +203,7 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) fun placeOrder(body: Order) : Order { val localVariableConfig = placeOrderRequestConfig(body = body) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -234,20 +228,18 @@ class StoreApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) * @param body order placed for purchasing the pet * @return RequestConfig */ - fun placeOrderRequestConfig(body: Order) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun placeOrderRequestConfig(body: Order) : RequestConfig { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/store/order", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } } diff --git a/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/apis/UserApi.kt b/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/apis/UserApi.kt index 53748b93463..9f93e853a12 100644 --- a/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/apis/UserApi.kt +++ b/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/apis/UserApi.kt @@ -46,7 +46,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun createUser(body: User) : Unit { val localVariableConfig = createUserRequestConfig(body = body) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -71,20 +71,18 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param body Created user object * @return RequestConfig */ - fun createUserRequestConfig(body: User) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun createUserRequestConfig(body: User) : RequestConfig { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/user", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -100,7 +98,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun createUsersWithArrayInput(body: kotlin.collections.List) : Unit { val localVariableConfig = createUsersWithArrayInputRequestConfig(body = body) - val localVarResponse = request( + val localVarResponse = request, Unit>( localVariableConfig ) @@ -125,20 +123,18 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param body List of user object * @return RequestConfig */ - fun createUsersWithArrayInputRequestConfig(body: kotlin.collections.List) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun createUsersWithArrayInputRequestConfig(body: kotlin.collections.List) : RequestConfig> { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/user/createWithArray", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -154,7 +150,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun createUsersWithListInput(body: kotlin.collections.List) : Unit { val localVariableConfig = createUsersWithListInputRequestConfig(body = body) - val localVarResponse = request( + val localVarResponse = request, Unit>( localVariableConfig ) @@ -179,20 +175,18 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param body List of user object * @return RequestConfig */ - fun createUsersWithListInputRequestConfig(body: kotlin.collections.List) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun createUsersWithListInputRequestConfig(body: kotlin.collections.List) : RequestConfig> { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.POST, path = "/user/createWithList", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -208,7 +202,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun deleteUser(username: kotlin.String) : Unit { val localVariableConfig = deleteUserRequestConfig(username = username) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -233,20 +227,18 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param username The name that needs to be deleted * @return RequestConfig */ - fun deleteUserRequestConfig(username: kotlin.String) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun deleteUserRequestConfig(username: kotlin.String) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.DELETE, path = "/user/{username}".replace("{"+"username"+"}", "$username"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -263,7 +255,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun getUserByName(username: kotlin.String) : User { val localVariableConfig = getUserByNameRequestConfig(username = username) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -288,20 +280,18 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param username The name that needs to be fetched. Use user1 for testing. * @return RequestConfig */ - fun getUserByNameRequestConfig(username: kotlin.String) : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun getUserByNameRequestConfig(username: kotlin.String) : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/user/{username}".replace("{"+"username"+"}", "$username"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -319,7 +309,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun loginUser(username: kotlin.String, password: kotlin.String) : kotlin.String { val localVariableConfig = loginUserRequestConfig(username = username, password = password) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -345,24 +335,22 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param password The password for login in clear text * @return RequestConfig */ - fun loginUserRequestConfig(username: kotlin.String, password: kotlin.String) : RequestConfig { - val localVariableBody: kotlin.Any? = null + 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() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/user/login", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -377,7 +365,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun logoutUser() : Unit { val localVariableConfig = logoutUserRequestConfig() - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -401,20 +389,18 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * * @return RequestConfig */ - fun logoutUserRequestConfig() : RequestConfig { - val localVariableBody: kotlin.Any? = null + fun logoutUserRequestConfig() : RequestConfig { + val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.GET, path = "/user/logout", query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } /** @@ -431,7 +417,7 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { fun updateUser(username: kotlin.String, body: User) : Unit { val localVariableConfig = updateUserRequestConfig(username = username, body = body) - val localVarResponse = request( + val localVarResponse = request( localVariableConfig ) @@ -457,20 +443,18 @@ class UserApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { * @param body Updated user object * @return RequestConfig */ - fun updateUserRequestConfig(username: kotlin.String, body: User) : RequestConfig { - val localVariableBody: kotlin.Any? = body + fun updateUserRequestConfig(username: kotlin.String, body: User) : RequestConfig { + val localVariableBody = body val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() - - val localVariableConfig = RequestConfig( + + return RequestConfig( method = RequestMethod.PUT, path = "/user/{username}".replace("{"+"username"+"}", "$username"), query = localVariableQuery, headers = localVariableHeaders, body = localVariableBody ) - - return localVariableConfig } } 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 bc9ed02c0f1..ae6e80e9506 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 @@ -1,6 +1,5 @@ package org.openapitools.client.infrastructure -import okhttp3.Credentials import okhttp3.OkHttpClient import okhttp3.RequestBody import okhttp3.RequestBody.Companion.asRequestBody @@ -12,17 +11,17 @@ import okhttp3.MediaType.Companion.toMediaTypeOrNull import okhttp3.Request import okhttp3.Headers import okhttp3.MultipartBody -import java.io.File import java.io.BufferedWriter +import java.io.File import java.io.FileWriter import java.net.URLConnection -import java.nio.file.Files -import java.util.Date import java.time.LocalDate import java.time.LocalDateTime import java.time.LocalTime import java.time.OffsetDateTime import java.time.OffsetTime +import java.util.Date +import java.util.Locale open class ApiClient(val baseUrl: String) { companion object { @@ -62,9 +61,7 @@ open class ApiClient(val baseUrl: String) { protected inline fun requestBody(content: T, mediaType: String = JsonMediaType): RequestBody = when { - content is File -> content.asRequestBody( - mediaType.toMediaTypeOrNull() - ) + content is File -> content.asRequestBody(mediaType.toMediaTypeOrNull()) mediaType == FormDataMediaType -> { MultipartBody.Builder() .setType(MultipartBody.FORM) @@ -119,7 +116,7 @@ open class ApiClient(val baseUrl: String) { } if (T::class.java == File::class.java) { // return tempfile - val f = Files.createTempFile("tmp.org.openapitools.client", null).toFile() + val f = java.nio.file.Files.createTempFile("tmp.org.openapitools.client", null).toFile() f.deleteOnExit() val out = BufferedWriter(FileWriter(f)) out.write(bodyContent) @@ -132,7 +129,7 @@ open class ApiClient(val baseUrl: String) { } } - protected fun updateAuthParams(requestConfig: RequestConfig) { + protected fun updateAuthParams(requestConfig: RequestConfig) { if (requestConfig.headers["api_key"].isNullOrEmpty()) { if (apiKey["api_key"] != null) { if (apiKeyPrefix["api_key"] != null) { @@ -149,7 +146,7 @@ open class ApiClient(val baseUrl: String) { } } - protected inline fun request(requestConfig: RequestConfig): ApiInfrastructureResponse { + protected inline fun request(requestConfig: RequestConfig): ApiInfrastructureResponse { val httpUrl = baseUrl.toHttpUrlOrNull() ?: throw IllegalStateException("baseUrl is invalid.") // take authMethod from operation @@ -183,7 +180,7 @@ open class ApiClient(val baseUrl: String) { } // TODO: support multiple contentType options here. - val contentType = (headers[ContentType] as String).substringBefore(";").toLowerCase() + val contentType = (headers[ContentType] as String).substringBefore(";").lowercase(Locale.getDefault()) val request = when (requestConfig.method) { RequestMethod.DELETE -> Request.Builder().url(url).delete(requestBody(requestConfig.body, contentType)) @@ -198,57 +195,46 @@ open class ApiClient(val baseUrl: String) { }.build() val response = client.newCall(request).execute() - val accept = response.header(ContentType)?.substringBefore(";")?.toLowerCase() + val accept = response.header(ContentType)?.substringBefore(";")?.lowercase(Locale.getDefault()) // TODO: handle specific mapping types. e.g. Map> - when { - response.isRedirect -> return Redirection( - response.code, - response.headers.toMultimap() + return when { + response.isRedirect -> Redirection( + response.code, + response.headers.toMultimap() ) - response.isInformational -> return Informational( - response.message, - response.code, - response.headers.toMultimap() + response.isInformational -> Informational( + response.message, + response.code, + response.headers.toMultimap() ) - response.isSuccessful -> return Success( - responseBody(response.body, accept), - response.code, - response.headers.toMultimap() + response.isSuccessful -> Success( + responseBody(response.body, accept), + response.code, + response.headers.toMultimap() ) - response.isClientError -> return ClientError( - response.message, - response.body?.string(), - response.code, - response.headers.toMultimap() + response.isClientError -> ClientError( + response.message, + response.body?.string(), + response.code, + response.headers.toMultimap() ) - else -> return ServerError( - 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 -> { - return "" - } - is Array<*> -> { - return toMultiValue(value, "csv").toString() - } - is Iterable<*> -> { - return toMultiValue(value, "csv").toString() - } - is OffsetDateTime, is OffsetTime, is LocalDateTime, is LocalDate, is LocalTime, is Date -> { - return parseDateToQueryString(value) - } - else -> { - return value.toString() - } - } + 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, is Date -> + parseDateToQueryString(value) + else -> value.toString() } protected inline fun parseDateToQueryString(value : T): String { 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 0f2790f370e..7e948e1dd07 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 @@ -8,10 +8,10 @@ package org.openapitools.client.infrastructure * NOTE: Headers is a Map because rfc2616 defines * multi-valued headers as csv-only. */ -data class RequestConfig( +data class RequestConfig( val method: RequestMethod, val path: String, val headers: MutableMap = mutableMapOf(), val query: MutableMap> = mutableMapOf(), - val body: kotlin.Any? = null + val body: T? = null ) \ No newline at end of file diff --git a/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt b/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt index 3d0a6c32566..e77581231c3 100644 --- a/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt +++ b/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt @@ -12,6 +12,7 @@ object Serializer { .add(LocalDateAdapter()) .add(UUIDAdapter()) .add(ByteArrayAdapter()) + .add(URIAdapter()) .add(KotlinJsonAdapterFactory()) .add(BigDecimalAdapter()) .add(BigIntegerAdapter()) diff --git a/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/infrastructure/URIAdapter.kt b/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/infrastructure/URIAdapter.kt new file mode 100644 index 00000000000..927522757da --- /dev/null +++ b/samples/client/petstore/kotlin/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/src/main/kotlin/org/openapitools/client/infrastructure/UUIDAdapter.kt b/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/infrastructure/UUIDAdapter.kt index a4a44cc18b7..7ccf7dc25d2 100644 --- a/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/infrastructure/UUIDAdapter.kt +++ b/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/infrastructure/UUIDAdapter.kt @@ -9,5 +9,5 @@ class UUIDAdapter { fun toJson(uuid: UUID) = uuid.toString() @FromJson - fun fromJson(s: String) = UUID.fromString(s) + fun fromJson(s: String): UUID = UUID.fromString(s) } diff --git a/samples/client/petstore/lua/.openapi-generator/VERSION b/samples/client/petstore/lua/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/client/petstore/lua/.openapi-generator/VERSION +++ b/samples/client/petstore/lua/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/client/petstore/nim/.openapi-generator/VERSION b/samples/client/petstore/nim/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/client/petstore/nim/.openapi-generator/VERSION +++ b/samples/client/petstore/nim/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/client/petstore/objc/core-data/.openapi-generator/VERSION b/samples/client/petstore/objc/core-data/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/client/petstore/objc/core-data/.openapi-generator/VERSION +++ b/samples/client/petstore/objc/core-data/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/client/petstore/objc/default/.openapi-generator/VERSION b/samples/client/petstore/objc/default/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/client/petstore/objc/default/.openapi-generator/VERSION +++ b/samples/client/petstore/objc/default/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/client/petstore/perl/.openapi-generator/VERSION b/samples/client/petstore/perl/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/client/petstore/perl/.openapi-generator/VERSION +++ b/samples/client/petstore/perl/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/client/petstore/perl/README.md b/samples/client/petstore/perl/README.md index 9dd81b461b1..2a469ee47b7 100644 --- a/samples/client/petstore/perl/README.md +++ b/samples/client/petstore/perl/README.md @@ -385,6 +385,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_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 diff --git a/samples/client/petstore/perl/docs/FakeApi.md b/samples/client/petstore/perl/docs/FakeApi.md index d1696217c59..9db900a571a 100644 --- a/samples/client/petstore/perl/docs/FakeApi.md +++ b/samples/client/petstore/perl/docs/FakeApi.md @@ -16,6 +16,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_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 @@ -347,12 +348,57 @@ 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_with_binary** +> test_body_with_binary(body => $body) + + + +For this test, the body has to be a binary file. + +### Example +```perl +use Data::Dumper; +use WWW::OpenAPIClient::FakeApi; +my $api_instance = WWW::OpenAPIClient::FakeApi->new( +); + +my $body = WWW::OpenAPIClient::Object::string->new(); # string | image to upload + +eval { + $api_instance->test_body_with_binary(body => $body); +}; +if ($@) { + warn "Exception when calling FakeApi->test_body_with_binary: $@\n"; +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | **string****string**| image to upload | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: image/png + - **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_file_schema** > test_body_with_file_schema(file_schema_test_class => $file_schema_test_class) -For this test, the body for this request much reference a schema named `File`. +For this test, the body for this request must reference a schema named `File`. ### Example ```perl diff --git a/samples/client/petstore/perl/lib/WWW/OpenAPIClient/FakeApi.pm b/samples/client/petstore/perl/lib/WWW/OpenAPIClient/FakeApi.pm index 8646aa3cc07..d3879045dee 100644 --- a/samples/client/petstore/perl/lib/WWW/OpenAPIClient/FakeApi.pm +++ b/samples/client/petstore/perl/lib/WWW/OpenAPIClient/FakeApi.pm @@ -485,6 +485,62 @@ sub fake_property_enum_integer_serialize { return $_response_object; } +# +# test_body_with_binary +# +# +# +# @param string $body image to upload (required) +{ + my $params = { + 'body' => { + data_type => 'string', + description => 'image to upload', + required => '1', + }, + }; + __PACKAGE__->method_documentation->{ 'test_body_with_binary' } = { + summary => '', + params => $params, + returns => undef, + }; +} +# @return void +# +sub test_body_with_binary { + my ($self, %args) = @_; + + # parse inputs + my $_resource_path = '/fake/body-with-binary'; + + my $_method = 'PUT'; + 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('image/png'); + + my $_body_data; + # body params + if ( exists $args{'body'}) { + $_body_data = $args{'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_file_schema # diff --git a/samples/client/petstore/php/OpenAPIClient-php/.openapi-generator/VERSION b/samples/client/petstore/php/OpenAPIClient-php/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/.openapi-generator/VERSION +++ b/samples/client/petstore/php/OpenAPIClient-php/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/client/petstore/php/OpenAPIClient-php/README.md b/samples/client/petstore/php/OpenAPIClient-php/README.md index 2f4807ddee0..6540cb639a5 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/README.md +++ b/samples/client/petstore/php/OpenAPIClient-php/README.md @@ -80,6 +80,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* | [**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 | *FakeApi* | [**testClientModel**](docs/Api/FakeApi.md#testclientmodel) | **PATCH** /fake | To test \"client\" model 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 4319d48a408..ce8d2050136 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/docs/Api/FakeApi.md +++ b/samples/client/petstore/php/OpenAPIClient-php/docs/Api/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 | +[**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 | [**testClientModel()**](FakeApi.md#testClientModel) | **PATCH** /fake | To test \"client\" model @@ -412,6 +413,61 @@ No authorization required [[Back to Model list]](../../README.md#models) [[Back to README]](../../README.md) +## `testBodyWithBinary()` + +```php +testBodyWithBinary($body) +``` + + + +For this test, the body has to be a binary file. + +### Example + +```php +testBodyWithBinary($body); +} catch (Exception $e) { + echo 'Exception when calling FakeApi->testBodyWithBinary: ', $e->getMessage(), PHP_EOL; +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | **\SplFileObject****\SplFileObject**| image to upload | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: `image/png` +- **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) + ## `testBodyWithFileSchema()` ```php @@ -420,7 +476,7 @@ testBodyWithFileSchema($file_schema_test_class) -For this test, the body for this request much reference a schema named `File`. +For this test, the body for this request must reference a schema named `File`. ### Example 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 e274c49defd..fc90624b4df 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,11 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech +<<<<<<< HEAD * OpenAPI Generator version: 6.0.0-SNAPSHOT +======= + * OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x */ /** 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 c34fe66e69e..50c39e12a57 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,11 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech +<<<<<<< HEAD * OpenAPI Generator version: 6.0.0-SNAPSHOT +======= + * OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x */ /** 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 a9b246949f7..61f7633e202 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,11 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech +<<<<<<< HEAD * OpenAPI Generator version: 6.0.0-SNAPSHOT +======= + * OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x */ /** @@ -1847,6 +1851,215 @@ class FakeApi ); } + /** + * Operation testBodyWithBinary + * + * @param \SplFileObject $body image to upload (required) + * + * @throws \OpenAPI\Client\ApiException on non-2xx response + * @throws \InvalidArgumentException + * @return void + */ + public function testBodyWithBinary($body) + { + $this->testBodyWithBinaryWithHttpInfo($body); + } + + /** + * Operation testBodyWithBinaryWithHttpInfo + * + * @param \SplFileObject $body image to upload (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 testBodyWithBinaryWithHttpInfo($body) + { + $request = $this->testBodyWithBinaryRequest($body); + + 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 + ); + } + + $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 testBodyWithBinaryAsync + * + * @param \SplFileObject $body image to upload (required) + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function testBodyWithBinaryAsync($body) + { + return $this->testBodyWithBinaryAsyncWithHttpInfo($body) + ->then( + function ($response) { + return $response[0]; + } + ); + } + + /** + * Operation testBodyWithBinaryAsyncWithHttpInfo + * + * @param \SplFileObject $body image to upload (required) + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function testBodyWithBinaryAsyncWithHttpInfo($body) + { + $returnType = ''; + $request = $this->testBodyWithBinaryRequest($body); + + 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 'testBodyWithBinary' + * + * @param \SplFileObject $body image to upload (required) + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Psr7\Request + */ + public function testBodyWithBinaryRequest($body) + { + // verify the required parameter 'body' is set + if ($body === null || (is_array($body) && count($body) === 0)) { + throw new \InvalidArgumentException( + 'Missing the required parameter $body when calling testBodyWithBinary' + ); + } + + $resourcePath = '/fake/body-with-binary'; + $formParams = []; + $queryParams = []; + $headerParams = []; + $httpBody = ''; + $multipart = false; + + + + + + if ($multipart) { + $headers = $this->headerSelector->selectHeadersForMultipart( + [] + ); + } else { + $headers = $this->headerSelector->selectHeaders( + [], + ['image/png'] + ); + } + + // for model (json/xml) + if (isset($body)) { + if ($headers['Content-Type'] === 'application/json') { + $httpBody = \GuzzleHttp\json_encode(ObjectSerializer::sanitizeForSerialization($body)); + } else { + $httpBody = $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 = \GuzzleHttp\json_encode($formParams); + + } else { + // for HTTP post (form) + $httpBody = \GuzzleHttp\Psr7\build_query($formParams); + } + } + + + $defaultHeaders = []; + if ($this->config->getUserAgent()) { + $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); + } + + $headers = array_merge( + $defaultHeaders, + $headerParams, + $headers + ); + + $query = \GuzzleHttp\Psr7\build_query($queryParams); + return new Request( + 'PUT', + $this->config->getHost() . $resourcePath . ($query ? "?{$query}" : ''), + $headers, + $httpBody + ); + } + /** * Operation testBodyWithFileSchema * @@ -4217,15 +4430,11 @@ class FakeApi $multipart = false; // query params + if (is_array($pipe)) { + $pipe = ObjectSerializer::serializeCollection($pipe, 'pipeDelimited', true); + } if ($pipe !== null) { - if('form' === 'form' && is_array($pipe)) { - foreach($pipe as $key => $value) { - $queryParams[$key] = $value; - } - } - else { - $queryParams['pipe'] = $pipe; - } + $queryParams['pipe'] = $pipe; } // query params if (is_array($ioutil)) { 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 3a839b44195..4ca760e8333 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,11 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech +<<<<<<< HEAD * OpenAPI Generator version: 6.0.0-SNAPSHOT +======= + * OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x */ /** 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 20a126194bc..e04bb268794 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,11 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech +<<<<<<< HEAD * OpenAPI Generator version: 6.0.0-SNAPSHOT +======= + * OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x */ /** 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 b69d2fcad45..f0a660d6705 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,11 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech +<<<<<<< HEAD * OpenAPI Generator version: 6.0.0-SNAPSHOT +======= + * OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x */ /** 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 621d0ae7e48..6fbfe0531cb 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,11 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech +<<<<<<< HEAD * OpenAPI Generator version: 6.0.0-SNAPSHOT +======= + * OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x */ /** diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/ApiException.php b/samples/client/petstore/php/OpenAPIClient-php/lib/ApiException.php index dbf0b74a5de..8a36b391917 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/ApiException.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/ApiException.php @@ -16,7 +16,11 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech +<<<<<<< HEAD * OpenAPI Generator version: 6.0.0-SNAPSHOT +======= + * OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x */ /** diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Configuration.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Configuration.php index 4b7cde6f651..858ade0a135 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Configuration.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Configuration.php @@ -16,7 +16,11 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech +<<<<<<< HEAD * OpenAPI Generator version: 6.0.0-SNAPSHOT +======= + * OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x */ /** diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/HeaderSelector.php b/samples/client/petstore/php/OpenAPIClient-php/lib/HeaderSelector.php index b581653f899..2753d49f2ca 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/HeaderSelector.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/HeaderSelector.php @@ -16,7 +16,11 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech +<<<<<<< HEAD * OpenAPI Generator version: 6.0.0-SNAPSHOT +======= + * OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x */ /** 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 c683523db47..a81b16b161f 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,11 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech +<<<<<<< HEAD * OpenAPI Generator version: 6.0.0-SNAPSHOT +======= + * OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x */ /** 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 72f96cc82ef..face3590373 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,11 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech +<<<<<<< HEAD * OpenAPI Generator version: 6.0.0-SNAPSHOT +======= + * OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x */ /** 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 578f3dcf4fd..089f017d0a1 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,11 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech +<<<<<<< HEAD * OpenAPI Generator version: 6.0.0-SNAPSHOT +======= + * OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x */ /** 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 b34e160fe4a..7f8483a0143 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,11 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech +<<<<<<< HEAD * OpenAPI Generator version: 6.0.0-SNAPSHOT +======= + * OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x */ /** 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 b6c852835fa..fd62de9d944 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,11 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech +<<<<<<< HEAD * OpenAPI Generator version: 6.0.0-SNAPSHOT +======= + * OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x */ /** 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 926094ca886..5f43ff20946 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,11 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech +<<<<<<< HEAD * OpenAPI Generator version: 6.0.0-SNAPSHOT +======= + * OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x */ /** 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 f7529adcd39..497a311f92e 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,11 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech +<<<<<<< HEAD * OpenAPI Generator version: 6.0.0-SNAPSHOT +======= + * OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x */ /** 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 1942a63cc90..bc612bfeec9 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,11 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech +<<<<<<< HEAD * OpenAPI Generator version: 6.0.0-SNAPSHOT +======= + * OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x */ /** diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/CatAllOf.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/CatAllOf.php index 6d34416801b..3659234edfd 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/CatAllOf.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/CatAllOf.php @@ -17,7 +17,11 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech +<<<<<<< HEAD * OpenAPI Generator version: 6.0.0-SNAPSHOT +======= + * OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x */ /** 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 80fd93f2298..dbb76598cf6 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,11 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech +<<<<<<< HEAD * OpenAPI Generator version: 6.0.0-SNAPSHOT +======= + * OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x */ /** 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 7248264909b..64383103d1d 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,11 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech +<<<<<<< HEAD * OpenAPI Generator version: 6.0.0-SNAPSHOT +======= + * OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x */ /** 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 5cab06ef880..acc19883332 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,11 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech +<<<<<<< HEAD * OpenAPI Generator version: 6.0.0-SNAPSHOT +======= + * OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x */ /** 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 ca6a91fb50e..ab8b1aa9fa7 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,11 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech +<<<<<<< HEAD * OpenAPI Generator version: 6.0.0-SNAPSHOT +======= + * OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x */ /** diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/DogAllOf.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/DogAllOf.php index 2c833dfd94a..6b70a19af97 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/DogAllOf.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/DogAllOf.php @@ -17,7 +17,11 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech +<<<<<<< HEAD * OpenAPI Generator version: 6.0.0-SNAPSHOT +======= + * OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x */ /** 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 cce2b822f17..3a24aadf25d 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,11 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech +<<<<<<< HEAD * OpenAPI Generator version: 6.0.0-SNAPSHOT +======= + * OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x */ /** 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 e73d0a55fe0..4b886dd3a37 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,11 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech +<<<<<<< HEAD * OpenAPI Generator version: 6.0.0-SNAPSHOT +======= + * OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x */ /** 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 a9eaba5ffc3..5fb88686006 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,11 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech +<<<<<<< HEAD * OpenAPI Generator version: 6.0.0-SNAPSHOT +======= + * OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x */ /** 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 e24d5cd20d3..a42239cecf3 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,11 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech +<<<<<<< HEAD * OpenAPI Generator version: 6.0.0-SNAPSHOT +======= + * OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x */ /** 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 a93f493e584..904a48737cb 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,11 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech +<<<<<<< HEAD * OpenAPI Generator version: 6.0.0-SNAPSHOT +======= + * OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x */ /** 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 ca94f928380..49f6dcc28de 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,11 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech +<<<<<<< HEAD * OpenAPI Generator version: 6.0.0-SNAPSHOT +======= + * OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x */ /** 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 11945dd803f..699c545750c 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,11 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech +<<<<<<< HEAD * OpenAPI Generator version: 6.0.0-SNAPSHOT +======= + * OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x */ /** 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 104d77da150..a274cde05d8 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,11 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech +<<<<<<< HEAD * OpenAPI Generator version: 6.0.0-SNAPSHOT +======= + * OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x */ /** 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 b5d373d06e9..d2177e059b4 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,11 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech +<<<<<<< HEAD * OpenAPI Generator version: 6.0.0-SNAPSHOT +======= + * OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x */ /** diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/InlineResponseDefault.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/InlineResponseDefault.php index 31094c88e47..e62630cb581 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/InlineResponseDefault.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/InlineResponseDefault.php @@ -17,7 +17,11 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech +<<<<<<< HEAD * OpenAPI Generator version: 6.0.0-SNAPSHOT +======= + * OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x */ /** 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 43b66104acd..32291a7b956 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,11 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech +<<<<<<< HEAD * OpenAPI Generator version: 6.0.0-SNAPSHOT +======= + * OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x */ /** 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 eb612fdcbcb..34aeb340cc6 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,11 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech +<<<<<<< HEAD * OpenAPI Generator version: 6.0.0-SNAPSHOT +======= + * OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x */ /** 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 0a31e0354bd..17f6f79c100 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,11 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech +<<<<<<< HEAD * OpenAPI Generator version: 6.0.0-SNAPSHOT +======= + * OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x */ /** 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 272493d1ab6..18961c5d195 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,11 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech +<<<<<<< HEAD * OpenAPI Generator version: 6.0.0-SNAPSHOT +======= + * OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x */ /** 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 2ab8188521d..bd279888906 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,11 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech +<<<<<<< HEAD * OpenAPI Generator version: 6.0.0-SNAPSHOT +======= + * OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x */ /** 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 f1b432b5afa..d5a94f4a277 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,11 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech +<<<<<<< HEAD * OpenAPI Generator version: 6.0.0-SNAPSHOT +======= + * OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x */ /** 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 97b77d52ce2..949eb0b7735 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,11 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech +<<<<<<< HEAD * OpenAPI Generator version: 6.0.0-SNAPSHOT +======= + * OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x */ /** 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 7664b5b7db8..566e042e7eb 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,11 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech +<<<<<<< HEAD * OpenAPI Generator version: 6.0.0-SNAPSHOT +======= + * OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x */ /** 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 eb69c865e06..91875f73c43 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,11 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech +<<<<<<< HEAD * OpenAPI Generator version: 6.0.0-SNAPSHOT +======= + * OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x */ /** 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 330f8553863..b855a520c6b 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,11 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech +<<<<<<< HEAD * OpenAPI Generator version: 6.0.0-SNAPSHOT +======= + * OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x */ /** 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 f107d19892e..666ea542fab 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,11 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech +<<<<<<< HEAD * OpenAPI Generator version: 6.0.0-SNAPSHOT +======= + * OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x */ /** 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 dce8fcf5482..9d55484163d 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,11 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech +<<<<<<< HEAD * OpenAPI Generator version: 6.0.0-SNAPSHOT +======= + * OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x */ /** 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 d8a1f0d00c0..20be3cbb9cb 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,11 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech +<<<<<<< HEAD * OpenAPI Generator version: 6.0.0-SNAPSHOT +======= + * OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x */ /** 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 dda213945d6..8dc1a541174 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,11 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech +<<<<<<< HEAD * OpenAPI Generator version: 6.0.0-SNAPSHOT +======= + * OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x */ /** 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 e0e9334622d..7d46a63ed67 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,11 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech +<<<<<<< HEAD * OpenAPI Generator version: 6.0.0-SNAPSHOT +======= + * OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x */ /** 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 798cacdf166..f4543fcb433 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,11 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech +<<<<<<< HEAD * OpenAPI Generator version: 6.0.0-SNAPSHOT +======= + * OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x */ /** 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 aced8e0837f..957dcdde2f5 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,11 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech +<<<<<<< HEAD * OpenAPI Generator version: 6.0.0-SNAPSHOT +======= + * OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x */ /** 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 0e23abd34f8..e05a3116b65 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,11 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech +<<<<<<< HEAD * OpenAPI Generator version: 6.0.0-SNAPSHOT +======= + * OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x */ /** 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 7ac47a8b4f9..b2e810da372 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,11 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech +<<<<<<< HEAD * OpenAPI Generator version: 6.0.0-SNAPSHOT +======= + * OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x */ /** 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 5911b10ec15..ef81ed203e1 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,11 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech +<<<<<<< HEAD * OpenAPI Generator version: 6.0.0-SNAPSHOT +======= + * OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x */ /** 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 11b01b255f7..5e046821f51 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,11 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech +<<<<<<< HEAD * OpenAPI Generator version: 6.0.0-SNAPSHOT +======= + * OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x */ /** diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/ObjectSerializer.php b/samples/client/petstore/php/OpenAPIClient-php/lib/ObjectSerializer.php index 7afe22cafe3..d684f740fef 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/ObjectSerializer.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/ObjectSerializer.php @@ -17,7 +17,11 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech +<<<<<<< HEAD * OpenAPI Generator version: 6.0.0-SNAPSHOT +======= + * OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x */ /** diff --git a/samples/client/petstore/powershell/.openapi-generator/VERSION b/samples/client/petstore/powershell/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/client/petstore/powershell/.openapi-generator/VERSION +++ b/samples/client/petstore/powershell/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/client/petstore/powershell/docs/PSPetApi.md b/samples/client/petstore/powershell/docs/PSPetApi.md index 5b8c2a0f2e3..913618efaf3 100644 --- a/samples/client/petstore/powershell/docs/PSPetApi.md +++ b/samples/client/petstore/powershell/docs/PSPetApi.md @@ -28,11 +28,13 @@ $Configuration = Get-Configuration # Configure OAuth2 access token for authorization: petstore_auth $Configuration.AccessToken = "YOUR_ACCESS_TOKEN" -$Pet = (Initialize-Pet -Id 123 -Category (Initialize-Category -Id 123 -Name "Name_example") -Name "Name_example" -PhotoUrls @("PhotoUrls_example") -Tags @((Initialize-Tag -Id 123 -Name "Name_example")) -Status "available") # Pet | Pet object that needs to be added to the store +$Category = Initialize-Category -Id 0 -Name "MyName" +$Tag = Initialize-Tag -Id 0 -Name "MyName" +$Pet = Initialize-Pet -Id 0 -Category $Category -Name "doggie" -PhotoUrls "MyPhotoUrls" -Tags $Tag -Status "available" # Pet | Pet object that needs to be added to the store # Add a new pet to the store try { - $Result = Add-PSPet -Pet $Pet + $Result = Add-PSPet -Pet $Pet } catch { Write-Host ("Exception occured when calling Add-PSPet: {0}" -f ($_.ErrorDetails | ConvertFrom-Json)) Write-Host ("Response headers: {0}" -f ($_.Exception.Response.Headers | ConvertTo-Json)) @@ -75,12 +77,12 @@ $Configuration = Get-Configuration # Configure OAuth2 access token for authorization: petstore_auth $Configuration.AccessToken = "YOUR_ACCESS_TOKEN" -$PetId = 987 # Int64 | Pet id to delete -$ApiKey = "ApiKey_example" # String | (optional) +$PetId = 789 # Int64 | Pet id to delete +$ApiKey = "MyApiKey" # String | (optional) # Deletes a pet try { - $Result = Remove-Pet -PetId $PetId -ApiKey $ApiKey + $Result = Remove-Pet -PetId $PetId -ApiKey $ApiKey } catch { Write-Host ("Exception occured when calling Remove-Pet: {0}" -f ($_.ErrorDetails | ConvertFrom-Json)) Write-Host ("Response headers: {0}" -f ($_.Exception.Response.Headers | ConvertTo-Json)) @@ -125,11 +127,11 @@ $Configuration = Get-Configuration # Configure OAuth2 access token for authorization: petstore_auth $Configuration.AccessToken = "YOUR_ACCESS_TOKEN" -$Status = @("available") # String[] | Status values that need to be considered for filter +$Status = "available" # String[] | Status values that need to be considered for filter # Finds Pets by status try { - $Result = Find-PSPetsByStatus -Status $Status + $Result = Find-PSPetsByStatus -Status $Status } catch { Write-Host ("Exception occured when calling Find-PSPetsByStatus: {0}" -f ($_.ErrorDetails | ConvertFrom-Json)) Write-Host ("Response headers: {0}" -f ($_.Exception.Response.Headers | ConvertTo-Json)) @@ -173,11 +175,11 @@ $Configuration = Get-Configuration # Configure OAuth2 access token for authorization: petstore_auth $Configuration.AccessToken = "YOUR_ACCESS_TOKEN" -$Tags = @("Inner_example") # String[] | Tags to filter by +$Tags = "MyTags" # String[] | Tags to filter by # Finds Pets by tags try { - $Result = Find-PSPetsByTags -Tags $Tags + $Result = Find-PSPetsByTags -Tags $Tags } catch { Write-Host ("Exception occured when calling Find-PSPetsByTags: {0}" -f ($_.ErrorDetails | ConvertFrom-Json)) Write-Host ("Response headers: {0}" -f ($_.Exception.Response.Headers | ConvertTo-Json)) @@ -223,11 +225,11 @@ $Configuration.ApiKey.api_key = "YOUR_API_KEY" # Uncomment below to setup prefix (e.g. Bearer) for API key, if needed #$Configuration.ApiKeyPrefix.api_key = "Bearer" -$PetId = 987 # Int64 | ID of pet to return +$PetId = 789 # Int64 | ID of pet to return # Find pet by ID try { - $Result = Get-PSPetById -PetId $PetId + $Result = Get-PSPetById -PetId $PetId } catch { Write-Host ("Exception occured when calling Get-PSPetById: {0}" -f ($_.ErrorDetails | ConvertFrom-Json)) Write-Host ("Response headers: {0}" -f ($_.Exception.Response.Headers | ConvertTo-Json)) @@ -269,11 +271,13 @@ $Configuration = Get-Configuration # Configure OAuth2 access token for authorization: petstore_auth $Configuration.AccessToken = "YOUR_ACCESS_TOKEN" -$Pet = (Initialize-Pet -Id 123 -Category (Initialize-Category -Id 123 -Name "Name_example") -Name "Name_example" -PhotoUrls @("PhotoUrls_example") -Tags @((Initialize-Tag -Id 123 -Name "Name_example")) -Status "available") # Pet | Pet object that needs to be added to the store +$Category = Initialize-Category -Id 0 -Name "MyName" +$Tag = Initialize-Tag -Id 0 -Name "MyName" +$Pet = Initialize-Pet -Id 0 -Category $Category -Name "doggie" -PhotoUrls "MyPhotoUrls" -Tags $Tag -Status "available" # Pet | Pet object that needs to be added to the store # Update an existing pet try { - $Result = Update-PSPet -Pet $Pet + $Result = Update-PSPet -Pet $Pet } catch { Write-Host ("Exception occured when calling Update-PSPet: {0}" -f ($_.ErrorDetails | ConvertFrom-Json)) Write-Host ("Response headers: {0}" -f ($_.Exception.Response.Headers | ConvertTo-Json)) @@ -317,13 +321,13 @@ $Configuration = Get-Configuration # Configure OAuth2 access token for authorization: petstore_auth $Configuration.AccessToken = "YOUR_ACCESS_TOKEN" -$PetId = 987 # 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) +$PetId = 789 # Int64 | ID of pet that needs to be updated +$Name = "MyName" # String | Updated name of the pet (optional) +$Status = "MyStatus" # String | Updated status of the pet (optional) # Updates a pet in the store with form data try { - $Result = Update-PSPetWithForm -PetId $PetId -Name $Name -Status $Status + $Result = Update-PSPetWithForm -PetId $PetId -Name $Name -Status $Status } catch { Write-Host ("Exception occured when calling Update-PSPetWithForm: {0}" -f ($_.ErrorDetails | ConvertFrom-Json)) Write-Host ("Response headers: {0}" -f ($_.Exception.Response.Headers | ConvertTo-Json)) @@ -369,13 +373,13 @@ $Configuration = Get-Configuration # Configure OAuth2 access token for authorization: petstore_auth $Configuration.AccessToken = "YOUR_ACCESS_TOKEN" -$PetId = 987 # Int64 | ID of pet to update -$AdditionalMetadata = "AdditionalMetadata_example" # String | Additional data to pass to server (optional) -$File = 987 # System.IO.FileInfo | file to upload (optional) +$PetId = 789 # Int64 | ID of pet to update +$AdditionalMetadata = "MyAdditionalMetadata" # String | Additional data to pass to server (optional) +$File = # System.IO.FileInfo | file to upload (optional) # uploads an image try { - $Result = Invoke-PSUploadFile -PetId $PetId -AdditionalMetadata $AdditionalMetadata -File $File + $Result = Invoke-PSUploadFile -PetId $PetId -AdditionalMetadata $AdditionalMetadata -File $File } catch { Write-Host ("Exception occured when calling Invoke-PSUploadFile: {0}" -f ($_.ErrorDetails | ConvertFrom-Json)) Write-Host ("Response headers: {0}" -f ($_.Exception.Response.Headers | ConvertTo-Json)) diff --git a/samples/client/petstore/powershell/docs/PSStoreApi.md b/samples/client/petstore/powershell/docs/PSStoreApi.md index 33b3541ced6..479c994a009 100644 --- a/samples/client/petstore/powershell/docs/PSStoreApi.md +++ b/samples/client/petstore/powershell/docs/PSStoreApi.md @@ -21,11 +21,11 @@ For valid response try integer IDs with value < 1000. Anything above 1000 or non ### Example ```powershell -$OrderId = "OrderId_example" # String | ID of the order that needs to be deleted +$OrderId = "MyOrderId" # String | ID of the order that needs to be deleted # Delete purchase order by ID try { - $Result = Remove-PSOrder -OrderId $OrderId + $Result = Remove-PSOrder -OrderId $OrderId } catch { Write-Host ("Exception occured when calling Remove-PSOrder: {0}" -f ($_.ErrorDetails | ConvertFrom-Json)) Write-Host ("Response headers: {0}" -f ($_.Exception.Response.Headers | ConvertTo-Json)) @@ -73,7 +73,7 @@ $Configuration.ApiKey.api_key = "YOUR_API_KEY" # Returns pet inventories by status try { - $Result = Get-PSInventory + $Result = Get-PSInventory } catch { Write-Host ("Exception occured when calling Get-PSInventory: {0}" -f ($_.ErrorDetails | ConvertFrom-Json)) Write-Host ("Response headers: {0}" -f ($_.Exception.Response.Headers | ConvertTo-Json)) @@ -109,11 +109,11 @@ For valid response try integer IDs with value <= 5 or > 10. Other values will ge ### Example ```powershell -$OrderId = 987 # Int64 | ID of pet that needs to be fetched +$OrderId = 789 # Int64 | ID of pet that needs to be fetched # Find purchase order by ID try { - $Result = Get-PSOrderById -OrderId $OrderId + $Result = Get-PSOrderById -OrderId $OrderId } catch { Write-Host ("Exception occured when calling Get-PSOrderById: {0}" -f ($_.ErrorDetails | ConvertFrom-Json)) Write-Host ("Response headers: {0}" -f ($_.Exception.Response.Headers | ConvertTo-Json)) @@ -150,11 +150,11 @@ Place an order for a pet ### Example ```powershell -$Order = (Initialize-Order -Id 123 -PetId 123 -Quantity 123 -ShipDate Get-Date -Status "placed" -Complete $false) # Order | order placed for purchasing the pet +$Order = Initialize-Order -Id 0 -PetId 0 -Quantity 0 -ShipDate (Get-Date) -Status "placed" -Complete $false # Order | order placed for purchasing the pet # Place an order for a pet try { - $Result = Invoke-PSPlaceOrder -Order $Order + $Result = Invoke-PSPlaceOrder -Order $Order } catch { Write-Host ("Exception occured when calling Invoke-PSPlaceOrder: {0}" -f ($_.ErrorDetails | ConvertFrom-Json)) Write-Host ("Response headers: {0}" -f ($_.Exception.Response.Headers | ConvertTo-Json)) diff --git a/samples/client/petstore/powershell/docs/PSUserApi.md b/samples/client/petstore/powershell/docs/PSUserApi.md index f008e292f2c..f701d6daba9 100644 --- a/samples/client/petstore/powershell/docs/PSUserApi.md +++ b/samples/client/petstore/powershell/docs/PSUserApi.md @@ -32,11 +32,11 @@ $Configuration.ApiKey.AUTH_KEY = "YOUR_API_KEY" # Uncomment below to setup prefix (e.g. Bearer) for API key, if needed #$Configuration.ApiKeyPrefix.AUTH_KEY = "Bearer" -$User = (Initialize-User -Id 123 -Username "Username_example" -FirstName "FirstName_example" -LastName "LastName_example" -Email "Email_example" -Password "Password_example" -Phone "Phone_example" -UserStatus 123) # User | Created user object +$User = Initialize-User -Id 0 -Username "MyUsername" -FirstName "MyFirstName" -LastName "MyLastName" -Email "MyEmail" -Password "MyPassword" -Phone "MyPhone" -UserStatus 0 # User | Created user object # Create user try { - $Result = New-PSUser -User $User + $Result = New-PSUser -User $User } catch { Write-Host ("Exception occured when calling New-PSUser: {0}" -f ($_.ErrorDetails | ConvertFrom-Json)) Write-Host ("Response headers: {0}" -f ($_.Exception.Response.Headers | ConvertTo-Json)) @@ -80,11 +80,11 @@ $Configuration.ApiKey.AUTH_KEY = "YOUR_API_KEY" # Uncomment below to setup prefix (e.g. Bearer) for API key, if needed #$Configuration.ApiKeyPrefix.AUTH_KEY = "Bearer" -$User = @((Initialize-User -Id 123 -Username "Username_example" -FirstName "FirstName_example" -LastName "LastName_example" -Email "Email_example" -Password "Password_example" -Phone "Phone_example" -UserStatus 123)) # User[] | List of user object +$User = Initialize-User -Id 0 -Username "MyUsername" -FirstName "MyFirstName" -LastName "MyLastName" -Email "MyEmail" -Password "MyPassword" -Phone "MyPhone" -UserStatus 0 # User[] | List of user object # Creates list of users with given input array try { - $Result = New-PSUsersWithArrayInput -User $User + $Result = New-PSUsersWithArrayInput -User $User } catch { Write-Host ("Exception occured when calling New-PSUsersWithArrayInput: {0}" -f ($_.ErrorDetails | ConvertFrom-Json)) Write-Host ("Response headers: {0}" -f ($_.Exception.Response.Headers | ConvertTo-Json)) @@ -128,11 +128,11 @@ $Configuration.ApiKey.AUTH_KEY = "YOUR_API_KEY" # Uncomment below to setup prefix (e.g. Bearer) for API key, if needed #$Configuration.ApiKeyPrefix.AUTH_KEY = "Bearer" -$User = @() # User[] | List of user object +$User = Initialize-User -Id 0 -Username "MyUsername" -FirstName "MyFirstName" -LastName "MyLastName" -Email "MyEmail" -Password "MyPassword" -Phone "MyPhone" -UserStatus 0 # User[] | List of user object # Creates list of users with given input array try { - $Result = New-PSUsersWithListInput -User $User + $Result = New-PSUsersWithListInput -User $User } catch { Write-Host ("Exception occured when calling New-PSUsersWithListInput: {0}" -f ($_.ErrorDetails | ConvertFrom-Json)) Write-Host ("Response headers: {0}" -f ($_.Exception.Response.Headers | ConvertTo-Json)) @@ -178,11 +178,11 @@ $Configuration.ApiKey.AUTH_KEY = "YOUR_API_KEY" # Uncomment below to setup prefix (e.g. Bearer) for API key, if needed #$Configuration.ApiKeyPrefix.AUTH_KEY = "Bearer" -$Username = "Username_example" # String | The name that needs to be deleted +$Username = "MyUsername" # String | The name that needs to be deleted # Delete user try { - $Result = Remove-PSUser -Username $Username + $Result = Remove-PSUser -Username $Username } catch { Write-Host ("Exception occured when calling Remove-PSUser: {0}" -f ($_.ErrorDetails | ConvertFrom-Json)) Write-Host ("Response headers: {0}" -f ($_.Exception.Response.Headers | ConvertTo-Json)) @@ -219,11 +219,11 @@ Get user by user name ### Example ```powershell -$Username = "Username_example" # String | The name that needs to be fetched. Use user1 for testing. +$Username = "MyUsername" # String | The name that needs to be fetched. Use user1 for testing. # Get user by user name try { - $Result = Get-PSUserByName -Username $Username + $Result = Get-PSUserByName -Username $Username } catch { Write-Host ("Exception occured when calling Get-PSUserByName: {0}" -f ($_.ErrorDetails | ConvertFrom-Json)) Write-Host ("Response headers: {0}" -f ($_.Exception.Response.Headers | ConvertTo-Json)) @@ -261,12 +261,12 @@ Logs user into the system ### Example ```powershell -$Username = "Username_example" # String | The user name for login -$Password = "Password_example" # String | The password for login in clear text +$Username = "MyUsername" # String | The user name for login +$Password = "MyPassword" # String | The password for login in clear text # Logs user into the system try { - $Result = Invoke-PSLoginUser -Username $Username -Password $Password + $Result = Invoke-PSLoginUser -Username $Username -Password $Password } catch { Write-Host ("Exception occured when calling Invoke-PSLoginUser: {0}" -f ($_.ErrorDetails | ConvertFrom-Json)) Write-Host ("Response headers: {0}" -f ($_.Exception.Response.Headers | ConvertTo-Json)) @@ -313,7 +313,7 @@ $Configuration.ApiKey.AUTH_KEY = "YOUR_API_KEY" # Logs out current logged in user session try { - $Result = Invoke-PSLogoutUser + $Result = Invoke-PSLogoutUser } catch { Write-Host ("Exception occured when calling Invoke-PSLogoutUser: {0}" -f ($_.ErrorDetails | ConvertFrom-Json)) Write-Host ("Response headers: {0}" -f ($_.Exception.Response.Headers | ConvertTo-Json)) @@ -357,12 +357,12 @@ $Configuration.ApiKey.AUTH_KEY = "YOUR_API_KEY" # Uncomment below to setup prefix (e.g. Bearer) for API key, if needed #$Configuration.ApiKeyPrefix.AUTH_KEY = "Bearer" -$Username = "Username_example" # String | name that need to be deleted -$User = # User | Updated user object +$Username = "MyUsername" # String | name that need to be deleted +$User = Initialize-User -Id 0 -Username "MyUsername" -FirstName "MyFirstName" -LastName "MyLastName" -Email "MyEmail" -Password "MyPassword" -Phone "MyPhone" -UserStatus 0 # User | Updated user object # Updated user try { - $Result = Update-PSUser -Username $Username -User $User + $Result = Update-PSUser -Username $Username -User $User } catch { Write-Host ("Exception occured when calling Update-PSUser: {0}" -f ($_.ErrorDetails | ConvertFrom-Json)) Write-Host ("Response headers: {0}" -f ($_.Exception.Response.Headers | ConvertTo-Json)) diff --git a/samples/client/petstore/powershell/src/PSPetstore/Api/PSPetApi.ps1 b/samples/client/petstore/powershell/src/PSPetstore/Api/PSPetApi.ps1 index 4024745d0ca..b6c13d19fb1 100644 --- a/samples/client/petstore/powershell/src/PSPetstore/Api/PSPetApi.ps1 +++ b/samples/client/petstore/powershell/src/PSPetstore/Api/PSPetApi.ps1 @@ -150,7 +150,7 @@ function Remove-Pet { if (!$PetId) { throw "Error! The required parameter `PetId` missing when calling deletePet." } - $LocalVarUri = $LocalVarUri.replace('{petId}', $PetId) + $LocalVarUri = $LocalVarUri.replace('{petId}', [System.Web.HTTPUtility]::UrlEncode($PetId)) if ($ApiKey) { $LocalVarHeaderParameters['api_key'] = $ApiKey @@ -415,7 +415,7 @@ function Get-PSPetById { if (!$PetId) { throw "Error! The required parameter `PetId` missing when calling getPetById." } - $LocalVarUri = $LocalVarUri.replace('{petId}', $PetId) + $LocalVarUri = $LocalVarUri.replace('{petId}', [System.Web.HTTPUtility]::UrlEncode($PetId)) if ($Configuration["ApiKey"] -and $Configuration["ApiKey"]["api_key"]) { $LocalVarHeaderParameters['api_key'] = $Configuration["ApiKey"]["api_key"] @@ -596,7 +596,7 @@ function Update-PSPetWithForm { if (!$PetId) { throw "Error! The required parameter `PetId` missing when calling updatePetWithForm." } - $LocalVarUri = $LocalVarUri.replace('{petId}', $PetId) + $LocalVarUri = $LocalVarUri.replace('{petId}', [System.Web.HTTPUtility]::UrlEncode($PetId)) if ($Name) { $LocalVarFormParameters['name'] = $Name @@ -693,7 +693,7 @@ function Invoke-PSUploadFile { if (!$PetId) { throw "Error! The required parameter `PetId` missing when calling uploadFile." } - $LocalVarUri = $LocalVarUri.replace('{petId}', $PetId) + $LocalVarUri = $LocalVarUri.replace('{petId}', [System.Web.HTTPUtility]::UrlEncode($PetId)) if ($AdditionalMetadata) { $LocalVarFormParameters['additionalMetadata'] = $AdditionalMetadata diff --git a/samples/client/petstore/powershell/src/PSPetstore/Api/PSStoreApi.ps1 b/samples/client/petstore/powershell/src/PSPetstore/Api/PSStoreApi.ps1 index ae56dcdd258..da64d177edd 100644 --- a/samples/client/petstore/powershell/src/PSPetstore/Api/PSStoreApi.ps1 +++ b/samples/client/petstore/powershell/src/PSPetstore/Api/PSStoreApi.ps1 @@ -53,7 +53,7 @@ function Remove-PSOrder { if (!$OrderId) { throw "Error! The required parameter `OrderId` missing when calling deleteOrder." } - $LocalVarUri = $LocalVarUri.replace('{orderId}', $OrderId) + $LocalVarUri = $LocalVarUri.replace('{orderId}', [System.Web.HTTPUtility]::UrlEncode($OrderId)) $LocalVarResult = Invoke-PSApiClient -Method 'DELETE' ` -Uri $LocalVarUri ` @@ -206,7 +206,7 @@ function Get-PSOrderById { if (!$OrderId) { throw "Error! The required parameter `OrderId` missing when calling getOrderById." } - $LocalVarUri = $LocalVarUri.replace('{orderId}', $OrderId) + $LocalVarUri = $LocalVarUri.replace('{orderId}', [System.Web.HTTPUtility]::UrlEncode($OrderId)) $LocalVarResult = Invoke-PSApiClient -Method 'GET' ` -Uri $LocalVarUri ` diff --git a/samples/client/petstore/powershell/src/PSPetstore/Api/PSUserApi.ps1 b/samples/client/petstore/powershell/src/PSPetstore/Api/PSUserApi.ps1 index cbf47aace79..b1bf3241a10 100644 --- a/samples/client/petstore/powershell/src/PSPetstore/Api/PSUserApi.ps1 +++ b/samples/client/petstore/powershell/src/PSPetstore/Api/PSUserApi.ps1 @@ -293,7 +293,7 @@ function Remove-PSUser { if (!$Username) { throw "Error! The required parameter `Username` missing when calling deleteUser." } - $LocalVarUri = $LocalVarUri.replace('{username}', $Username) + $LocalVarUri = $LocalVarUri.replace('{username}', [System.Web.HTTPUtility]::UrlEncode($Username)) if ($Configuration["Cookie"]) { $LocalVarCookieParameters['auth_cookie'] = $Configuration["Cookie"] @@ -383,7 +383,7 @@ function Get-PSUserByName { if (!$Username) { throw "Error! The required parameter `Username` missing when calling getUserByName." } - $LocalVarUri = $LocalVarUri.replace('{username}', $Username) + $LocalVarUri = $LocalVarUri.replace('{username}', [System.Web.HTTPUtility]::UrlEncode($Username)) $LocalVarResult = Invoke-PSApiClient -Method 'GET' ` -Uri $LocalVarUri ` @@ -624,7 +624,7 @@ function Update-PSUser { if (!$Username) { throw "Error! The required parameter `Username` missing when calling updateUser." } - $LocalVarUri = $LocalVarUri.replace('{username}', $Username) + $LocalVarUri = $LocalVarUri.replace('{username}', [System.Web.HTTPUtility]::UrlEncode($Username)) if (!$User) { throw "Error! The required parameter `User` missing when calling updateUser." diff --git a/samples/client/petstore/powershell/src/PSPetstore/Private/PSApiClient.ps1 b/samples/client/petstore/powershell/src/PSPetstore/Private/PSApiClient.ps1 index 9223b3a93e6..09a202cee9d 100644 --- a/samples/client/petstore/powershell/src/PSPetstore/Private/PSApiClient.ps1 +++ b/samples/client/petstore/powershell/src/PSPetstore/Private/PSApiClient.ps1 @@ -198,6 +198,10 @@ function DeserializeResponse { [string[]]$ContentTypes ) + If ($ContentTypes -eq $null) { + $ContentTypes = [string[]]@() + } + If ([string]::IsNullOrEmpty($ReturnType) -and $ContentTypes.Count -eq 0) { # void response return $Response } Elseif ($ReturnType -match '\[\]$') { # array diff --git a/samples/client/petstore/python-asyncio/.openapi-generator/VERSION b/samples/client/petstore/python-asyncio/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/client/petstore/python-asyncio/.openapi-generator/VERSION +++ b/samples/client/petstore/python-asyncio/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/client/petstore/python-legacy/.openapi-generator/VERSION b/samples/client/petstore/python-legacy/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/client/petstore/python-legacy/.openapi-generator/VERSION +++ b/samples/client/petstore/python-legacy/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/client/petstore/python-tornado/.openapi-generator/VERSION b/samples/client/petstore/python-tornado/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/client/petstore/python-tornado/.openapi-generator/VERSION +++ b/samples/client/petstore/python-tornado/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/client/petstore/python/.openapi-generator/VERSION b/samples/client/petstore/python/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/client/petstore/python/.openapi-generator/VERSION +++ b/samples/client/petstore/python/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/client/petstore/python/petstore_api/api/another_fake_api.py b/samples/client/petstore/python/petstore_api/api/another_fake_api.py index 9c75f7d5a83..3a4931f84d4 100644 --- a/samples/client/petstore/python/petstore_api/api/another_fake_api.py +++ b/samples/client/petstore/python/petstore_api/api/another_fake_api.py @@ -59,8 +59,8 @@ class AnotherFakeApi(object): _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. - _request_timeout (float/tuple): timeout setting for this request. If one - number provided, it will be total request timeout. It can also + _request_timeout (int/float/tuple): timeout setting for this request. If + one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking diff --git a/samples/client/petstore/python/petstore_api/api/fake_api.py b/samples/client/petstore/python/petstore_api/api/fake_api.py index aaf44e6f64c..d821febabed 100644 --- a/samples/client/petstore/python/petstore_api/api/fake_api.py +++ b/samples/client/petstore/python/petstore_api/api/fake_api.py @@ -64,8 +64,8 @@ class FakeApi(object): _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. - _request_timeout (float/tuple): timeout setting for this request. If one - number provided, it will be total request timeout. It can also + _request_timeout (int/float/tuple): timeout setting for this request. If + one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking @@ -174,8 +174,8 @@ class FakeApi(object): _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. - _request_timeout (float/tuple): timeout setting for this request. If one - number provided, it will be total request timeout. It can also + _request_timeout (int/float/tuple): timeout setting for this request. If + one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking @@ -286,8 +286,8 @@ class FakeApi(object): _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. - _request_timeout (float/tuple): timeout setting for this request. If one - number provided, it will be total request timeout. It can also + _request_timeout (int/float/tuple): timeout setting for this request. If + one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking @@ -405,8 +405,8 @@ class FakeApi(object): _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. - _request_timeout (float/tuple): timeout setting for this request. If one - number provided, it will be total request timeout. It can also + _request_timeout (int/float/tuple): timeout setting for this request. If + one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking @@ -515,8 +515,8 @@ class FakeApi(object): _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. - _request_timeout (float/tuple): timeout setting for this request. If one - number provided, it will be total request timeout. It can also + _request_timeout (int/float/tuple): timeout setting for this request. If + one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking @@ -625,8 +625,8 @@ class FakeApi(object): _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. - _request_timeout (float/tuple): timeout setting for this request. If one - number provided, it will be total request timeout. It can also + _request_timeout (int/float/tuple): timeout setting for this request. If + one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking @@ -735,8 +735,8 @@ class FakeApi(object): _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. - _request_timeout (float/tuple): timeout setting for this request. If one - number provided, it will be total request timeout. It can also + _request_timeout (int/float/tuple): timeout setting for this request. If + one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking @@ -847,8 +847,8 @@ class FakeApi(object): _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. - _request_timeout (float/tuple): timeout setting for this request. If one - number provided, it will be total request timeout. It can also + _request_timeout (int/float/tuple): timeout setting for this request. If + one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking @@ -964,8 +964,8 @@ class FakeApi(object): _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. - _request_timeout (float/tuple): timeout setting for this request. If one - number provided, it will be total request timeout. It can also + _request_timeout (int/float/tuple): timeout setting for this request. If + one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking @@ -1088,8 +1088,8 @@ class FakeApi(object): _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. - _request_timeout (float/tuple): timeout setting for this request. If one - number provided, it will be total request timeout. It can also + _request_timeout (int/float/tuple): timeout setting for this request. If + one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking @@ -1214,8 +1214,8 @@ class FakeApi(object): _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. - _request_timeout (float/tuple): timeout setting for this request. If one - number provided, it will be total request timeout. It can also + _request_timeout (int/float/tuple): timeout setting for this request. If + one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking @@ -1402,8 +1402,8 @@ class FakeApi(object): _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. - _request_timeout (float/tuple): timeout setting for this request. If one - number provided, it will be total request timeout. It can also + _request_timeout (int/float/tuple): timeout setting for this request. If + one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking @@ -1649,8 +1649,8 @@ class FakeApi(object): _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. - _request_timeout (float/tuple): timeout setting for this request. If one - number provided, it will be total request timeout. It can also + _request_timeout (int/float/tuple): timeout setting for this request. If + one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking @@ -1858,8 +1858,8 @@ class FakeApi(object): _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. - _request_timeout (float/tuple): timeout setting for this request. If one - number provided, it will be total request timeout. It can also + _request_timeout (int/float/tuple): timeout setting for this request. If + one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking @@ -2003,8 +2003,8 @@ class FakeApi(object): _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. - _request_timeout (float/tuple): timeout setting for this request. If one - number provided, it will be total request timeout. It can also + _request_timeout (int/float/tuple): timeout setting for this request. If + one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking @@ -2120,8 +2120,8 @@ class FakeApi(object): _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. - _request_timeout (float/tuple): timeout setting for this request. If one - number provided, it will be total request timeout. It can also + _request_timeout (int/float/tuple): timeout setting for this request. If + one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking diff --git a/samples/client/petstore/python/petstore_api/api/fake_classname_tags_123_api.py b/samples/client/petstore/python/petstore_api/api/fake_classname_tags_123_api.py index 1d1afc214c1..1f8275b9eec 100644 --- a/samples/client/petstore/python/petstore_api/api/fake_classname_tags_123_api.py +++ b/samples/client/petstore/python/petstore_api/api/fake_classname_tags_123_api.py @@ -59,8 +59,8 @@ class FakeClassnameTags123Api(object): _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. - _request_timeout (float/tuple): timeout setting for this request. If one - number provided, it will be total request timeout. It can also + _request_timeout (int/float/tuple): timeout setting for this request. If + one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking diff --git a/samples/client/petstore/python/petstore_api/api/pet_api.py b/samples/client/petstore/python/petstore_api/api/pet_api.py index 2989ca8d4ab..52478be44a1 100644 --- a/samples/client/petstore/python/petstore_api/api/pet_api.py +++ b/samples/client/petstore/python/petstore_api/api/pet_api.py @@ -59,8 +59,8 @@ class PetApi(object): _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. - _request_timeout (float/tuple): timeout setting for this request. If one - number provided, it will be total request timeout. It can also + _request_timeout (int/float/tuple): timeout setting for this request. If + one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking @@ -178,8 +178,8 @@ class PetApi(object): _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. - _request_timeout (float/tuple): timeout setting for this request. If one - number provided, it will be total request timeout. It can also + _request_timeout (int/float/tuple): timeout setting for this request. If + one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking @@ -300,8 +300,8 @@ class PetApi(object): _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. - _request_timeout (float/tuple): timeout setting for this request. If one - number provided, it will be total request timeout. It can also + _request_timeout (int/float/tuple): timeout setting for this request. If + one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking @@ -428,8 +428,8 @@ class PetApi(object): _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. - _request_timeout (float/tuple): timeout setting for this request. If one - number provided, it will be total request timeout. It can also + _request_timeout (int/float/tuple): timeout setting for this request. If + one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking @@ -549,8 +549,8 @@ class PetApi(object): _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. - _request_timeout (float/tuple): timeout setting for this request. If one - number provided, it will be total request timeout. It can also + _request_timeout (int/float/tuple): timeout setting for this request. If + one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking @@ -668,8 +668,8 @@ class PetApi(object): _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. - _request_timeout (float/tuple): timeout setting for this request. If one - number provided, it will be total request timeout. It can also + _request_timeout (int/float/tuple): timeout setting for this request. If + one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking @@ -788,8 +788,8 @@ class PetApi(object): _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. - _request_timeout (float/tuple): timeout setting for this request. If one - number provided, it will be total request timeout. It can also + _request_timeout (int/float/tuple): timeout setting for this request. If + one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking @@ -919,8 +919,8 @@ class PetApi(object): _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. - _request_timeout (float/tuple): timeout setting for this request. If one - number provided, it will be total request timeout. It can also + _request_timeout (int/float/tuple): timeout setting for this request. If + one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking @@ -1058,8 +1058,8 @@ class PetApi(object): _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. - _request_timeout (float/tuple): timeout setting for this request. If one - number provided, it will be total request timeout. It can also + _request_timeout (int/float/tuple): timeout setting for this request. If + one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking diff --git a/samples/client/petstore/python/petstore_api/api/store_api.py b/samples/client/petstore/python/petstore_api/api/store_api.py index c30ca943b2d..81f1779174b 100644 --- a/samples/client/petstore/python/petstore_api/api/store_api.py +++ b/samples/client/petstore/python/petstore_api/api/store_api.py @@ -59,8 +59,8 @@ class StoreApi(object): _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. - _request_timeout (float/tuple): timeout setting for this request. If one - number provided, it will be total request timeout. It can also + _request_timeout (int/float/tuple): timeout setting for this request. If + one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking @@ -171,8 +171,8 @@ class StoreApi(object): _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. - _request_timeout (float/tuple): timeout setting for this request. If one - number provided, it will be total request timeout. It can also + _request_timeout (int/float/tuple): timeout setting for this request. If + one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking @@ -281,8 +281,8 @@ class StoreApi(object): _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. - _request_timeout (float/tuple): timeout setting for this request. If one - number provided, it will be total request timeout. It can also + _request_timeout (int/float/tuple): timeout setting for this request. If + one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking @@ -404,8 +404,8 @@ class StoreApi(object): _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. - _request_timeout (float/tuple): timeout setting for this request. If one - number provided, it will be total request timeout. It can also + _request_timeout (int/float/tuple): timeout setting for this request. If + one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking diff --git a/samples/client/petstore/python/petstore_api/api/user_api.py b/samples/client/petstore/python/petstore_api/api/user_api.py index a5ef0d5c309..931b31d5ef8 100644 --- a/samples/client/petstore/python/petstore_api/api/user_api.py +++ b/samples/client/petstore/python/petstore_api/api/user_api.py @@ -59,8 +59,8 @@ class UserApi(object): _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. - _request_timeout (float/tuple): timeout setting for this request. If one - number provided, it will be total request timeout. It can also + _request_timeout (int/float/tuple): timeout setting for this request. If + one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking @@ -172,8 +172,8 @@ class UserApi(object): _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. - _request_timeout (float/tuple): timeout setting for this request. If one - number provided, it will be total request timeout. It can also + _request_timeout (int/float/tuple): timeout setting for this request. If + one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking @@ -285,8 +285,8 @@ class UserApi(object): _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. - _request_timeout (float/tuple): timeout setting for this request. If one - number provided, it will be total request timeout. It can also + _request_timeout (int/float/tuple): timeout setting for this request. If + one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking @@ -399,8 +399,8 @@ class UserApi(object): _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. - _request_timeout (float/tuple): timeout setting for this request. If one - number provided, it will be total request timeout. It can also + _request_timeout (int/float/tuple): timeout setting for this request. If + one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking @@ -513,8 +513,8 @@ class UserApi(object): _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. - _request_timeout (float/tuple): timeout setting for this request. If one - number provided, it will be total request timeout. It can also + _request_timeout (int/float/tuple): timeout setting for this request. If + one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking @@ -632,8 +632,8 @@ class UserApi(object): _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. - _request_timeout (float/tuple): timeout setting for this request. If one - number provided, it will be total request timeout. It can also + _request_timeout (int/float/tuple): timeout setting for this request. If + one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking @@ -754,8 +754,8 @@ class UserApi(object): _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. - _request_timeout (float/tuple): timeout setting for this request. If one - number provided, it will be total request timeout. It can also + _request_timeout (int/float/tuple): timeout setting for this request. If + one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking @@ -862,8 +862,8 @@ class UserApi(object): _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. - _request_timeout (float/tuple): timeout setting for this request. If one - number provided, it will be total request timeout. It can also + _request_timeout (int/float/tuple): timeout setting for this request. If + one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking diff --git a/samples/client/petstore/python/petstore_api/api_client.py b/samples/client/petstore/python/petstore_api/api_client.py index a43e4ace242..9b8ea1d5d1a 100644 --- a/samples/client/petstore/python/petstore_api/api_client.py +++ b/samples/client/petstore/python/petstore_api/api_client.py @@ -129,7 +129,7 @@ class ApiClient(object): _return_http_data_only: typing.Optional[bool] = None, collection_formats: typing.Optional[typing.Dict[str, str]] = None, _preload_content: bool = True, - _request_timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + _request_timeout: typing.Optional[typing.Union[int, float, typing.Tuple]] = None, _host: typing.Optional[str] = None, _check_type: typing.Optional[bool] = None ): @@ -347,7 +347,7 @@ class ApiClient(object): _return_http_data_only: typing.Optional[bool] = None, collection_formats: typing.Optional[typing.Dict[str, str]] = None, _preload_content: bool = True, - _request_timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + _request_timeout: typing.Optional[typing.Union[int, float, typing.Tuple]] = None, _host: typing.Optional[str] = None, _check_type: typing.Optional[bool] = None ): @@ -674,7 +674,7 @@ class Endpoint(object): 'async_req': (bool,), '_host_index': (none_type, int), '_preload_content': (bool,), - '_request_timeout': (none_type, int, (int,), [int]), + '_request_timeout': (none_type, float, (float,), [float], int, (int,), [int]), '_return_http_data_only': (bool,), '_check_input_type': (bool,), '_check_return_type': (bool,) diff --git a/samples/client/petstore/python/petstore_api/model_utils.py b/samples/client/petstore/python/petstore_api/model_utils.py index 3913228d6b8..aa747a3f9a8 100644 --- a/samples/client/petstore/python/petstore_api/model_utils.py +++ b/samples/client/petstore/python/petstore_api/model_utils.py @@ -47,7 +47,7 @@ def convert_js_args_to_python_args(fn): class cached_property(object): # this caches the result of the function call for fn with no inputs - # use this as a decorator on fuction methods that you want converted + # use this as a decorator on function methods that you want converted # into cached properties result_key = '_results' @@ -1632,12 +1632,20 @@ def model_to_dict(model_instance, serialize=True): model_instances = [model_instance] if model_instance._composed_schemas: model_instances.extend(model_instance._composed_instances) + seen_json_attribute_names = set() + used_fallback_python_attribute_names = set() + py_to_json_map = {} for model_instance in model_instances: for attr, value in model_instance._data_store.items(): if serialize: # we use get here because additional property key names do not # exist in attribute_map - attr = model_instance.attribute_map.get(attr, attr) + try: + attr = model_instance.attribute_map[attr] + py_to_json_map.update(model_instance.attribute_map) + seen_json_attribute_names.add(attr) + except KeyError: + used_fallback_python_attribute_names.add(attr) if isinstance(value, list): if not value: # empty list or None @@ -1665,6 +1673,16 @@ def model_to_dict(model_instance, serialize=True): result[attr] = model_to_dict(value, serialize=serialize) else: result[attr] = value + if serialize: + for python_key in used_fallback_python_attribute_names: + json_key = py_to_json_map.get(python_key) + if json_key is None: + continue + if python_key == json_key: + continue + json_key_assigned_no_need_for_python_key = json_key in seen_json_attribute_names + if json_key_assigned_no_need_for_python_key: + del result[python_key] return result diff --git a/samples/client/petstore/python/petstore_api/rest.py b/samples/client/petstore/python/petstore_api/rest.py index a1d580fbe05..a38fcec1c84 100644 --- a/samples/client/petstore/python/petstore_api/rest.py +++ b/samples/client/petstore/python/petstore_api/rest.py @@ -137,15 +137,15 @@ class RESTClientObject(object): timeout = urllib3.Timeout( connect=_request_timeout[0], read=_request_timeout[1]) - if 'Content-Type' not in headers: - headers['Content-Type'] = 'application/json' - try: # For `POST`, `PUT`, `PATCH`, `OPTIONS`, `DELETE` if method in ['POST', 'PUT', 'PATCH', 'OPTIONS', 'DELETE']: + # Only set a default Content-Type for POST, PUT, PATCH and OPTIONS requests + if (method != 'DELETE') and ('Content-Type' not in headers): + headers['Content-Type'] = 'application/json' if query_params: url += '?' + urlencode(query_params) - if re.search('json', headers['Content-Type'], re.IGNORECASE): + if ('Content-Type' not in headers) or (re.search('json', headers['Content-Type'], re.IGNORECASE)): request_body = None if body is not None: request_body = json.dumps(body) diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/.openapi-generator/VERSION b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/.openapi-generator/VERSION +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/api/another_fake_api.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/api/another_fake_api.py index 9c75f7d5a83..3a4931f84d4 100644 --- a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/api/another_fake_api.py +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/api/another_fake_api.py @@ -59,8 +59,8 @@ class AnotherFakeApi(object): _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. - _request_timeout (float/tuple): timeout setting for this request. If one - number provided, it will be total request timeout. It can also + _request_timeout (int/float/tuple): timeout setting for this request. If + one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/api/fake_api.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/api/fake_api.py index aaf44e6f64c..d821febabed 100644 --- a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/api/fake_api.py +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/api/fake_api.py @@ -64,8 +64,8 @@ class FakeApi(object): _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. - _request_timeout (float/tuple): timeout setting for this request. If one - number provided, it will be total request timeout. It can also + _request_timeout (int/float/tuple): timeout setting for this request. If + one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking @@ -174,8 +174,8 @@ class FakeApi(object): _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. - _request_timeout (float/tuple): timeout setting for this request. If one - number provided, it will be total request timeout. It can also + _request_timeout (int/float/tuple): timeout setting for this request. If + one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking @@ -286,8 +286,8 @@ class FakeApi(object): _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. - _request_timeout (float/tuple): timeout setting for this request. If one - number provided, it will be total request timeout. It can also + _request_timeout (int/float/tuple): timeout setting for this request. If + one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking @@ -405,8 +405,8 @@ class FakeApi(object): _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. - _request_timeout (float/tuple): timeout setting for this request. If one - number provided, it will be total request timeout. It can also + _request_timeout (int/float/tuple): timeout setting for this request. If + one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking @@ -515,8 +515,8 @@ class FakeApi(object): _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. - _request_timeout (float/tuple): timeout setting for this request. If one - number provided, it will be total request timeout. It can also + _request_timeout (int/float/tuple): timeout setting for this request. If + one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking @@ -625,8 +625,8 @@ class FakeApi(object): _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. - _request_timeout (float/tuple): timeout setting for this request. If one - number provided, it will be total request timeout. It can also + _request_timeout (int/float/tuple): timeout setting for this request. If + one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking @@ -735,8 +735,8 @@ class FakeApi(object): _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. - _request_timeout (float/tuple): timeout setting for this request. If one - number provided, it will be total request timeout. It can also + _request_timeout (int/float/tuple): timeout setting for this request. If + one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking @@ -847,8 +847,8 @@ class FakeApi(object): _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. - _request_timeout (float/tuple): timeout setting for this request. If one - number provided, it will be total request timeout. It can also + _request_timeout (int/float/tuple): timeout setting for this request. If + one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking @@ -964,8 +964,8 @@ class FakeApi(object): _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. - _request_timeout (float/tuple): timeout setting for this request. If one - number provided, it will be total request timeout. It can also + _request_timeout (int/float/tuple): timeout setting for this request. If + one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking @@ -1088,8 +1088,8 @@ class FakeApi(object): _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. - _request_timeout (float/tuple): timeout setting for this request. If one - number provided, it will be total request timeout. It can also + _request_timeout (int/float/tuple): timeout setting for this request. If + one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking @@ -1214,8 +1214,8 @@ class FakeApi(object): _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. - _request_timeout (float/tuple): timeout setting for this request. If one - number provided, it will be total request timeout. It can also + _request_timeout (int/float/tuple): timeout setting for this request. If + one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking @@ -1402,8 +1402,8 @@ class FakeApi(object): _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. - _request_timeout (float/tuple): timeout setting for this request. If one - number provided, it will be total request timeout. It can also + _request_timeout (int/float/tuple): timeout setting for this request. If + one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking @@ -1649,8 +1649,8 @@ class FakeApi(object): _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. - _request_timeout (float/tuple): timeout setting for this request. If one - number provided, it will be total request timeout. It can also + _request_timeout (int/float/tuple): timeout setting for this request. If + one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking @@ -1858,8 +1858,8 @@ class FakeApi(object): _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. - _request_timeout (float/tuple): timeout setting for this request. If one - number provided, it will be total request timeout. It can also + _request_timeout (int/float/tuple): timeout setting for this request. If + one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking @@ -2003,8 +2003,8 @@ class FakeApi(object): _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. - _request_timeout (float/tuple): timeout setting for this request. If one - number provided, it will be total request timeout. It can also + _request_timeout (int/float/tuple): timeout setting for this request. If + one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking @@ -2120,8 +2120,8 @@ class FakeApi(object): _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. - _request_timeout (float/tuple): timeout setting for this request. If one - number provided, it will be total request timeout. It can also + _request_timeout (int/float/tuple): timeout setting for this request. If + one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/api/fake_classname_tags_123_api.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/api/fake_classname_tags_123_api.py index 1d1afc214c1..1f8275b9eec 100644 --- a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/api/fake_classname_tags_123_api.py +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/api/fake_classname_tags_123_api.py @@ -59,8 +59,8 @@ class FakeClassnameTags123Api(object): _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. - _request_timeout (float/tuple): timeout setting for this request. If one - number provided, it will be total request timeout. It can also + _request_timeout (int/float/tuple): timeout setting for this request. If + one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/api/pet_api.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/api/pet_api.py index 2989ca8d4ab..52478be44a1 100644 --- a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/api/pet_api.py +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/api/pet_api.py @@ -59,8 +59,8 @@ class PetApi(object): _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. - _request_timeout (float/tuple): timeout setting for this request. If one - number provided, it will be total request timeout. It can also + _request_timeout (int/float/tuple): timeout setting for this request. If + one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking @@ -178,8 +178,8 @@ class PetApi(object): _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. - _request_timeout (float/tuple): timeout setting for this request. If one - number provided, it will be total request timeout. It can also + _request_timeout (int/float/tuple): timeout setting for this request. If + one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking @@ -300,8 +300,8 @@ class PetApi(object): _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. - _request_timeout (float/tuple): timeout setting for this request. If one - number provided, it will be total request timeout. It can also + _request_timeout (int/float/tuple): timeout setting for this request. If + one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking @@ -428,8 +428,8 @@ class PetApi(object): _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. - _request_timeout (float/tuple): timeout setting for this request. If one - number provided, it will be total request timeout. It can also + _request_timeout (int/float/tuple): timeout setting for this request. If + one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking @@ -549,8 +549,8 @@ class PetApi(object): _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. - _request_timeout (float/tuple): timeout setting for this request. If one - number provided, it will be total request timeout. It can also + _request_timeout (int/float/tuple): timeout setting for this request. If + one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking @@ -668,8 +668,8 @@ class PetApi(object): _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. - _request_timeout (float/tuple): timeout setting for this request. If one - number provided, it will be total request timeout. It can also + _request_timeout (int/float/tuple): timeout setting for this request. If + one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking @@ -788,8 +788,8 @@ class PetApi(object): _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. - _request_timeout (float/tuple): timeout setting for this request. If one - number provided, it will be total request timeout. It can also + _request_timeout (int/float/tuple): timeout setting for this request. If + one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking @@ -919,8 +919,8 @@ class PetApi(object): _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. - _request_timeout (float/tuple): timeout setting for this request. If one - number provided, it will be total request timeout. It can also + _request_timeout (int/float/tuple): timeout setting for this request. If + one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking @@ -1058,8 +1058,8 @@ class PetApi(object): _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. - _request_timeout (float/tuple): timeout setting for this request. If one - number provided, it will be total request timeout. It can also + _request_timeout (int/float/tuple): timeout setting for this request. If + one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/api/store_api.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/api/store_api.py index c30ca943b2d..81f1779174b 100644 --- a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/api/store_api.py +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/api/store_api.py @@ -59,8 +59,8 @@ class StoreApi(object): _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. - _request_timeout (float/tuple): timeout setting for this request. If one - number provided, it will be total request timeout. It can also + _request_timeout (int/float/tuple): timeout setting for this request. If + one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking @@ -171,8 +171,8 @@ class StoreApi(object): _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. - _request_timeout (float/tuple): timeout setting for this request. If one - number provided, it will be total request timeout. It can also + _request_timeout (int/float/tuple): timeout setting for this request. If + one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking @@ -281,8 +281,8 @@ class StoreApi(object): _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. - _request_timeout (float/tuple): timeout setting for this request. If one - number provided, it will be total request timeout. It can also + _request_timeout (int/float/tuple): timeout setting for this request. If + one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking @@ -404,8 +404,8 @@ class StoreApi(object): _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. - _request_timeout (float/tuple): timeout setting for this request. If one - number provided, it will be total request timeout. It can also + _request_timeout (int/float/tuple): timeout setting for this request. If + one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/api/user_api.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/api/user_api.py index a5ef0d5c309..931b31d5ef8 100644 --- a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/api/user_api.py +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/api/user_api.py @@ -59,8 +59,8 @@ class UserApi(object): _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. - _request_timeout (float/tuple): timeout setting for this request. If one - number provided, it will be total request timeout. It can also + _request_timeout (int/float/tuple): timeout setting for this request. If + one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking @@ -172,8 +172,8 @@ class UserApi(object): _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. - _request_timeout (float/tuple): timeout setting for this request. If one - number provided, it will be total request timeout. It can also + _request_timeout (int/float/tuple): timeout setting for this request. If + one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking @@ -285,8 +285,8 @@ class UserApi(object): _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. - _request_timeout (float/tuple): timeout setting for this request. If one - number provided, it will be total request timeout. It can also + _request_timeout (int/float/tuple): timeout setting for this request. If + one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking @@ -399,8 +399,8 @@ class UserApi(object): _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. - _request_timeout (float/tuple): timeout setting for this request. If one - number provided, it will be total request timeout. It can also + _request_timeout (int/float/tuple): timeout setting for this request. If + one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking @@ -513,8 +513,8 @@ class UserApi(object): _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. - _request_timeout (float/tuple): timeout setting for this request. If one - number provided, it will be total request timeout. It can also + _request_timeout (int/float/tuple): timeout setting for this request. If + one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking @@ -632,8 +632,8 @@ class UserApi(object): _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. - _request_timeout (float/tuple): timeout setting for this request. If one - number provided, it will be total request timeout. It can also + _request_timeout (int/float/tuple): timeout setting for this request. If + one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking @@ -754,8 +754,8 @@ class UserApi(object): _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. - _request_timeout (float/tuple): timeout setting for this request. If one - number provided, it will be total request timeout. It can also + _request_timeout (int/float/tuple): timeout setting for this request. If + one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking @@ -862,8 +862,8 @@ class UserApi(object): _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. - _request_timeout (float/tuple): timeout setting for this request. If one - number provided, it will be total request timeout. It can also + _request_timeout (int/float/tuple): timeout setting for this request. If + one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/api_client.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/api_client.py index a43e4ace242..9b8ea1d5d1a 100644 --- a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/api_client.py +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/api_client.py @@ -129,7 +129,7 @@ class ApiClient(object): _return_http_data_only: typing.Optional[bool] = None, collection_formats: typing.Optional[typing.Dict[str, str]] = None, _preload_content: bool = True, - _request_timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + _request_timeout: typing.Optional[typing.Union[int, float, typing.Tuple]] = None, _host: typing.Optional[str] = None, _check_type: typing.Optional[bool] = None ): @@ -347,7 +347,7 @@ class ApiClient(object): _return_http_data_only: typing.Optional[bool] = None, collection_formats: typing.Optional[typing.Dict[str, str]] = None, _preload_content: bool = True, - _request_timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + _request_timeout: typing.Optional[typing.Union[int, float, typing.Tuple]] = None, _host: typing.Optional[str] = None, _check_type: typing.Optional[bool] = None ): @@ -674,7 +674,7 @@ class Endpoint(object): 'async_req': (bool,), '_host_index': (none_type, int), '_preload_content': (bool,), - '_request_timeout': (none_type, int, (int,), [int]), + '_request_timeout': (none_type, float, (float,), [float], int, (int,), [int]), '_return_http_data_only': (bool,), '_check_input_type': (bool,), '_check_return_type': (bool,) diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model_utils.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model_utils.py index 3913228d6b8..aa747a3f9a8 100644 --- a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model_utils.py +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model_utils.py @@ -47,7 +47,7 @@ def convert_js_args_to_python_args(fn): class cached_property(object): # this caches the result of the function call for fn with no inputs - # use this as a decorator on fuction methods that you want converted + # use this as a decorator on function methods that you want converted # into cached properties result_key = '_results' @@ -1632,12 +1632,20 @@ def model_to_dict(model_instance, serialize=True): model_instances = [model_instance] if model_instance._composed_schemas: model_instances.extend(model_instance._composed_instances) + seen_json_attribute_names = set() + used_fallback_python_attribute_names = set() + py_to_json_map = {} for model_instance in model_instances: for attr, value in model_instance._data_store.items(): if serialize: # we use get here because additional property key names do not # exist in attribute_map - attr = model_instance.attribute_map.get(attr, attr) + try: + attr = model_instance.attribute_map[attr] + py_to_json_map.update(model_instance.attribute_map) + seen_json_attribute_names.add(attr) + except KeyError: + used_fallback_python_attribute_names.add(attr) if isinstance(value, list): if not value: # empty list or None @@ -1665,6 +1673,16 @@ def model_to_dict(model_instance, serialize=True): result[attr] = model_to_dict(value, serialize=serialize) else: result[attr] = value + if serialize: + for python_key in used_fallback_python_attribute_names: + json_key = py_to_json_map.get(python_key) + if json_key is None: + continue + if python_key == json_key: + continue + json_key_assigned_no_need_for_python_key = json_key in seen_json_attribute_names + if json_key_assigned_no_need_for_python_key: + del result[python_key] return result diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/rest.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/rest.py index a1d580fbe05..a38fcec1c84 100644 --- a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/rest.py +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/rest.py @@ -137,15 +137,15 @@ class RESTClientObject(object): timeout = urllib3.Timeout( connect=_request_timeout[0], read=_request_timeout[1]) - if 'Content-Type' not in headers: - headers['Content-Type'] = 'application/json' - try: # For `POST`, `PUT`, `PATCH`, `OPTIONS`, `DELETE` if method in ['POST', 'PUT', 'PATCH', 'OPTIONS', 'DELETE']: + # Only set a default Content-Type for POST, PUT, PATCH and OPTIONS requests + if (method != 'DELETE') and ('Content-Type' not in headers): + headers['Content-Type'] = 'application/json' if query_params: url += '?' + urlencode(query_params) - if re.search('json', headers['Content-Type'], re.IGNORECASE): + if ('Content-Type' not in headers) or (re.search('json', headers['Content-Type'], re.IGNORECASE)): request_body = None if body is not None: request_body = json.dumps(body) diff --git a/samples/client/petstore/ruby-faraday/.openapi-generator/VERSION b/samples/client/petstore/ruby-faraday/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/client/petstore/ruby-faraday/.openapi-generator/VERSION +++ b/samples/client/petstore/ruby-faraday/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/client/petstore/ruby-faraday/README.md b/samples/client/petstore/ruby-faraday/README.md index f7d8816e8ca..e4cc57adb51 100644 --- a/samples/client/petstore/ruby-faraday/README.md +++ b/samples/client/petstore/ruby-faraday/README.md @@ -84,6 +84,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_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 | *Petstore::FakeApi* | [**test_client_model**](docs/FakeApi.md#test_client_model) | **PATCH** /fake | To test \"client\" model diff --git a/samples/client/petstore/ruby-faraday/docs/FakeApi.md b/samples/client/petstore/ruby-faraday/docs/FakeApi.md index ce74242565c..696f5ff4820 100644 --- a/samples/client/petstore/ruby-faraday/docs/FakeApi.md +++ b/samples/client/petstore/ruby-faraday/docs/FakeApi.md @@ -11,6 +11,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_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 | @@ -479,13 +480,76 @@ No authorization required - **Accept**: */* +## test_body_with_binary + +> test_body_with_binary(body) + + + +For this test, the body has to be a binary file. + +### Examples + +```ruby +require 'time' +require 'petstore' + +api_instance = Petstore::FakeApi.new +body = File.new('/path/to/some/file') # File | image to upload + +begin + + api_instance.test_body_with_binary(body) +rescue Petstore::ApiError => e + puts "Error when calling FakeApi->test_body_with_binary: #{e}" +end +``` + +#### Using the test_body_with_binary_with_http_info variant + +This returns an Array which contains the response data (`nil` in this case), status code and headers. + +> test_body_with_binary_with_http_info(body) + +```ruby +begin + + data, status_code, headers = api_instance.test_body_with_binary_with_http_info(body) + p status_code # => 2xx + p headers # => { ... } + p data # => nil +rescue Petstore::ApiError => e + puts "Error when calling FakeApi->test_body_with_binary_with_http_info: #{e}" +end +``` + +### Parameters + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **body** | **File** | image to upload | | + +### Return type + +nil (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: image/png +- **Accept**: Not defined + + ## test_body_with_file_schema > test_body_with_file_schema(file_schema_test_class) -For this test, the body for this request much reference a schema named `File`. +For this test, the body for this request must reference a schema named `File`. ### Examples diff --git a/samples/client/petstore/ruby-faraday/lib/petstore.rb b/samples/client/petstore/ruby-faraday/lib/petstore.rb index 1c0389beacd..df4c5ad38e7 100644 --- a/samples/client/petstore/ruby-faraday/lib/petstore.rb +++ b/samples/client/petstore/ruby-faraday/lib/petstore.rb @@ -6,7 +6,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =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 1b9b1297272..3a1ebebc3df 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,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =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 2d2b7da307e..c7faf16f2af 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,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =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 3c933b61a83..6b23171fd35 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,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =end @@ -440,7 +444,64 @@ module Petstore return data, status_code, headers end - # For this test, the body for this request much reference a schema named `File`. + # For this test, the body has to be a binary file. + # @param body [File] image to upload + # @param [Hash] opts the optional parameters + # @return [nil] + def test_body_with_binary(body, opts = {}) + test_body_with_binary_with_http_info(body, opts) + nil + end + + # For this test, the body has to be a binary file. + # @param body [File] image to upload + # @param [Hash] opts the optional parameters + # @return [Array<(nil, Integer, Hash)>] nil, response status code and response headers + def test_body_with_binary_with_http_info(body, opts = {}) + if @api_client.config.debugging + @api_client.config.logger.debug 'Calling API: FakeApi.test_body_with_binary ...' + end + # resource path + local_var_path = '/fake/body-with-binary' + + # query parameters + query_params = opts[:query_params] || {} + + # header parameters + header_params = opts[:header_params] || {} + # HTTP header 'Content-Type' + header_params['Content-Type'] = @api_client.select_header_content_type(['image/png']) + + # form parameters + form_params = opts[:form_params] || {} + + # http body (model) + post_body = opts[:debug_body] || @api_client.object_to_http_body(body) + + # return_type + return_type = opts[:debug_return_type] + + # auth_names + auth_names = opts[:debug_auth_names] || [] + + new_options = opts.merge( + :operation => :"FakeApi.test_body_with_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(:PUT, local_var_path, new_options) + if @api_client.config.debugging + @api_client.config.logger.debug "API called: FakeApi#test_body_with_binary\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" + end + return data, status_code, headers + end + + # For this test, the body for this request must reference a schema named `File`. # @param file_schema_test_class [FileSchemaTestClass] # @param [Hash] opts the optional parameters # @return [nil] @@ -449,7 +510,7 @@ module Petstore nil end - # For this test, the body for this request much reference a schema named `File`. + # For this test, the body for this request must reference a schema named `File`. # @param file_schema_test_class [FileSchemaTestClass] # @param [Hash] opts the optional parameters # @return [Array<(nil, Integer, Hash)>] nil, response status code and response headers @@ -1179,7 +1240,7 @@ module Petstore # query parameters query_params = opts[:query_params] || {} - query_params[:'pipe'] = @api_client.build_collection_param(pipe, :multi) + query_params[:'pipe'] = @api_client.build_collection_param(pipe, :pipes) query_params[:'ioutil'] = @api_client.build_collection_param(ioutil, :csv) query_params[:'http'] = @api_client.build_collection_param(http, :ssv) query_params[:'url'] = @api_client.build_collection_param(url, :csv) 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 a0f686867d9..da10052dd2a 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,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =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 26394638556..9915beefb23 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,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =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 f462790c3f3..255fa743e75 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,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =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 b6827f6fc5c..d0d07779c90 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,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =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 59c530b18c6..cc95a404d69 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,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =end 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 85b3bd9da06..37f6d8fc29f 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,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =end diff --git a/samples/client/petstore/ruby-faraday/lib/petstore/configuration.rb b/samples/client/petstore/ruby-faraday/lib/petstore/configuration.rb index e90211cfa17..b892a310af0 100644 --- a/samples/client/petstore/ruby-faraday/lib/petstore/configuration.rb +++ b/samples/client/petstore/ruby-faraday/lib/petstore/configuration.rb @@ -6,7 +6,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =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 ef7cdf93d9d..6d5e77e7d75 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,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =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 7e22de93da5..be16e3cf5f4 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,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =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 031565289a0..c20d63af0e4 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,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =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 659e25306ce..cf2dbfc8751 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,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =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 c495716c118..3162510675f 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,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =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 c6ec6c1a90f..5cee2b93325 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,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =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 a89f9693501..e17c007ec1b 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,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =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 57cfa8343d0..37f256a4c8a 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,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =end diff --git a/samples/client/petstore/ruby-faraday/lib/petstore/models/cat_all_of.rb b/samples/client/petstore/ruby-faraday/lib/petstore/models/cat_all_of.rb index 10be8ec0a08..b440220a2ed 100644 --- a/samples/client/petstore/ruby-faraday/lib/petstore/models/cat_all_of.rb +++ b/samples/client/petstore/ruby-faraday/lib/petstore/models/cat_all_of.rb @@ -6,7 +6,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =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 ea966f177bc..7a49cdcda2f 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,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =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 b73022da326..fb821398573 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,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =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 e874ebe700f..36d48682205 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,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =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 7d692a46b61..9787bc82bcf 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,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =end diff --git a/samples/client/petstore/ruby-faraday/lib/petstore/models/dog_all_of.rb b/samples/client/petstore/ruby-faraday/lib/petstore/models/dog_all_of.rb index 7e9649319fb..646d4b556d1 100644 --- a/samples/client/petstore/ruby-faraday/lib/petstore/models/dog_all_of.rb +++ b/samples/client/petstore/ruby-faraday/lib/petstore/models/dog_all_of.rb @@ -6,7 +6,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =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 23580e86e68..c19bc78f979 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,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =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 9913a456cdc..d1d43400c59 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,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =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 a972cfdb885..7ed6d4b365b 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,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =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 adbf1b36756..856ec3e41ea 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,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =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 b99cf2a5305..235390c32da 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,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =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 9361c7a52d3..1727a09fdaa 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,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =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 78da1ead1f8..32adcdca86f 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,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =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 121251962cb..90c0ce27f0b 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,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =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 1d3d86c5496..5d81c3a4a70 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,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =end diff --git a/samples/client/petstore/ruby-faraday/lib/petstore/models/inline_response_default.rb b/samples/client/petstore/ruby-faraday/lib/petstore/models/inline_response_default.rb index 605524a3dcd..589ec6fd11c 100644 --- a/samples/client/petstore/ruby-faraday/lib/petstore/models/inline_response_default.rb +++ b/samples/client/petstore/ruby-faraday/lib/petstore/models/inline_response_default.rb @@ -6,7 +6,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =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 86bd8d8cc3f..ec03a9ba040 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,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =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 1c7c233056a..415b006f7ab 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,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =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 ba61734af03..ad0a4256f38 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,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =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 813d434348e..ebe17766a37 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,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =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 9b6cb8a8174..00e71d0b805 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,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =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 26019385252..c5dcdb3c6af 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,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =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 b33d22daadb..ca9ec495b5b 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,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =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 28148b31886..48b8d2d279f 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,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =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 374e7e85aff..40b0a9bffd9 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,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =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 e0776697e63..68e655cfb1f 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,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =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 91902de42c8..e6b496b2bf9 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,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =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 78ea4449368..915f78a0f66 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,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =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 ed9af6f2c46..9a9c9a03694 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,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =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 f6a263dfe9d..334b0598136 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,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =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 a304dc9b46c..f5ff813d2b0 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,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =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 68c3343d1d3..35cbe40f430 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,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =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 6c18c4ea29c..de94c54c4ef 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,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =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 a2e8925d2ce..6adc47d9b5a 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,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =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 a9958f7d213..a90d22c5ff1 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,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =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 f59454450b2..b08062f32db 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,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =end diff --git a/samples/client/petstore/ruby-faraday/lib/petstore/version.rb b/samples/client/petstore/ruby-faraday/lib/petstore/version.rb index 59c7e87806f..460e6134857 100644 --- a/samples/client/petstore/ruby-faraday/lib/petstore/version.rb +++ b/samples/client/petstore/ruby-faraday/lib/petstore/version.rb @@ -6,7 +6,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =end diff --git a/samples/client/petstore/ruby-faraday/petstore.gemspec b/samples/client/petstore/ruby-faraday/petstore.gemspec index 814f96b310d..1e38980d8c4 100644 --- a/samples/client/petstore/ruby-faraday/petstore.gemspec +++ b/samples/client/petstore/ruby-faraday/petstore.gemspec @@ -8,7 +8,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =end 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 bfc71e43597..7183b5e9bab 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,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =end diff --git a/samples/client/petstore/ruby-faraday/spec/configuration_spec.rb b/samples/client/petstore/ruby-faraday/spec/configuration_spec.rb index 785eebfe6d6..b76b6cbee30 100644 --- a/samples/client/petstore/ruby-faraday/spec/configuration_spec.rb +++ b/samples/client/petstore/ruby-faraday/spec/configuration_spec.rb @@ -6,7 +6,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =end diff --git a/samples/client/petstore/ruby-faraday/spec/spec_helper.rb b/samples/client/petstore/ruby-faraday/spec/spec_helper.rb index d4a79a9a5be..f85cbfd7373 100644 --- a/samples/client/petstore/ruby-faraday/spec/spec_helper.rb +++ b/samples/client/petstore/ruby-faraday/spec/spec_helper.rb @@ -6,7 +6,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =end diff --git a/samples/client/petstore/ruby/.openapi-generator/VERSION b/samples/client/petstore/ruby/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/client/petstore/ruby/.openapi-generator/VERSION +++ b/samples/client/petstore/ruby/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/client/petstore/ruby/README.md b/samples/client/petstore/ruby/README.md index f7d8816e8ca..e4cc57adb51 100644 --- a/samples/client/petstore/ruby/README.md +++ b/samples/client/petstore/ruby/README.md @@ -84,6 +84,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_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 | *Petstore::FakeApi* | [**test_client_model**](docs/FakeApi.md#test_client_model) | **PATCH** /fake | To test \"client\" model diff --git a/samples/client/petstore/ruby/docs/FakeApi.md b/samples/client/petstore/ruby/docs/FakeApi.md index ce74242565c..696f5ff4820 100644 --- a/samples/client/petstore/ruby/docs/FakeApi.md +++ b/samples/client/petstore/ruby/docs/FakeApi.md @@ -11,6 +11,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_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 | @@ -479,13 +480,76 @@ No authorization required - **Accept**: */* +## test_body_with_binary + +> test_body_with_binary(body) + + + +For this test, the body has to be a binary file. + +### Examples + +```ruby +require 'time' +require 'petstore' + +api_instance = Petstore::FakeApi.new +body = File.new('/path/to/some/file') # File | image to upload + +begin + + api_instance.test_body_with_binary(body) +rescue Petstore::ApiError => e + puts "Error when calling FakeApi->test_body_with_binary: #{e}" +end +``` + +#### Using the test_body_with_binary_with_http_info variant + +This returns an Array which contains the response data (`nil` in this case), status code and headers. + +> test_body_with_binary_with_http_info(body) + +```ruby +begin + + data, status_code, headers = api_instance.test_body_with_binary_with_http_info(body) + p status_code # => 2xx + p headers # => { ... } + p data # => nil +rescue Petstore::ApiError => e + puts "Error when calling FakeApi->test_body_with_binary_with_http_info: #{e}" +end +``` + +### Parameters + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **body** | **File** | image to upload | | + +### Return type + +nil (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: image/png +- **Accept**: Not defined + + ## test_body_with_file_schema > test_body_with_file_schema(file_schema_test_class) -For this test, the body for this request much reference a schema named `File`. +For this test, the body for this request must reference a schema named `File`. ### Examples diff --git a/samples/client/petstore/ruby/lib/petstore.rb b/samples/client/petstore/ruby/lib/petstore.rb index 1c0389beacd..df4c5ad38e7 100644 --- a/samples/client/petstore/ruby/lib/petstore.rb +++ b/samples/client/petstore/ruby/lib/petstore.rb @@ -6,7 +6,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =end 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 1b9b1297272..3a1ebebc3df 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,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =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 2d2b7da307e..c7faf16f2af 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,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =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 3c933b61a83..6b23171fd35 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,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =end @@ -440,7 +444,64 @@ module Petstore return data, status_code, headers end - # For this test, the body for this request much reference a schema named `File`. + # For this test, the body has to be a binary file. + # @param body [File] image to upload + # @param [Hash] opts the optional parameters + # @return [nil] + def test_body_with_binary(body, opts = {}) + test_body_with_binary_with_http_info(body, opts) + nil + end + + # For this test, the body has to be a binary file. + # @param body [File] image to upload + # @param [Hash] opts the optional parameters + # @return [Array<(nil, Integer, Hash)>] nil, response status code and response headers + def test_body_with_binary_with_http_info(body, opts = {}) + if @api_client.config.debugging + @api_client.config.logger.debug 'Calling API: FakeApi.test_body_with_binary ...' + end + # resource path + local_var_path = '/fake/body-with-binary' + + # query parameters + query_params = opts[:query_params] || {} + + # header parameters + header_params = opts[:header_params] || {} + # HTTP header 'Content-Type' + header_params['Content-Type'] = @api_client.select_header_content_type(['image/png']) + + # form parameters + form_params = opts[:form_params] || {} + + # http body (model) + post_body = opts[:debug_body] || @api_client.object_to_http_body(body) + + # return_type + return_type = opts[:debug_return_type] + + # auth_names + auth_names = opts[:debug_auth_names] || [] + + new_options = opts.merge( + :operation => :"FakeApi.test_body_with_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(:PUT, local_var_path, new_options) + if @api_client.config.debugging + @api_client.config.logger.debug "API called: FakeApi#test_body_with_binary\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" + end + return data, status_code, headers + end + + # For this test, the body for this request must reference a schema named `File`. # @param file_schema_test_class [FileSchemaTestClass] # @param [Hash] opts the optional parameters # @return [nil] @@ -449,7 +510,7 @@ module Petstore nil end - # For this test, the body for this request much reference a schema named `File`. + # For this test, the body for this request must reference a schema named `File`. # @param file_schema_test_class [FileSchemaTestClass] # @param [Hash] opts the optional parameters # @return [Array<(nil, Integer, Hash)>] nil, response status code and response headers @@ -1179,7 +1240,7 @@ module Petstore # query parameters query_params = opts[:query_params] || {} - query_params[:'pipe'] = @api_client.build_collection_param(pipe, :multi) + query_params[:'pipe'] = @api_client.build_collection_param(pipe, :pipes) query_params[:'ioutil'] = @api_client.build_collection_param(ioutil, :csv) query_params[:'http'] = @api_client.build_collection_param(http, :ssv) query_params[:'url'] = @api_client.build_collection_param(url, :csv) 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 a0f686867d9..da10052dd2a 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,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =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 ce4639d99fc..76c9117ada7 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,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =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 2fdcbb1e893..db3ff6bc862 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,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =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 ab73c19e3ff..c239ff1d9a9 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,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =end diff --git a/samples/client/petstore/ruby/lib/petstore/api_client.rb b/samples/client/petstore/ruby/lib/petstore/api_client.rb index 8b67459b3f4..faa7f88a8bd 100644 --- a/samples/client/petstore/ruby/lib/petstore/api_client.rb +++ b/samples/client/petstore/ruby/lib/petstore/api_client.rb @@ -6,7 +6,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =end diff --git a/samples/client/petstore/ruby/lib/petstore/api_error.rb b/samples/client/petstore/ruby/lib/petstore/api_error.rb index 85b3bd9da06..37f6d8fc29f 100644 --- a/samples/client/petstore/ruby/lib/petstore/api_error.rb +++ b/samples/client/petstore/ruby/lib/petstore/api_error.rb @@ -6,7 +6,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =end diff --git a/samples/client/petstore/ruby/lib/petstore/configuration.rb b/samples/client/petstore/ruby/lib/petstore/configuration.rb index e76708b33a3..620e49b7a9a 100644 --- a/samples/client/petstore/ruby/lib/petstore/configuration.rb +++ b/samples/client/petstore/ruby/lib/petstore/configuration.rb @@ -6,7 +6,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =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 ef7cdf93d9d..6d5e77e7d75 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,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =end diff --git a/samples/client/petstore/ruby/lib/petstore/models/animal.rb b/samples/client/petstore/ruby/lib/petstore/models/animal.rb index 7e22de93da5..be16e3cf5f4 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/animal.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/animal.rb @@ -6,7 +6,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =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 031565289a0..c20d63af0e4 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,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =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 659e25306ce..cf2dbfc8751 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,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =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 c495716c118..3162510675f 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,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =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 c6ec6c1a90f..5cee2b93325 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,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =end diff --git a/samples/client/petstore/ruby/lib/petstore/models/capitalization.rb b/samples/client/petstore/ruby/lib/petstore/models/capitalization.rb index a89f9693501..e17c007ec1b 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/capitalization.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/capitalization.rb @@ -6,7 +6,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =end diff --git a/samples/client/petstore/ruby/lib/petstore/models/cat.rb b/samples/client/petstore/ruby/lib/petstore/models/cat.rb index 57cfa8343d0..37f256a4c8a 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/cat.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/cat.rb @@ -6,7 +6,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =end diff --git a/samples/client/petstore/ruby/lib/petstore/models/cat_all_of.rb b/samples/client/petstore/ruby/lib/petstore/models/cat_all_of.rb index 10be8ec0a08..b440220a2ed 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/cat_all_of.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/cat_all_of.rb @@ -6,7 +6,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =end diff --git a/samples/client/petstore/ruby/lib/petstore/models/category.rb b/samples/client/petstore/ruby/lib/petstore/models/category.rb index ea966f177bc..7a49cdcda2f 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/category.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/category.rb @@ -6,7 +6,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =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 b73022da326..fb821398573 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,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =end diff --git a/samples/client/petstore/ruby/lib/petstore/models/client.rb b/samples/client/petstore/ruby/lib/petstore/models/client.rb index e874ebe700f..36d48682205 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/client.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/client.rb @@ -6,7 +6,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =end diff --git a/samples/client/petstore/ruby/lib/petstore/models/dog.rb b/samples/client/petstore/ruby/lib/petstore/models/dog.rb index 7d692a46b61..9787bc82bcf 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/dog.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/dog.rb @@ -6,7 +6,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =end diff --git a/samples/client/petstore/ruby/lib/petstore/models/dog_all_of.rb b/samples/client/petstore/ruby/lib/petstore/models/dog_all_of.rb index 7e9649319fb..646d4b556d1 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/dog_all_of.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/dog_all_of.rb @@ -6,7 +6,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =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 23580e86e68..c19bc78f979 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,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =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 9913a456cdc..d1d43400c59 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,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =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 a972cfdb885..7ed6d4b365b 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,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =end diff --git a/samples/client/petstore/ruby/lib/petstore/models/file.rb b/samples/client/petstore/ruby/lib/petstore/models/file.rb index adbf1b36756..856ec3e41ea 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/file.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/file.rb @@ -6,7 +6,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =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 b99cf2a5305..235390c32da 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,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =end diff --git a/samples/client/petstore/ruby/lib/petstore/models/foo.rb b/samples/client/petstore/ruby/lib/petstore/models/foo.rb index 9361c7a52d3..1727a09fdaa 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/foo.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/foo.rb @@ -6,7 +6,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =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 78da1ead1f8..32adcdca86f 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,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =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 121251962cb..90c0ce27f0b 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,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =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 1d3d86c5496..5d81c3a4a70 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,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =end diff --git a/samples/client/petstore/ruby/lib/petstore/models/inline_response_default.rb b/samples/client/petstore/ruby/lib/petstore/models/inline_response_default.rb index 605524a3dcd..589ec6fd11c 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/inline_response_default.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/inline_response_default.rb @@ -6,7 +6,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =end diff --git a/samples/client/petstore/ruby/lib/petstore/models/list.rb b/samples/client/petstore/ruby/lib/petstore/models/list.rb index 86bd8d8cc3f..ec03a9ba040 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/list.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/list.rb @@ -6,7 +6,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =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 1c7c233056a..415b006f7ab 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,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =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 ba61734af03..ad0a4256f38 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,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =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 813d434348e..ebe17766a37 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,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =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 9b6cb8a8174..00e71d0b805 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,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =end diff --git a/samples/client/petstore/ruby/lib/petstore/models/name.rb b/samples/client/petstore/ruby/lib/petstore/models/name.rb index 26019385252..c5dcdb3c6af 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/name.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/name.rb @@ -6,7 +6,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =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 b33d22daadb..ca9ec495b5b 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,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =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 28148b31886..48b8d2d279f 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,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =end diff --git a/samples/client/petstore/ruby/lib/petstore/models/order.rb b/samples/client/petstore/ruby/lib/petstore/models/order.rb index 374e7e85aff..40b0a9bffd9 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/order.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/order.rb @@ -6,7 +6,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =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 e0776697e63..68e655cfb1f 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,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =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 91902de42c8..e6b496b2bf9 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,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =end 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 78ea4449368..915f78a0f66 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,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =end 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 ed9af6f2c46..9a9c9a03694 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,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =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 f6a263dfe9d..334b0598136 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,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =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 a304dc9b46c..f5ff813d2b0 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,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =end diff --git a/samples/client/petstore/ruby/lib/petstore/models/pet.rb b/samples/client/petstore/ruby/lib/petstore/models/pet.rb index 68c3343d1d3..35cbe40f430 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/pet.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/pet.rb @@ -6,7 +6,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =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 6c18c4ea29c..de94c54c4ef 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,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =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 a2e8925d2ce..6adc47d9b5a 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,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =end diff --git a/samples/client/petstore/ruby/lib/petstore/models/tag.rb b/samples/client/petstore/ruby/lib/petstore/models/tag.rb index a9958f7d213..a90d22c5ff1 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/tag.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/tag.rb @@ -6,7 +6,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =end diff --git a/samples/client/petstore/ruby/lib/petstore/models/user.rb b/samples/client/petstore/ruby/lib/petstore/models/user.rb index f59454450b2..b08062f32db 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/user.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/user.rb @@ -6,7 +6,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =end diff --git a/samples/client/petstore/ruby/lib/petstore/version.rb b/samples/client/petstore/ruby/lib/petstore/version.rb index 59c7e87806f..460e6134857 100644 --- a/samples/client/petstore/ruby/lib/petstore/version.rb +++ b/samples/client/petstore/ruby/lib/petstore/version.rb @@ -6,7 +6,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =end diff --git a/samples/client/petstore/ruby/petstore.gemspec b/samples/client/petstore/ruby/petstore.gemspec index 0d15140ae09..60bacbe7d49 100644 --- a/samples/client/petstore/ruby/petstore.gemspec +++ b/samples/client/petstore/ruby/petstore.gemspec @@ -8,7 +8,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =end diff --git a/samples/client/petstore/ruby/spec/api_client_spec.rb b/samples/client/petstore/ruby/spec/api_client_spec.rb index 17a12f2b635..f487e3eb58b 100644 --- a/samples/client/petstore/ruby/spec/api_client_spec.rb +++ b/samples/client/petstore/ruby/spec/api_client_spec.rb @@ -6,7 +6,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =end diff --git a/samples/client/petstore/ruby/spec/configuration_spec.rb b/samples/client/petstore/ruby/spec/configuration_spec.rb index 785eebfe6d6..b76b6cbee30 100644 --- a/samples/client/petstore/ruby/spec/configuration_spec.rb +++ b/samples/client/petstore/ruby/spec/configuration_spec.rb @@ -6,7 +6,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =end diff --git a/samples/client/petstore/ruby/spec/spec_helper.rb b/samples/client/petstore/ruby/spec/spec_helper.rb index d4a79a9a5be..f85cbfd7373 100644 --- a/samples/client/petstore/ruby/spec/spec_helper.rb +++ b/samples/client/petstore/ruby/spec/spec_helper.rb @@ -6,7 +6,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =end diff --git a/samples/client/petstore/rust/hyper/petstore/.openapi-generator/VERSION b/samples/client/petstore/rust/hyper/petstore/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/client/petstore/rust/hyper/petstore/.openapi-generator/VERSION +++ b/samples/client/petstore/rust/hyper/petstore/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x 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 5f68295fc19..e8415097f3a 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,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/client/petstore/rust/reqwest/petstore-async/README.md b/samples/client/petstore/rust/reqwest/petstore-async/README.md index 4a3e0251107..6f195d6388d 100644 --- a/samples/client/petstore/rust/reqwest/petstore-async/README.md +++ b/samples/client/petstore/rust/reqwest/petstore-async/README.md @@ -24,26 +24,26 @@ All URIs are relative to *http://petstore.swagger.io/v2* Class | Method | HTTP request | Description ------------ | ------------- | ------------- | ------------- -*PetApi* | [**add_pet**](docs/PetApi.md#add_pet) | **post** /pet | Add a new pet to the store -*PetApi* | [**delete_pet**](docs/PetApi.md#delete_pet) | **delete** /pet/{petId} | Deletes a pet -*PetApi* | [**find_pets_by_status**](docs/PetApi.md#find_pets_by_status) | **get** /pet/findByStatus | Finds Pets by status -*PetApi* | [**find_pets_by_tags**](docs/PetApi.md#find_pets_by_tags) | **get** /pet/findByTags | Finds Pets by tags -*PetApi* | [**get_pet_by_id**](docs/PetApi.md#get_pet_by_id) | **get** /pet/{petId} | Find pet by ID -*PetApi* | [**update_pet**](docs/PetApi.md#update_pet) | **put** /pet | Update an existing pet -*PetApi* | [**update_pet_with_form**](docs/PetApi.md#update_pet_with_form) | **post** /pet/{petId} | Updates a pet in the store with form data -*PetApi* | [**upload_file**](docs/PetApi.md#upload_file) | **post** /pet/{petId}/uploadImage | uploads an image -*StoreApi* | [**delete_order**](docs/StoreApi.md#delete_order) | **delete** /store/order/{orderId} | Delete purchase order by ID -*StoreApi* | [**get_inventory**](docs/StoreApi.md#get_inventory) | **get** /store/inventory | Returns pet inventories by status -*StoreApi* | [**get_order_by_id**](docs/StoreApi.md#get_order_by_id) | **get** /store/order/{orderId} | Find purchase order by ID -*StoreApi* | [**place_order**](docs/StoreApi.md#place_order) | **post** /store/order | Place an order for a pet -*UserApi* | [**create_user**](docs/UserApi.md#create_user) | **post** /user | Create user -*UserApi* | [**create_users_with_array_input**](docs/UserApi.md#create_users_with_array_input) | **post** /user/createWithArray | Creates list of users with given input array -*UserApi* | [**create_users_with_list_input**](docs/UserApi.md#create_users_with_list_input) | **post** /user/createWithList | Creates list of users with given input array -*UserApi* | [**delete_user**](docs/UserApi.md#delete_user) | **delete** /user/{username} | Delete user -*UserApi* | [**get_user_by_name**](docs/UserApi.md#get_user_by_name) | **get** /user/{username} | Get user by user name -*UserApi* | [**login_user**](docs/UserApi.md#login_user) | **get** /user/login | Logs user into the system -*UserApi* | [**logout_user**](docs/UserApi.md#logout_user) | **get** /user/logout | Logs out current logged in user session -*UserApi* | [**update_user**](docs/UserApi.md#update_user) | **put** /user/{username} | Updated user +*PetApi* | [**add_pet**](docs/PetApi.md#add_pet) | **POST** /pet | Add a new pet to the store +*PetApi* | [**delete_pet**](docs/PetApi.md#delete_pet) | **DELETE** /pet/{petId} | Deletes a pet +*PetApi* | [**find_pets_by_status**](docs/PetApi.md#find_pets_by_status) | **GET** /pet/findByStatus | Finds Pets by status +*PetApi* | [**find_pets_by_tags**](docs/PetApi.md#find_pets_by_tags) | **GET** /pet/findByTags | Finds Pets by tags +*PetApi* | [**get_pet_by_id**](docs/PetApi.md#get_pet_by_id) | **GET** /pet/{petId} | Find pet by ID +*PetApi* | [**update_pet**](docs/PetApi.md#update_pet) | **PUT** /pet | Update an existing pet +*PetApi* | [**update_pet_with_form**](docs/PetApi.md#update_pet_with_form) | **POST** /pet/{petId} | Updates a pet in the store with form data +*PetApi* | [**upload_file**](docs/PetApi.md#upload_file) | **POST** /pet/{petId}/uploadImage | uploads an image +*StoreApi* | [**delete_order**](docs/StoreApi.md#delete_order) | **DELETE** /store/order/{orderId} | Delete purchase order by ID +*StoreApi* | [**get_inventory**](docs/StoreApi.md#get_inventory) | **GET** /store/inventory | Returns pet inventories by status +*StoreApi* | [**get_order_by_id**](docs/StoreApi.md#get_order_by_id) | **GET** /store/order/{orderId} | Find purchase order by ID +*StoreApi* | [**place_order**](docs/StoreApi.md#place_order) | **POST** /store/order | Place an order for a pet +*UserApi* | [**create_user**](docs/UserApi.md#create_user) | **POST** /user | Create user +*UserApi* | [**create_users_with_array_input**](docs/UserApi.md#create_users_with_array_input) | **POST** /user/createWithArray | Creates list of users with given input array +*UserApi* | [**create_users_with_list_input**](docs/UserApi.md#create_users_with_list_input) | **POST** /user/createWithList | Creates list of users with given input array +*UserApi* | [**delete_user**](docs/UserApi.md#delete_user) | **DELETE** /user/{username} | Delete user +*UserApi* | [**get_user_by_name**](docs/UserApi.md#get_user_by_name) | **GET** /user/{username} | Get user by user name +*UserApi* | [**login_user**](docs/UserApi.md#login_user) | **GET** /user/login | Logs user into the system +*UserApi* | [**logout_user**](docs/UserApi.md#logout_user) | **GET** /user/logout | Logs out current logged in user session +*UserApi* | [**update_user**](docs/UserApi.md#update_user) | **PUT** /user/{username} | Updated user ## Documentation For Models diff --git a/samples/client/petstore/rust/reqwest/petstore-async/docs/PetApi.md b/samples/client/petstore/rust/reqwest/petstore-async/docs/PetApi.md index 4716e752b66..4833ebc6277 100644 --- a/samples/client/petstore/rust/reqwest/petstore-async/docs/PetApi.md +++ b/samples/client/petstore/rust/reqwest/petstore-async/docs/PetApi.md @@ -4,14 +4,14 @@ All URIs are relative to *http://petstore.swagger.io/v2* Method | HTTP request | Description ------------- | ------------- | ------------- -[**add_pet**](PetApi.md#add_pet) | **post** /pet | Add a new pet to the store -[**delete_pet**](PetApi.md#delete_pet) | **delete** /pet/{petId} | Deletes a pet -[**find_pets_by_status**](PetApi.md#find_pets_by_status) | **get** /pet/findByStatus | Finds Pets by status -[**find_pets_by_tags**](PetApi.md#find_pets_by_tags) | **get** /pet/findByTags | Finds Pets by tags -[**get_pet_by_id**](PetApi.md#get_pet_by_id) | **get** /pet/{petId} | Find pet by ID -[**update_pet**](PetApi.md#update_pet) | **put** /pet | Update an existing pet -[**update_pet_with_form**](PetApi.md#update_pet_with_form) | **post** /pet/{petId} | Updates a pet in the store with form data -[**upload_file**](PetApi.md#upload_file) | **post** /pet/{petId}/uploadImage | uploads an image +[**add_pet**](PetApi.md#add_pet) | **POST** /pet | Add a new pet to the store +[**delete_pet**](PetApi.md#delete_pet) | **DELETE** /pet/{petId} | Deletes a pet +[**find_pets_by_status**](PetApi.md#find_pets_by_status) | **GET** /pet/findByStatus | Finds Pets by status +[**find_pets_by_tags**](PetApi.md#find_pets_by_tags) | **GET** /pet/findByTags | Finds Pets by tags +[**get_pet_by_id**](PetApi.md#get_pet_by_id) | **GET** /pet/{petId} | Find pet by ID +[**update_pet**](PetApi.md#update_pet) | **PUT** /pet | Update an existing pet +[**update_pet_with_form**](PetApi.md#update_pet_with_form) | **POST** /pet/{petId} | Updates a pet in the store with form data +[**upload_file**](PetApi.md#upload_file) | **POST** /pet/{petId}/uploadImage | uploads an image diff --git a/samples/client/petstore/rust/reqwest/petstore-async/docs/StoreApi.md b/samples/client/petstore/rust/reqwest/petstore-async/docs/StoreApi.md index a310b538315..79c900d4ae4 100644 --- a/samples/client/petstore/rust/reqwest/petstore-async/docs/StoreApi.md +++ b/samples/client/petstore/rust/reqwest/petstore-async/docs/StoreApi.md @@ -4,10 +4,10 @@ All URIs are relative to *http://petstore.swagger.io/v2* Method | HTTP request | Description ------------- | ------------- | ------------- -[**delete_order**](StoreApi.md#delete_order) | **delete** /store/order/{orderId} | Delete purchase order by ID -[**get_inventory**](StoreApi.md#get_inventory) | **get** /store/inventory | Returns pet inventories by status -[**get_order_by_id**](StoreApi.md#get_order_by_id) | **get** /store/order/{orderId} | Find purchase order by ID -[**place_order**](StoreApi.md#place_order) | **post** /store/order | Place an order for a pet +[**delete_order**](StoreApi.md#delete_order) | **DELETE** /store/order/{orderId} | Delete purchase order by ID +[**get_inventory**](StoreApi.md#get_inventory) | **GET** /store/inventory | Returns pet inventories by status +[**get_order_by_id**](StoreApi.md#get_order_by_id) | **GET** /store/order/{orderId} | Find purchase order by ID +[**place_order**](StoreApi.md#place_order) | **POST** /store/order | Place an order for a pet diff --git a/samples/client/petstore/rust/reqwest/petstore-async/docs/UserApi.md b/samples/client/petstore/rust/reqwest/petstore-async/docs/UserApi.md index a6268f251a6..f8a2117f7f8 100644 --- a/samples/client/petstore/rust/reqwest/petstore-async/docs/UserApi.md +++ b/samples/client/petstore/rust/reqwest/petstore-async/docs/UserApi.md @@ -4,14 +4,14 @@ All URIs are relative to *http://petstore.swagger.io/v2* Method | HTTP request | Description ------------- | ------------- | ------------- -[**create_user**](UserApi.md#create_user) | **post** /user | Create user -[**create_users_with_array_input**](UserApi.md#create_users_with_array_input) | **post** /user/createWithArray | Creates list of users with given input array -[**create_users_with_list_input**](UserApi.md#create_users_with_list_input) | **post** /user/createWithList | Creates list of users with given input array -[**delete_user**](UserApi.md#delete_user) | **delete** /user/{username} | Delete user -[**get_user_by_name**](UserApi.md#get_user_by_name) | **get** /user/{username} | Get user by user name -[**login_user**](UserApi.md#login_user) | **get** /user/login | Logs user into the system -[**logout_user**](UserApi.md#logout_user) | **get** /user/logout | Logs out current logged in user session -[**update_user**](UserApi.md#update_user) | **put** /user/{username} | Updated user +[**create_user**](UserApi.md#create_user) | **POST** /user | Create user +[**create_users_with_array_input**](UserApi.md#create_users_with_array_input) | **POST** /user/createWithArray | Creates list of users with given input array +[**create_users_with_list_input**](UserApi.md#create_users_with_list_input) | **POST** /user/createWithList | Creates list of users with given input array +[**delete_user**](UserApi.md#delete_user) | **DELETE** /user/{username} | Delete user +[**get_user_by_name**](UserApi.md#get_user_by_name) | **GET** /user/{username} | Get user by user name +[**login_user**](UserApi.md#login_user) | **GET** /user/login | Logs user into the system +[**logout_user**](UserApi.md#logout_user) | **GET** /user/logout | Logs out current logged in user session +[**update_user**](UserApi.md#update_user) | **PUT** /user/{username} | Updated user diff --git a/samples/client/petstore/rust/reqwest/petstore-async/src/apis/pet_api.rs b/samples/client/petstore/rust/reqwest/petstore-async/src/apis/pet_api.rs index e4162a33129..0aec41dc66d 100644 --- a/samples/client/petstore/rust/reqwest/petstore-async/src/apis/pet_api.rs +++ b/samples/client/petstore/rust/reqwest/petstore-async/src/apis/pet_api.rs @@ -215,7 +215,7 @@ pub async fn add_pet(configuration: &configuration::Configuration, params: AddPe let local_var_client = &configuration.client; let local_var_uri_str = format!("{}/pet", configuration.base_path); - let mut local_var_req_builder = local_var_client.post(local_var_uri_str.as_str()); + let mut local_var_req_builder = local_var_client.request(reqwest::Method::POST, local_var_uri_str.as_str()); if let Some(ref local_var_user_agent) = configuration.user_agent { local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); @@ -251,7 +251,7 @@ pub async fn delete_pet(configuration: &configuration::Configuration, params: De let local_var_client = &configuration.client; let local_var_uri_str = format!("{}/pet/{petId}", configuration.base_path, petId=pet_id); - let mut local_var_req_builder = local_var_client.delete(local_var_uri_str.as_str()); + let mut local_var_req_builder = local_var_client.request(reqwest::Method::DELETE, local_var_uri_str.as_str()); if let Some(ref local_var_user_agent) = configuration.user_agent { local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); @@ -289,7 +289,7 @@ pub async fn find_pets_by_status(configuration: &configuration::Configuration, p let local_var_client = &configuration.client; let local_var_uri_str = format!("{}/pet/findByStatus", configuration.base_path); - let mut local_var_req_builder = local_var_client.get(local_var_uri_str.as_str()); + let mut local_var_req_builder = local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str()); local_var_req_builder = local_var_req_builder.query(&[("status", &status.into_iter().map(|p| p.to_string()).collect::>().join(",").to_string())]); if let Some(ref local_var_user_agent) = configuration.user_agent { @@ -325,7 +325,7 @@ pub async fn find_pets_by_tags(configuration: &configuration::Configuration, par let local_var_client = &configuration.client; let local_var_uri_str = format!("{}/pet/findByTags", configuration.base_path); - let mut local_var_req_builder = local_var_client.get(local_var_uri_str.as_str()); + let mut local_var_req_builder = local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str()); local_var_req_builder = local_var_req_builder.query(&[("tags", &tags.into_iter().map(|p| p.to_string()).collect::>().join(",").to_string())]); if let Some(ref local_var_user_agent) = configuration.user_agent { @@ -361,7 +361,7 @@ pub async fn get_pet_by_id(configuration: &configuration::Configuration, params: let local_var_client = &configuration.client; let local_var_uri_str = format!("{}/pet/{petId}", configuration.base_path, petId=pet_id); - let mut local_var_req_builder = local_var_client.get(local_var_uri_str.as_str()); + let mut local_var_req_builder = local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str()); if let Some(ref local_var_user_agent) = configuration.user_agent { local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); @@ -400,7 +400,7 @@ pub async fn update_pet(configuration: &configuration::Configuration, params: Up let local_var_client = &configuration.client; let local_var_uri_str = format!("{}/pet", configuration.base_path); - let mut local_var_req_builder = local_var_client.put(local_var_uri_str.as_str()); + let mut local_var_req_builder = local_var_client.request(reqwest::Method::PUT, local_var_uri_str.as_str()); if let Some(ref local_var_user_agent) = configuration.user_agent { local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); @@ -437,7 +437,7 @@ pub async fn update_pet_with_form(configuration: &configuration::Configuration, let local_var_client = &configuration.client; let local_var_uri_str = format!("{}/pet/{petId}", configuration.base_path, petId=pet_id); - let mut local_var_req_builder = local_var_client.post(local_var_uri_str.as_str()); + let mut local_var_req_builder = local_var_client.request(reqwest::Method::POST, local_var_uri_str.as_str()); if let Some(ref local_var_user_agent) = configuration.user_agent { local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); @@ -481,7 +481,7 @@ pub async fn upload_file(configuration: &configuration::Configuration, params: U let local_var_client = &configuration.client; let local_var_uri_str = format!("{}/pet/{petId}/uploadImage", configuration.base_path, petId=pet_id); - let mut local_var_req_builder = local_var_client.post(local_var_uri_str.as_str()); + let mut local_var_req_builder = local_var_client.request(reqwest::Method::POST, local_var_uri_str.as_str()); if let Some(ref local_var_user_agent) = configuration.user_agent { local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); diff --git a/samples/client/petstore/rust/reqwest/petstore-async/src/apis/store_api.rs b/samples/client/petstore/rust/reqwest/petstore-async/src/apis/store_api.rs index 21647faa062..c4c4ff3b207 100644 --- a/samples/client/petstore/rust/reqwest/petstore-async/src/apis/store_api.rs +++ b/samples/client/petstore/rust/reqwest/petstore-async/src/apis/store_api.rs @@ -110,7 +110,7 @@ pub async fn delete_order(configuration: &configuration::Configuration, params: let local_var_client = &configuration.client; let local_var_uri_str = format!("{}/store/order/{orderId}", configuration.base_path, orderId=crate::apis::urlencode(order_id)); - let mut local_var_req_builder = local_var_client.delete(local_var_uri_str.as_str()); + let mut local_var_req_builder = local_var_client.request(reqwest::Method::DELETE, local_var_uri_str.as_str()); if let Some(ref local_var_user_agent) = configuration.user_agent { local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); @@ -141,7 +141,7 @@ pub async fn get_inventory(configuration: &configuration::Configuration) -> Resu let local_var_client = &configuration.client; let local_var_uri_str = format!("{}/store/inventory", configuration.base_path); - let mut local_var_req_builder = local_var_client.get(local_var_uri_str.as_str()); + let mut local_var_req_builder = local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str()); if let Some(ref local_var_user_agent) = configuration.user_agent { local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); @@ -181,7 +181,7 @@ pub async fn get_order_by_id(configuration: &configuration::Configuration, param let local_var_client = &configuration.client; let local_var_uri_str = format!("{}/store/order/{orderId}", configuration.base_path, orderId=order_id); - let mut local_var_req_builder = local_var_client.get(local_var_uri_str.as_str()); + let mut local_var_req_builder = local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str()); if let Some(ref local_var_user_agent) = configuration.user_agent { local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); @@ -212,7 +212,7 @@ pub async fn place_order(configuration: &configuration::Configuration, params: P let local_var_client = &configuration.client; let local_var_uri_str = format!("{}/store/order", configuration.base_path); - let mut local_var_req_builder = local_var_client.post(local_var_uri_str.as_str()); + let mut local_var_req_builder = local_var_client.request(reqwest::Method::POST, local_var_uri_str.as_str()); if let Some(ref local_var_user_agent) = configuration.user_agent { local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); diff --git a/samples/client/petstore/rust/reqwest/petstore-async/src/apis/user_api.rs b/samples/client/petstore/rust/reqwest/petstore-async/src/apis/user_api.rs index a791bfbc9bb..5bd62bf8553 100644 --- a/samples/client/petstore/rust/reqwest/petstore-async/src/apis/user_api.rs +++ b/samples/client/petstore/rust/reqwest/petstore-async/src/apis/user_api.rs @@ -203,7 +203,7 @@ pub async fn create_user(configuration: &configuration::Configuration, params: C let local_var_client = &configuration.client; let local_var_uri_str = format!("{}/user", configuration.base_path); - let mut local_var_req_builder = local_var_client.post(local_var_uri_str.as_str()); + let mut local_var_req_builder = local_var_client.request(reqwest::Method::POST, local_var_uri_str.as_str()); if let Some(ref local_var_user_agent) = configuration.user_agent { local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); @@ -235,7 +235,7 @@ pub async fn create_users_with_array_input(configuration: &configuration::Config let local_var_client = &configuration.client; let local_var_uri_str = format!("{}/user/createWithArray", configuration.base_path); - let mut local_var_req_builder = local_var_client.post(local_var_uri_str.as_str()); + let mut local_var_req_builder = local_var_client.request(reqwest::Method::POST, local_var_uri_str.as_str()); if let Some(ref local_var_user_agent) = configuration.user_agent { local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); @@ -267,7 +267,7 @@ pub async fn create_users_with_list_input(configuration: &configuration::Configu let local_var_client = &configuration.client; let local_var_uri_str = format!("{}/user/createWithList", configuration.base_path); - let mut local_var_req_builder = local_var_client.post(local_var_uri_str.as_str()); + let mut local_var_req_builder = local_var_client.request(reqwest::Method::POST, local_var_uri_str.as_str()); if let Some(ref local_var_user_agent) = configuration.user_agent { local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); @@ -300,7 +300,7 @@ pub async fn delete_user(configuration: &configuration::Configuration, params: D let local_var_client = &configuration.client; let local_var_uri_str = format!("{}/user/{username}", configuration.base_path, username=crate::apis::urlencode(username)); - let mut local_var_req_builder = local_var_client.delete(local_var_uri_str.as_str()); + let mut local_var_req_builder = local_var_client.request(reqwest::Method::DELETE, local_var_uri_str.as_str()); if let Some(ref local_var_user_agent) = configuration.user_agent { local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); @@ -331,7 +331,7 @@ pub async fn get_user_by_name(configuration: &configuration::Configuration, para let local_var_client = &configuration.client; let local_var_uri_str = format!("{}/user/{username}", configuration.base_path, username=crate::apis::urlencode(username)); - let mut local_var_req_builder = local_var_client.get(local_var_uri_str.as_str()); + let mut local_var_req_builder = local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str()); if let Some(ref local_var_user_agent) = configuration.user_agent { local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); @@ -363,7 +363,7 @@ pub async fn login_user(configuration: &configuration::Configuration, params: Lo let local_var_client = &configuration.client; let local_var_uri_str = format!("{}/user/login", configuration.base_path); - let mut local_var_req_builder = local_var_client.get(local_var_uri_str.as_str()); + let mut local_var_req_builder = local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str()); local_var_req_builder = local_var_req_builder.query(&[("username", &username.to_string())]); local_var_req_builder = local_var_req_builder.query(&[("password", &password.to_string())]); @@ -395,7 +395,7 @@ pub async fn logout_user(configuration: &configuration::Configuration) -> Result let local_var_client = &configuration.client; let local_var_uri_str = format!("{}/user/logout", configuration.base_path); - let mut local_var_req_builder = local_var_client.get(local_var_uri_str.as_str()); + let mut local_var_req_builder = local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str()); if let Some(ref local_var_user_agent) = configuration.user_agent { local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); @@ -428,7 +428,7 @@ pub async fn update_user(configuration: &configuration::Configuration, params: U let local_var_client = &configuration.client; let local_var_uri_str = format!("{}/user/{username}", configuration.base_path, username=crate::apis::urlencode(username)); - let mut local_var_req_builder = local_var_client.put(local_var_uri_str.as_str()); + let mut local_var_req_builder = local_var_client.request(reqwest::Method::PUT, local_var_uri_str.as_str()); if let Some(ref local_var_user_agent) = configuration.user_agent { local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); diff --git a/samples/client/petstore/rust/reqwest/petstore/.openapi-generator/VERSION b/samples/client/petstore/rust/reqwest/petstore/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/client/petstore/rust/reqwest/petstore/.openapi-generator/VERSION +++ b/samples/client/petstore/rust/reqwest/petstore/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/client/petstore/rust/reqwest/petstore/README.md b/samples/client/petstore/rust/reqwest/petstore/README.md index b83be74204c..57aa8f05026 100644 --- a/samples/client/petstore/rust/reqwest/petstore/README.md +++ b/samples/client/petstore/rust/reqwest/petstore/README.md @@ -24,26 +24,26 @@ All URIs are relative to *http://petstore.swagger.io/v2* Class | Method | HTTP request | Description ------------ | ------------- | ------------- | ------------- -*PetApi* | [**add_pet**](docs/PetApi.md#add_pet) | **post** /pet | Add a new pet to the store -*PetApi* | [**delete_pet**](docs/PetApi.md#delete_pet) | **delete** /pet/{petId} | Deletes a pet -*PetApi* | [**find_pets_by_status**](docs/PetApi.md#find_pets_by_status) | **get** /pet/findByStatus | Finds Pets by status -*PetApi* | [**find_pets_by_tags**](docs/PetApi.md#find_pets_by_tags) | **get** /pet/findByTags | Finds Pets by tags -*PetApi* | [**get_pet_by_id**](docs/PetApi.md#get_pet_by_id) | **get** /pet/{petId} | Find pet by ID -*PetApi* | [**update_pet**](docs/PetApi.md#update_pet) | **put** /pet | Update an existing pet -*PetApi* | [**update_pet_with_form**](docs/PetApi.md#update_pet_with_form) | **post** /pet/{petId} | Updates a pet in the store with form data -*PetApi* | [**upload_file**](docs/PetApi.md#upload_file) | **post** /pet/{petId}/uploadImage | uploads an image -*StoreApi* | [**delete_order**](docs/StoreApi.md#delete_order) | **delete** /store/order/{orderId} | Delete purchase order by ID -*StoreApi* | [**get_inventory**](docs/StoreApi.md#get_inventory) | **get** /store/inventory | Returns pet inventories by status -*StoreApi* | [**get_order_by_id**](docs/StoreApi.md#get_order_by_id) | **get** /store/order/{orderId} | Find purchase order by ID -*StoreApi* | [**place_order**](docs/StoreApi.md#place_order) | **post** /store/order | Place an order for a pet -*UserApi* | [**create_user**](docs/UserApi.md#create_user) | **post** /user | Create user -*UserApi* | [**create_users_with_array_input**](docs/UserApi.md#create_users_with_array_input) | **post** /user/createWithArray | Creates list of users with given input array -*UserApi* | [**create_users_with_list_input**](docs/UserApi.md#create_users_with_list_input) | **post** /user/createWithList | Creates list of users with given input array -*UserApi* | [**delete_user**](docs/UserApi.md#delete_user) | **delete** /user/{username} | Delete user -*UserApi* | [**get_user_by_name**](docs/UserApi.md#get_user_by_name) | **get** /user/{username} | Get user by user name -*UserApi* | [**login_user**](docs/UserApi.md#login_user) | **get** /user/login | Logs user into the system -*UserApi* | [**logout_user**](docs/UserApi.md#logout_user) | **get** /user/logout | Logs out current logged in user session -*UserApi* | [**update_user**](docs/UserApi.md#update_user) | **put** /user/{username} | Updated user +*PetApi* | [**add_pet**](docs/PetApi.md#add_pet) | **POST** /pet | Add a new pet to the store +*PetApi* | [**delete_pet**](docs/PetApi.md#delete_pet) | **DELETE** /pet/{petId} | Deletes a pet +*PetApi* | [**find_pets_by_status**](docs/PetApi.md#find_pets_by_status) | **GET** /pet/findByStatus | Finds Pets by status +*PetApi* | [**find_pets_by_tags**](docs/PetApi.md#find_pets_by_tags) | **GET** /pet/findByTags | Finds Pets by tags +*PetApi* | [**get_pet_by_id**](docs/PetApi.md#get_pet_by_id) | **GET** /pet/{petId} | Find pet by ID +*PetApi* | [**update_pet**](docs/PetApi.md#update_pet) | **PUT** /pet | Update an existing pet +*PetApi* | [**update_pet_with_form**](docs/PetApi.md#update_pet_with_form) | **POST** /pet/{petId} | Updates a pet in the store with form data +*PetApi* | [**upload_file**](docs/PetApi.md#upload_file) | **POST** /pet/{petId}/uploadImage | uploads an image +*StoreApi* | [**delete_order**](docs/StoreApi.md#delete_order) | **DELETE** /store/order/{orderId} | Delete purchase order by ID +*StoreApi* | [**get_inventory**](docs/StoreApi.md#get_inventory) | **GET** /store/inventory | Returns pet inventories by status +*StoreApi* | [**get_order_by_id**](docs/StoreApi.md#get_order_by_id) | **GET** /store/order/{orderId} | Find purchase order by ID +*StoreApi* | [**place_order**](docs/StoreApi.md#place_order) | **POST** /store/order | Place an order for a pet +*UserApi* | [**create_user**](docs/UserApi.md#create_user) | **POST** /user | Create user +*UserApi* | [**create_users_with_array_input**](docs/UserApi.md#create_users_with_array_input) | **POST** /user/createWithArray | Creates list of users with given input array +*UserApi* | [**create_users_with_list_input**](docs/UserApi.md#create_users_with_list_input) | **POST** /user/createWithList | Creates list of users with given input array +*UserApi* | [**delete_user**](docs/UserApi.md#delete_user) | **DELETE** /user/{username} | Delete user +*UserApi* | [**get_user_by_name**](docs/UserApi.md#get_user_by_name) | **GET** /user/{username} | Get user by user name +*UserApi* | [**login_user**](docs/UserApi.md#login_user) | **GET** /user/login | Logs user into the system +*UserApi* | [**logout_user**](docs/UserApi.md#logout_user) | **GET** /user/logout | Logs out current logged in user session +*UserApi* | [**update_user**](docs/UserApi.md#update_user) | **PUT** /user/{username} | Updated user ## Documentation For Models diff --git a/samples/client/petstore/rust/reqwest/petstore/docs/PetApi.md b/samples/client/petstore/rust/reqwest/petstore/docs/PetApi.md index 4716e752b66..4833ebc6277 100644 --- a/samples/client/petstore/rust/reqwest/petstore/docs/PetApi.md +++ b/samples/client/petstore/rust/reqwest/petstore/docs/PetApi.md @@ -4,14 +4,14 @@ All URIs are relative to *http://petstore.swagger.io/v2* Method | HTTP request | Description ------------- | ------------- | ------------- -[**add_pet**](PetApi.md#add_pet) | **post** /pet | Add a new pet to the store -[**delete_pet**](PetApi.md#delete_pet) | **delete** /pet/{petId} | Deletes a pet -[**find_pets_by_status**](PetApi.md#find_pets_by_status) | **get** /pet/findByStatus | Finds Pets by status -[**find_pets_by_tags**](PetApi.md#find_pets_by_tags) | **get** /pet/findByTags | Finds Pets by tags -[**get_pet_by_id**](PetApi.md#get_pet_by_id) | **get** /pet/{petId} | Find pet by ID -[**update_pet**](PetApi.md#update_pet) | **put** /pet | Update an existing pet -[**update_pet_with_form**](PetApi.md#update_pet_with_form) | **post** /pet/{petId} | Updates a pet in the store with form data -[**upload_file**](PetApi.md#upload_file) | **post** /pet/{petId}/uploadImage | uploads an image +[**add_pet**](PetApi.md#add_pet) | **POST** /pet | Add a new pet to the store +[**delete_pet**](PetApi.md#delete_pet) | **DELETE** /pet/{petId} | Deletes a pet +[**find_pets_by_status**](PetApi.md#find_pets_by_status) | **GET** /pet/findByStatus | Finds Pets by status +[**find_pets_by_tags**](PetApi.md#find_pets_by_tags) | **GET** /pet/findByTags | Finds Pets by tags +[**get_pet_by_id**](PetApi.md#get_pet_by_id) | **GET** /pet/{petId} | Find pet by ID +[**update_pet**](PetApi.md#update_pet) | **PUT** /pet | Update an existing pet +[**update_pet_with_form**](PetApi.md#update_pet_with_form) | **POST** /pet/{petId} | Updates a pet in the store with form data +[**upload_file**](PetApi.md#upload_file) | **POST** /pet/{petId}/uploadImage | uploads an image diff --git a/samples/client/petstore/rust/reqwest/petstore/docs/StoreApi.md b/samples/client/petstore/rust/reqwest/petstore/docs/StoreApi.md index a310b538315..79c900d4ae4 100644 --- a/samples/client/petstore/rust/reqwest/petstore/docs/StoreApi.md +++ b/samples/client/petstore/rust/reqwest/petstore/docs/StoreApi.md @@ -4,10 +4,10 @@ All URIs are relative to *http://petstore.swagger.io/v2* Method | HTTP request | Description ------------- | ------------- | ------------- -[**delete_order**](StoreApi.md#delete_order) | **delete** /store/order/{orderId} | Delete purchase order by ID -[**get_inventory**](StoreApi.md#get_inventory) | **get** /store/inventory | Returns pet inventories by status -[**get_order_by_id**](StoreApi.md#get_order_by_id) | **get** /store/order/{orderId} | Find purchase order by ID -[**place_order**](StoreApi.md#place_order) | **post** /store/order | Place an order for a pet +[**delete_order**](StoreApi.md#delete_order) | **DELETE** /store/order/{orderId} | Delete purchase order by ID +[**get_inventory**](StoreApi.md#get_inventory) | **GET** /store/inventory | Returns pet inventories by status +[**get_order_by_id**](StoreApi.md#get_order_by_id) | **GET** /store/order/{orderId} | Find purchase order by ID +[**place_order**](StoreApi.md#place_order) | **POST** /store/order | Place an order for a pet diff --git a/samples/client/petstore/rust/reqwest/petstore/docs/UserApi.md b/samples/client/petstore/rust/reqwest/petstore/docs/UserApi.md index a6268f251a6..f8a2117f7f8 100644 --- a/samples/client/petstore/rust/reqwest/petstore/docs/UserApi.md +++ b/samples/client/petstore/rust/reqwest/petstore/docs/UserApi.md @@ -4,14 +4,14 @@ All URIs are relative to *http://petstore.swagger.io/v2* Method | HTTP request | Description ------------- | ------------- | ------------- -[**create_user**](UserApi.md#create_user) | **post** /user | Create user -[**create_users_with_array_input**](UserApi.md#create_users_with_array_input) | **post** /user/createWithArray | Creates list of users with given input array -[**create_users_with_list_input**](UserApi.md#create_users_with_list_input) | **post** /user/createWithList | Creates list of users with given input array -[**delete_user**](UserApi.md#delete_user) | **delete** /user/{username} | Delete user -[**get_user_by_name**](UserApi.md#get_user_by_name) | **get** /user/{username} | Get user by user name -[**login_user**](UserApi.md#login_user) | **get** /user/login | Logs user into the system -[**logout_user**](UserApi.md#logout_user) | **get** /user/logout | Logs out current logged in user session -[**update_user**](UserApi.md#update_user) | **put** /user/{username} | Updated user +[**create_user**](UserApi.md#create_user) | **POST** /user | Create user +[**create_users_with_array_input**](UserApi.md#create_users_with_array_input) | **POST** /user/createWithArray | Creates list of users with given input array +[**create_users_with_list_input**](UserApi.md#create_users_with_list_input) | **POST** /user/createWithList | Creates list of users with given input array +[**delete_user**](UserApi.md#delete_user) | **DELETE** /user/{username} | Delete user +[**get_user_by_name**](UserApi.md#get_user_by_name) | **GET** /user/{username} | Get user by user name +[**login_user**](UserApi.md#login_user) | **GET** /user/login | Logs user into the system +[**logout_user**](UserApi.md#logout_user) | **GET** /user/logout | Logs out current logged in user session +[**update_user**](UserApi.md#update_user) | **PUT** /user/{username} | Updated user 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 47cf47f1d59..dd7fc9ff0d4 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 @@ -87,7 +87,7 @@ pub fn add_pet(configuration: &configuration::Configuration, body: crate::models let local_var_client = &configuration.client; let local_var_uri_str = format!("{}/pet", configuration.base_path); - let mut local_var_req_builder = local_var_client.post(local_var_uri_str.as_str()); + let mut local_var_req_builder = local_var_client.request(reqwest::Method::POST, local_var_uri_str.as_str()); if let Some(ref local_var_user_agent) = configuration.user_agent { local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); @@ -117,7 +117,7 @@ pub fn delete_pet(configuration: &configuration::Configuration, pet_id: i64, api let local_var_client = &configuration.client; let local_var_uri_str = format!("{}/pet/{petId}", configuration.base_path, petId=pet_id); - let mut local_var_req_builder = local_var_client.delete(local_var_uri_str.as_str()); + let mut local_var_req_builder = local_var_client.request(reqwest::Method::DELETE, local_var_uri_str.as_str()); if let Some(ref local_var_user_agent) = configuration.user_agent { local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); @@ -150,7 +150,7 @@ pub fn find_pets_by_status(configuration: &configuration::Configuration, status: let local_var_client = &configuration.client; let local_var_uri_str = format!("{}/pet/findByStatus", configuration.base_path); - let mut local_var_req_builder = local_var_client.get(local_var_uri_str.as_str()); + let mut local_var_req_builder = local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str()); local_var_req_builder = local_var_req_builder.query(&[("status", &status.into_iter().map(|p| p.to_string()).collect::>().join(",").to_string())]); if let Some(ref local_var_user_agent) = configuration.user_agent { @@ -181,7 +181,7 @@ pub fn find_pets_by_tags(configuration: &configuration::Configuration, tags: Vec let local_var_client = &configuration.client; let local_var_uri_str = format!("{}/pet/findByTags", configuration.base_path); - let mut local_var_req_builder = local_var_client.get(local_var_uri_str.as_str()); + let mut local_var_req_builder = local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str()); local_var_req_builder = local_var_req_builder.query(&[("tags", &tags.into_iter().map(|p| p.to_string()).collect::>().join(",").to_string())]); if let Some(ref local_var_user_agent) = configuration.user_agent { @@ -212,7 +212,7 @@ pub fn get_pet_by_id(configuration: &configuration::Configuration, pet_id: i64) let local_var_client = &configuration.client; let local_var_uri_str = format!("{}/pet/{petId}", configuration.base_path, petId=pet_id); - let mut local_var_req_builder = local_var_client.get(local_var_uri_str.as_str()); + let mut local_var_req_builder = local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str()); if let Some(ref local_var_user_agent) = configuration.user_agent { local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); @@ -246,7 +246,7 @@ pub fn update_pet(configuration: &configuration::Configuration, body: crate::mod let local_var_client = &configuration.client; let local_var_uri_str = format!("{}/pet", configuration.base_path); - let mut local_var_req_builder = local_var_client.put(local_var_uri_str.as_str()); + let mut local_var_req_builder = local_var_client.request(reqwest::Method::PUT, local_var_uri_str.as_str()); if let Some(ref local_var_user_agent) = configuration.user_agent { local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); @@ -276,7 +276,7 @@ pub fn update_pet_with_form(configuration: &configuration::Configuration, pet_id let local_var_client = &configuration.client; let local_var_uri_str = format!("{}/pet/{petId}", configuration.base_path, petId=pet_id); - let mut local_var_req_builder = local_var_client.post(local_var_uri_str.as_str()); + let mut local_var_req_builder = local_var_client.request(reqwest::Method::POST, local_var_uri_str.as_str()); if let Some(ref local_var_user_agent) = configuration.user_agent { local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); @@ -313,7 +313,7 @@ pub fn upload_file(configuration: &configuration::Configuration, pet_id: i64, ad let local_var_client = &configuration.client; let local_var_uri_str = format!("{}/pet/{petId}/uploadImage", configuration.base_path, petId=pet_id); - let mut local_var_req_builder = local_var_client.post(local_var_uri_str.as_str()); + let mut local_var_req_builder = local_var_client.request(reqwest::Method::POST, local_var_uri_str.as_str()); if let Some(ref local_var_user_agent) = configuration.user_agent { local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); diff --git a/samples/client/petstore/rust/reqwest/petstore/src/apis/store_api.rs b/samples/client/petstore/rust/reqwest/petstore/src/apis/store_api.rs index 898599f9b2f..f4fd247f8ca 100644 --- a/samples/client/petstore/rust/reqwest/petstore/src/apis/store_api.rs +++ b/samples/client/petstore/rust/reqwest/petstore/src/apis/store_api.rs @@ -55,7 +55,7 @@ pub fn delete_order(configuration: &configuration::Configuration, order_id: &str let local_var_client = &configuration.client; let local_var_uri_str = format!("{}/store/order/{orderId}", configuration.base_path, orderId=crate::apis::urlencode(order_id)); - let mut local_var_req_builder = local_var_client.delete(local_var_uri_str.as_str()); + let mut local_var_req_builder = local_var_client.request(reqwest::Method::DELETE, local_var_uri_str.as_str()); if let Some(ref local_var_user_agent) = configuration.user_agent { local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); @@ -82,7 +82,7 @@ pub fn get_inventory(configuration: &configuration::Configuration, ) -> Result<: let local_var_client = &configuration.client; let local_var_uri_str = format!("{}/store/inventory", configuration.base_path); - let mut local_var_req_builder = local_var_client.get(local_var_uri_str.as_str()); + let mut local_var_req_builder = local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str()); if let Some(ref local_var_user_agent) = configuration.user_agent { local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); @@ -117,7 +117,7 @@ pub fn get_order_by_id(configuration: &configuration::Configuration, order_id: i let local_var_client = &configuration.client; let local_var_uri_str = format!("{}/store/order/{orderId}", configuration.base_path, orderId=order_id); - let mut local_var_req_builder = local_var_client.get(local_var_uri_str.as_str()); + let mut local_var_req_builder = local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str()); if let Some(ref local_var_user_agent) = configuration.user_agent { local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); @@ -143,7 +143,7 @@ pub fn place_order(configuration: &configuration::Configuration, body: crate::mo let local_var_client = &configuration.client; let local_var_uri_str = format!("{}/store/order", configuration.base_path); - let mut local_var_req_builder = local_var_client.post(local_var_uri_str.as_str()); + let mut local_var_req_builder = local_var_client.request(reqwest::Method::POST, local_var_uri_str.as_str()); if let Some(ref local_var_user_agent) = configuration.user_agent { local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); diff --git a/samples/client/petstore/rust/reqwest/petstore/src/apis/user_api.rs b/samples/client/petstore/rust/reqwest/petstore/src/apis/user_api.rs index 97f0f3c4e14..623b7ce22ff 100644 --- a/samples/client/petstore/rust/reqwest/petstore/src/apis/user_api.rs +++ b/samples/client/petstore/rust/reqwest/petstore/src/apis/user_api.rs @@ -89,7 +89,7 @@ pub fn create_user(configuration: &configuration::Configuration, body: crate::mo let local_var_client = &configuration.client; let local_var_uri_str = format!("{}/user", configuration.base_path); - let mut local_var_req_builder = local_var_client.post(local_var_uri_str.as_str()); + let mut local_var_req_builder = local_var_client.request(reqwest::Method::POST, local_var_uri_str.as_str()); if let Some(ref local_var_user_agent) = configuration.user_agent { local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); @@ -116,7 +116,7 @@ pub fn create_users_with_array_input(configuration: &configuration::Configuratio let local_var_client = &configuration.client; let local_var_uri_str = format!("{}/user/createWithArray", configuration.base_path); - let mut local_var_req_builder = local_var_client.post(local_var_uri_str.as_str()); + let mut local_var_req_builder = local_var_client.request(reqwest::Method::POST, local_var_uri_str.as_str()); if let Some(ref local_var_user_agent) = configuration.user_agent { local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); @@ -143,7 +143,7 @@ pub fn create_users_with_list_input(configuration: &configuration::Configuration let local_var_client = &configuration.client; let local_var_uri_str = format!("{}/user/createWithList", configuration.base_path); - let mut local_var_req_builder = local_var_client.post(local_var_uri_str.as_str()); + let mut local_var_req_builder = local_var_client.request(reqwest::Method::POST, local_var_uri_str.as_str()); if let Some(ref local_var_user_agent) = configuration.user_agent { local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); @@ -171,7 +171,7 @@ pub fn delete_user(configuration: &configuration::Configuration, username: &str) let local_var_client = &configuration.client; let local_var_uri_str = format!("{}/user/{username}", configuration.base_path, username=crate::apis::urlencode(username)); - let mut local_var_req_builder = local_var_client.delete(local_var_uri_str.as_str()); + let mut local_var_req_builder = local_var_client.request(reqwest::Method::DELETE, local_var_uri_str.as_str()); if let Some(ref local_var_user_agent) = configuration.user_agent { local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); @@ -197,7 +197,7 @@ pub fn get_user_by_name(configuration: &configuration::Configuration, username: let local_var_client = &configuration.client; let local_var_uri_str = format!("{}/user/{username}", configuration.base_path, username=crate::apis::urlencode(username)); - let mut local_var_req_builder = local_var_client.get(local_var_uri_str.as_str()); + let mut local_var_req_builder = local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str()); if let Some(ref local_var_user_agent) = configuration.user_agent { local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); @@ -223,7 +223,7 @@ pub fn login_user(configuration: &configuration::Configuration, username: &str, let local_var_client = &configuration.client; let local_var_uri_str = format!("{}/user/login", configuration.base_path); - let mut local_var_req_builder = local_var_client.get(local_var_uri_str.as_str()); + let mut local_var_req_builder = local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str()); local_var_req_builder = local_var_req_builder.query(&[("username", &username.to_string())]); local_var_req_builder = local_var_req_builder.query(&[("password", &password.to_string())]); @@ -251,7 +251,7 @@ pub fn logout_user(configuration: &configuration::Configuration, ) -> Result<(), let local_var_client = &configuration.client; let local_var_uri_str = format!("{}/user/logout", configuration.base_path); - let mut local_var_req_builder = local_var_client.get(local_var_uri_str.as_str()); + let mut local_var_req_builder = local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str()); if let Some(ref local_var_user_agent) = configuration.user_agent { local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); @@ -278,7 +278,7 @@ pub fn update_user(configuration: &configuration::Configuration, username: &str, let local_var_client = &configuration.client; let local_var_uri_str = format!("{}/user/{username}", configuration.base_path, username=crate::apis::urlencode(username)); - let mut local_var_req_builder = local_var_client.put(local_var_uri_str.as_str()); + let mut local_var_req_builder = local_var_client.request(reqwest::Method::PUT, local_var_uri_str.as_str()); if let Some(ref local_var_user_agent) = configuration.user_agent { local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); diff --git a/samples/client/petstore/scala-akka/.openapi-generator/VERSION b/samples/client/petstore/scala-akka/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/client/petstore/scala-akka/.openapi-generator/VERSION +++ b/samples/client/petstore/scala-akka/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/client/petstore/scala-httpclient-deprecated/.gitignore b/samples/client/petstore/scala-httpclient-deprecated/.gitignore new file mode 100644 index 00000000000..ad2b0d3ecd8 --- /dev/null +++ b/samples/client/petstore/scala-httpclient-deprecated/.gitignore @@ -0,0 +1,22 @@ +# scala specific +*.class +*.log + +# sbt specific +.cache +.history +.lib/ +dist/* +target/ +lib_managed/ +src_managed/ +project/boot/ +project/plugins/project/ + +# Scala-IDE specific +.scala_dependencies +.worksheet + +# IntelliJ specific +.idea +*.iml diff --git a/samples/client/petstore/scala-httpclient-deprecated/.openapi-generator-ignore b/samples/client/petstore/scala-httpclient-deprecated/.openapi-generator-ignore new file mode 100644 index 00000000000..7484ee590a3 --- /dev/null +++ b/samples/client/petstore/scala-httpclient-deprecated/.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-httpclient-deprecated/.openapi-generator/FILES b/samples/client/petstore/scala-httpclient-deprecated/.openapi-generator/FILES new file mode 100644 index 00000000000..77e4ca71c11 --- /dev/null +++ b/samples/client/petstore/scala-httpclient-deprecated/.openapi-generator/FILES @@ -0,0 +1,22 @@ +.gitignore +build.gradle +build.sbt +git_push.sh +gradle.properties +gradle/wrapper/gradle-wrapper.jar +gradle/wrapper/gradle-wrapper.properties +gradlew +gradlew.bat +pom.xml +settings.gradle +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 +src/main/scala/org/openapitools/example/api/PetApi.scala +src/main/scala/org/openapitools/example/api/StoreApi.scala +src/main/scala/org/openapitools/example/api/UserApi.scala +src/main/scala/org/openapitools/example/invoker/ApiInvoker.scala +src/main/scala/org/openapitools/example/invoker/AsyncClient.scala diff --git a/samples/client/petstore/scala-httpclient-deprecated/.openapi-generator/VERSION b/samples/client/petstore/scala-httpclient-deprecated/.openapi-generator/VERSION new file mode 100644 index 00000000000..4b448de535c --- /dev/null +++ b/samples/client/petstore/scala-httpclient-deprecated/.openapi-generator/VERSION @@ -0,0 +1 @@ +5.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/scala-httpclient-deprecated/build.gradle b/samples/client/petstore/scala-httpclient-deprecated/build.gradle new file mode 100644 index 00000000000..d05105184ff --- /dev/null +++ b/samples/client/petstore/scala-httpclient-deprecated/build.gradle @@ -0,0 +1,127 @@ +apply plugin: 'idea' +apply plugin: 'eclipse' + +group = 'org.openapitools' +version = '1.0.0' + +buildscript { + repositories { + jcenter() + } + dependencies { + classpath 'com.android.tools.build:gradle:1.5.+' + classpath 'com.github.dcendents:android-maven-gradle-plugin:1.3' + } +} + +repositories { + jcenter() +} + + +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_7 + targetCompatibility JavaVersion.VERSION_1_7 + } + + // 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 'javax.annotation:jsr250-api:1.0' + } + } + + 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.destinationDir + task.destinationDir = project.file("${project.buildDir}/outputs/jar") + task.archiveName = "${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: 'scala' + apply plugin: 'java' + apply plugin: 'maven' + + sourceCompatibility = JavaVersion.VERSION_1_7 + targetCompatibility = JavaVersion.VERSION_1_7 + + install { + repositories.mavenInstaller { + pom.artifactId = 'scala-legacy-petstore' + } + } + + task execute(type:JavaExec) { + main = System.getProperty('mainClass') + classpath = sourceSets.main.runtimeClasspath + } +} + +ext { + scala_version = "2.10.4" + joda_version = "1.2" + jodatime_version = "2.2" + jersey_version = "1.19" + swagger_core_version = "1.5.8" + jersey_async_version = "1.0.5" + jackson_version = "2.4.2" + junit_version = "4.8.1" + scala_test_version = "2.2.4" + swagger_async_httpclient_version = "0.3.5" +} + +repositories { + mavenLocal() + maven { url "https://repo1.maven.org/maven2" } +} + +dependencies { + compile "com.fasterxml.jackson.module:jackson-module-scala_2.10:$jackson_version" + compile "com.sun.jersey:jersey-client:$jersey_version" + compile "com.sun.jersey.contribs:jersey-multipart:$jersey_version" + compile "org.jfarcand:jersey-ahc-client:$jersey_async_version" + compile "org.scala-lang:scala-library:$scala_version" + compile "io.swagger:swagger-core:$swagger_core_version" + testCompile "org.scalatest:scalatest_2.10:$scala_test_version" + testCompile "junit:junit:$junit_version" + compile "joda-time:joda-time:$jodatime_version" + compile "org.joda:joda-convert:$joda_version" + compile "com.wordnik.swagger:swagger-async-httpclient_2.10:$swagger_async_httpclient_version" +} diff --git a/samples/client/petstore/scala-httpclient-deprecated/build.sbt b/samples/client/petstore/scala-httpclient-deprecated/build.sbt new file mode 100644 index 00000000000..0565bb12ae1 --- /dev/null +++ b/samples/client/petstore/scala-httpclient-deprecated/build.sbt @@ -0,0 +1,32 @@ +version := "1.0.0" +name := "scala-legacy-petstore" +organization := "org.openapitools" +scalaVersion := "2.11.12" + +libraryDependencies ++= Seq( + "com.fasterxml.jackson.module" %% "jackson-module-scala" % "2.9.9", + "com.fasterxml.jackson.datatype" % "jackson-datatype-joda" % "2.9.9", + "com.sun.jersey" % "jersey-core" % "1.19.4", + "com.sun.jersey" % "jersey-client" % "1.19.4", + "com.sun.jersey.contribs" % "jersey-multipart" % "1.19.4", + "org.jfarcand" % "jersey-ahc-client" % "1.0.5", + "io.swagger" % "swagger-core" % "1.5.8", + "joda-time" % "joda-time" % "2.9.9", + "org.joda" % "joda-convert" % "1.9.2", + "org.scalatest" %% "scalatest" % "3.0.4" % "test", + "junit" % "junit" % "4.13" % "test", + "com.wordnik.swagger" %% "swagger-async-httpclient" % "0.3.5" +) + +resolvers ++= Seq( + Resolver.mavenLocal +) + +scalacOptions := Seq( + "-unchecked", + "-deprecation", + "-feature" +) + +publishArtifact in (Compile, packageDoc) := false + diff --git a/samples/client/petstore/scala-httpclient-deprecated/git_push.sh b/samples/client/petstore/scala-httpclient-deprecated/git_push.sh new file mode 100644 index 00000000000..ced3be2b0c7 --- /dev/null +++ b/samples/client/petstore/scala-httpclient-deprecated/git_push.sh @@ -0,0 +1,58 @@ +#!/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-pestore-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/scala-httpclient-deprecated/gradle.properties b/samples/client/petstore/scala-httpclient-deprecated/gradle.properties new file mode 100644 index 00000000000..05644f0754a --- /dev/null +++ b/samples/client/petstore/scala-httpclient-deprecated/gradle.properties @@ -0,0 +1,2 @@ +# Uncomment to build for Android +#target = android \ No newline at end of file diff --git a/samples/client/petstore/scala-httpclient-deprecated/gradle/wrapper/gradle-wrapper.jar b/samples/client/petstore/scala-httpclient-deprecated/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 00000000000..87b738cbd05 Binary files /dev/null and b/samples/client/petstore/scala-httpclient-deprecated/gradle/wrapper/gradle-wrapper.jar differ diff --git a/samples/client/petstore/scala-httpclient-deprecated/gradle/wrapper/gradle-wrapper.properties b/samples/client/petstore/scala-httpclient-deprecated/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 00000000000..e496c054f69 --- /dev/null +++ b/samples/client/petstore/scala-httpclient-deprecated/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-2.14.1-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/samples/client/petstore/scala-httpclient-deprecated/gradlew b/samples/client/petstore/scala-httpclient-deprecated/gradlew new file mode 100644 index 00000000000..af6708ff229 --- /dev/null +++ b/samples/client/petstore/scala-httpclient-deprecated/gradlew @@ -0,0 +1,172 @@ +#!/usr/bin/env sh + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# 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 +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m"' + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn () { + echo "$*" +} + +die () { + echo + echo "$*" + echo + exit 1 +} + +# 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 + ;; +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" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin, switch paths to Windows format before running java +if $cygwin ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=$((i+1)) + done + case $i in + (0) set -- ;; + (1) set -- "$args0" ;; + (2) set -- "$args0" "$args1" ;; + (3) set -- "$args0" "$args1" "$args2" ;; + (4) set -- "$args0" "$args1" "$args2" "$args3" ;; + (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + 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, 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" + +# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong +if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then + cd "$(dirname "$0")" +fi + +exec "$JAVACMD" "$@" diff --git a/samples/client/petstore/scala-httpclient-deprecated/gradlew.bat b/samples/client/petstore/scala-httpclient-deprecated/gradlew.bat new file mode 100644 index 00000000000..f9553162f12 --- /dev/null +++ b/samples/client/petstore/scala-httpclient-deprecated/gradlew.bat @@ -0,0 +1,84 @@ +@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 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= + +@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 init + +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 init + +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 + +:init +@rem Get command-line arguments, handling Windows variants + +if not "%OS%" == "Windows_NT" goto win9xME_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* + +: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 %CMD_LINE_ARGS% + +: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/petstore/scala-httpclient-deprecated/pom.xml b/samples/client/petstore/scala-httpclient-deprecated/pom.xml new file mode 100644 index 00000000000..26ed58c1b59 --- /dev/null +++ b/samples/client/petstore/scala-httpclient-deprecated/pom.xml @@ -0,0 +1,255 @@ + + 4.0.0 + org.openapitools + scala-legacy-petstore + jar + scala-legacy-petstore + 1.0.0 + + + + maven-mongodb-plugin-repo + maven mongodb plugin repository + + https://maven-mongodb-plugin.googlecode.com/svn/maven/repo + default + + + + + + + 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.2 + + + + jar + test-jar + + + + + + + + + org.codehaus.mojo + build-helper-maven-plugin + 1.9.1 + + + 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.6.1 + + 1.7 + 1.7 + + + + 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 + + + + + + -Xms128m + -Xmx1500m + + + + + + + + + org.scala-tools + maven-scala-plugin + + ${scala-version} + + + + + + + com.fasterxml.jackson.module + jackson-module-scala_2.11 + ${jackson-version} + + + com.fasterxml.jackson.datatype + jackson-datatype-joda + ${jackson-version} + + + com.sun.jersey + jersey-client + ${jersey-version} + + + com.sun.jersey.contribs + jersey-multipart + ${jersey-version} + + + org.jfarcand + jersey-ahc-client + ${jersey-async-version} + compile + + + org.scala-lang + scala-library + ${scala-version} + + + io.swagger + swagger-core + ${swagger-core-version} + + + org.scalatest + scalatest_2.11 + ${scala-test-version} + test + + + junit + junit + ${junit-version} + test + + + joda-time + joda-time + ${joda-time-version} + + + org.joda + joda-convert + ${joda-version} + + + com.wordnik.swagger + swagger-async-httpclient_2.11 + ${async-httpclient-version} + + + + 2.11.12 + 1.9.2 + 2.9.9 + 1.19.4 + 1.5.18 + 1.0.5 + 1.0.0 + 2.9.9 + + 4.13 + 3.1.5 + 3.0.4 + 0.3.5 + + UTF-8 + + diff --git a/samples/client/petstore/scala-httpclient-deprecated/project/build.properties b/samples/client/petstore/scala-httpclient-deprecated/project/build.properties new file mode 100644 index 00000000000..c0bab04941d --- /dev/null +++ b/samples/client/petstore/scala-httpclient-deprecated/project/build.properties @@ -0,0 +1 @@ +sbt.version=1.2.8 diff --git a/samples/client/petstore/scala-httpclient-deprecated/settings.gradle b/samples/client/petstore/scala-httpclient-deprecated/settings.gradle new file mode 100644 index 00000000000..526dd2d0ab4 --- /dev/null +++ b/samples/client/petstore/scala-httpclient-deprecated/settings.gradle @@ -0,0 +1 @@ +rootProject.name = "scala-legacy-petstore" \ No newline at end of file diff --git a/samples/client/petstore/scala-httpclient-deprecated/src/main/scala/org/openapitools/client/model/ApiResponse.scala b/samples/client/petstore/scala-httpclient-deprecated/src/main/scala/org/openapitools/client/model/ApiResponse.scala new file mode 100644 index 00000000000..be741231329 --- /dev/null +++ b/samples/client/petstore/scala-httpclient-deprecated/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 + + +case class ApiResponse ( + code: Option[Integer] = None, + `type`: Option[String] = None, + message: Option[String] = None +) + diff --git a/samples/client/petstore/scala-httpclient-deprecated/src/main/scala/org/openapitools/client/model/Category.scala b/samples/client/petstore/scala-httpclient-deprecated/src/main/scala/org/openapitools/client/model/Category.scala new file mode 100644 index 00000000000..be3307b8f8e --- /dev/null +++ b/samples/client/petstore/scala-httpclient-deprecated/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 + + +case class Category ( + id: Option[Long] = None, + name: Option[String] = None +) + diff --git a/samples/client/petstore/scala-httpclient-deprecated/src/main/scala/org/openapitools/client/model/Order.scala b/samples/client/petstore/scala-httpclient-deprecated/src/main/scala/org/openapitools/client/model/Order.scala new file mode 100644 index 00000000000..d0ca63b5091 --- /dev/null +++ b/samples/client/petstore/scala-httpclient-deprecated/src/main/scala/org/openapitools/client/model/Order.scala @@ -0,0 +1,26 @@ +/** + * 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 + +case class Order ( + id: Option[Long] = None, + petId: Option[Long] = None, + quantity: Option[Integer] = None, + shipDate: Option[Date] = None, + // Order Status + status: Option[String] = None, + complete: Option[Boolean] = None +) + diff --git a/samples/client/petstore/scala-httpclient-deprecated/src/main/scala/org/openapitools/client/model/Pet.scala b/samples/client/petstore/scala-httpclient-deprecated/src/main/scala/org/openapitools/client/model/Pet.scala new file mode 100644 index 00000000000..2de76ae3588 --- /dev/null +++ b/samples/client/petstore/scala-httpclient-deprecated/src/main/scala/org/openapitools/client/model/Pet.scala @@ -0,0 +1,25 @@ +/** + * 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 + + +case class Pet ( + id: Option[Long] = None, + category: Option[Category] = None, + name: String, + photoUrls: List[String], + tags: Option[List[Tag]] = None, + // pet status in the store + status: Option[String] = None +) + diff --git a/samples/client/petstore/scala-httpclient-deprecated/src/main/scala/org/openapitools/client/model/Tag.scala b/samples/client/petstore/scala-httpclient-deprecated/src/main/scala/org/openapitools/client/model/Tag.scala new file mode 100644 index 00000000000..6fbabf7ed63 --- /dev/null +++ b/samples/client/petstore/scala-httpclient-deprecated/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 + + +case class Tag ( + id: Option[Long] = None, + name: Option[String] = None +) + diff --git a/samples/client/petstore/scala-httpclient-deprecated/src/main/scala/org/openapitools/client/model/User.scala b/samples/client/petstore/scala-httpclient-deprecated/src/main/scala/org/openapitools/client/model/User.scala new file mode 100644 index 00000000000..fc24b101e8b --- /dev/null +++ b/samples/client/petstore/scala-httpclient-deprecated/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 + + +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[Integer] = None +) + diff --git a/samples/client/petstore/scala-httpclient-deprecated/src/main/scala/org/openapitools/example/api/PetApi.scala b/samples/client/petstore/scala-httpclient-deprecated/src/main/scala/org/openapitools/example/api/PetApi.scala new file mode 100644 index 00000000000..bb58587307e --- /dev/null +++ b/samples/client/petstore/scala-httpclient-deprecated/src/main/scala/org/openapitools/example/api/PetApi.scala @@ -0,0 +1,476 @@ +/** + * 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.example.api + +import java.text.SimpleDateFormat + +import org.openapitools.client.model.ApiResponse +import java.io.File +import org.openapitools.client.model.Pet +import org.openapitools.example.invoker.{ApiInvoker, ApiException} + +import collection.mutable +import com.sun.jersey.multipart.FormDataMultiPart +import com.sun.jersey.multipart.file.FileDataBodyPart +import com.wordnik.swagger.client._ +import com.wordnik.swagger.client.ClientResponseReaders.Json4sFormatsReader._ +import com.wordnik.swagger.client.RequestWriters.Json4sFormatsWriter._ +import javax.ws.rs.core.Response.Status.Family + +import java.net.URI +import java.io.File +import java.util.Date +import java.util.TimeZone +import javax.ws.rs.core.{MediaType, Response} + +import scala.concurrent.ExecutionContext.Implicits.global +import scala.concurrent._ +import scala.concurrent.duration._ +import scala.collection.mutable.HashMap +import scala.util.{Failure, Success, Try} + +import org.json4s._ + +class PetApi( + val defBasePath: String = "http://petstore.swagger.io/v2", + defApiInvoker: ApiInvoker = ApiInvoker +) { + private lazy val dateTimeFormatter = { + val formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ") + formatter.setTimeZone(TimeZone.getTimeZone("UTC")) + formatter + } + private val dateFormatter = { + val formatter = new SimpleDateFormat("yyyy-MM-dd") + formatter.setTimeZone(TimeZone.getTimeZone("UTC")) + formatter + } + implicit val formats = new org.json4s.DefaultFormats { + override def dateFormatter = dateTimeFormatter + } + implicit val stringReader: ClientResponseReader[String] = ClientResponseReaders.StringReader + implicit val unitReader: ClientResponseReader[Unit] = ClientResponseReaders.UnitReader + implicit val jvalueReader: ClientResponseReader[JValue] = ClientResponseReaders.JValueReader + implicit val jsonReader: ClientResponseReader[Nothing] = JsonFormatsReader + implicit val stringWriter: RequestWriter[String] = RequestWriters.StringWriter + implicit val jsonWriter: RequestWriter[Nothing] = JsonFormatsWriter + + var basePath: String = defBasePath + var apiInvoker: ApiInvoker = defApiInvoker + + def addHeader(key: String, value: String): mutable.HashMap[String, String] = { + apiInvoker.defaultHeaders += key -> value + } + + val config: SwaggerConfig = SwaggerConfig.forUrl(new URI(defBasePath)) + val client = new RestClient(config) + val helper = new PetApiAsyncHelper(client, config) + + /** + * Add a new pet to the store + * + * + * @param pet Pet object that needs to be added to the store + * @return Pet + */ + def addPet(pet: Pet): Option[Pet] = { + val await = Try(Await.result(addPetAsync(pet), Duration.Inf)) + await match { + case Success(i) => Some(await.get) + case Failure(t) => None + } + } + + /** + * Add a new pet to the store asynchronously + * + * + * @param pet Pet object that needs to be added to the store + * @return Future(Pet) + */ + def addPetAsync(pet: Pet): Future[Pet] = { + helper.addPet(pet) + } + + /** + * Deletes a pet + * + * + * @param petId Pet id to delete + * @param apiKey (optional) + * @return void + */ + def deletePet(petId: Long, apiKey: Option[String] = None) = { + val await = Try(Await.result(deletePetAsync(petId, apiKey), Duration.Inf)) + await match { + case Success(i) => Some(await.get) + case Failure(t) => None + } + } + + /** + * Deletes a pet asynchronously + * + * + * @param petId Pet id to delete + * @param apiKey (optional) + * @return Future(void) + */ + def deletePetAsync(petId: Long, apiKey: Option[String] = None) = { + helper.deletePet(petId, apiKey) + } + + /** + * 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 List[Pet] + */ + def findPetsByStatus(status: List[String]): Option[List[Pet]] = { + val await = Try(Await.result(findPetsByStatusAsync(status), Duration.Inf)) + await match { + case Success(i) => Some(await.get) + case Failure(t) => None + } + } + + /** + * Finds Pets by status asynchronously + * Multiple status values can be provided with comma separated strings + * + * @param status Status values that need to be considered for filter + * @return Future(List[Pet]) + */ + def findPetsByStatusAsync(status: List[String]): Future[List[Pet]] = { + helper.findPetsByStatus(status) + } + + /** + * 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 List[Pet] + */ + def findPetsByTags(tags: List[String]): Option[List[Pet]] = { + val await = Try(Await.result(findPetsByTagsAsync(tags), Duration.Inf)) + await match { + case Success(i) => Some(await.get) + case Failure(t) => None + } + } + + /** + * Finds Pets by tags asynchronously + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + * + * @param tags Tags to filter by + * @return Future(List[Pet]) + */ + def findPetsByTagsAsync(tags: List[String]): Future[List[Pet]] = { + helper.findPetsByTags(tags) + } + + /** + * Find pet by ID + * Returns a single pet + * + * @param petId ID of pet to return + * @return Pet + */ + def getPetById(petId: Long): Option[Pet] = { + val await = Try(Await.result(getPetByIdAsync(petId), Duration.Inf)) + await match { + case Success(i) => Some(await.get) + case Failure(t) => None + } + } + + /** + * Find pet by ID asynchronously + * Returns a single pet + * + * @param petId ID of pet to return + * @return Future(Pet) + */ + def getPetByIdAsync(petId: Long): Future[Pet] = { + helper.getPetById(petId) + } + + /** + * Update an existing pet + * + * + * @param pet Pet object that needs to be added to the store + * @return Pet + */ + def updatePet(pet: Pet): Option[Pet] = { + val await = Try(Await.result(updatePetAsync(pet), Duration.Inf)) + await match { + case Success(i) => Some(await.get) + case Failure(t) => None + } + } + + /** + * Update an existing pet asynchronously + * + * + * @param pet Pet object that needs to be added to the store + * @return Future(Pet) + */ + def updatePetAsync(pet: Pet): Future[Pet] = { + helper.updatePet(pet) + } + + /** + * 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 + */ + def updatePetWithForm(petId: Long, name: Option[String] = None, status: Option[String] = None) = { + val await = Try(Await.result(updatePetWithFormAsync(petId, name, status), Duration.Inf)) + await match { + case Success(i) => Some(await.get) + case Failure(t) => None + } + } + + /** + * Updates a pet in the store with form data asynchronously + * + * + * @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 Future(void) + */ + def updatePetWithFormAsync(petId: Long, name: Option[String] = None, status: Option[String] = None) = { + helper.updatePetWithForm(petId, name, status) + } + + /** + * 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 + */ + def uploadFile(petId: Long, additionalMetadata: Option[String] = None, file: Option[File] = None): Option[ApiResponse] = { + val await = Try(Await.result(uploadFileAsync(petId, additionalMetadata, file), Duration.Inf)) + await match { + case Success(i) => Some(await.get) + case Failure(t) => None + } + } + + /** + * uploads an image asynchronously + * + * + * @param petId ID of pet to update + * @param additionalMetadata Additional data to pass to server (optional) + * @param file file to upload (optional) + * @return Future(ApiResponse) + */ + def uploadFileAsync(petId: Long, additionalMetadata: Option[String] = None, file: Option[File] = None): Future[ApiResponse] = { + helper.uploadFile(petId, additionalMetadata, file) + } + +} + +class PetApiAsyncHelper(client: TransportClient, config: SwaggerConfig) extends ApiClient(client, config) { + + def addPet(pet: Pet)(implicit reader: ClientResponseReader[Pet], writer: RequestWriter[Pet]): Future[Pet] = { + // create path and map variables + val path = (addFmt("/pet")) + + // query params + val queryParams = new mutable.HashMap[String, String] + val headerParams = new mutable.HashMap[String, String] + + if (pet == null) throw new Exception("Missing required parameter 'pet' when calling PetApi->addPet") + + val resFuture = client.submit("POST", path, queryParams.toMap, headerParams.toMap, writer.write(pet)) + resFuture flatMap { resp => + val status = Response.Status.fromStatusCode(resp.statusCode) + status.getFamily match { + case Family.SUCCESSFUL | Family.REDIRECTION | Family.INFORMATIONAL => process(reader.read(resp)) + case _ => throw new ApiException(resp.statusCode, resp.statusText) + } + } + } + + def deletePet(petId: Long, + apiKey: Option[String] = None + )(implicit reader: ClientResponseReader[Unit]): Future[Unit] = { + // create path and map variables + val path = (addFmt("/pet/{petId}") + replaceAll("\\{" + "petId" + "\\}", petId.toString)) + + // query params + val queryParams = new mutable.HashMap[String, String] + val headerParams = new mutable.HashMap[String, String] + + apiKey match { + case Some(param) => headerParams += "api_key" -> param.toString + case _ => headerParams + } + + val resFuture = client.submit("DELETE", path, queryParams.toMap, headerParams.toMap, "") + resFuture flatMap { resp => + val status = Response.Status.fromStatusCode(resp.statusCode) + status.getFamily match { + case Family.SUCCESSFUL | Family.REDIRECTION | Family.INFORMATIONAL => process(reader.read(resp)) + case _ => throw new ApiException(resp.statusCode, resp.statusText) + } + } + } + + def findPetsByStatus(status: List[String])(implicit reader: ClientResponseReader[List[Pet]]): Future[List[Pet]] = { + // create path and map variables + val path = (addFmt("/pet/findByStatus")) + + // query params + val queryParams = new mutable.HashMap[String, String] + val headerParams = new mutable.HashMap[String, String] + + if (status == null) throw new Exception("Missing required parameter 'status' when calling PetApi->findPetsByStatus") + queryParams += "status" -> status.toString + + val resFuture = client.submit("GET", path, queryParams.toMap, headerParams.toMap, "") + resFuture flatMap { resp => + val status = Response.Status.fromStatusCode(resp.statusCode) + status.getFamily match { + case Family.SUCCESSFUL | Family.REDIRECTION | Family.INFORMATIONAL => process(reader.read(resp)) + case _ => throw new ApiException(resp.statusCode, resp.statusText) + } + } + } + + def findPetsByTags(tags: List[String])(implicit reader: ClientResponseReader[List[Pet]]): Future[List[Pet]] = { + // create path and map variables + val path = (addFmt("/pet/findByTags")) + + // query params + val queryParams = new mutable.HashMap[String, String] + val headerParams = new mutable.HashMap[String, String] + + if (tags == null) throw new Exception("Missing required parameter 'tags' when calling PetApi->findPetsByTags") + queryParams += "tags" -> tags.toString + + val resFuture = client.submit("GET", path, queryParams.toMap, headerParams.toMap, "") + resFuture flatMap { resp => + val status = Response.Status.fromStatusCode(resp.statusCode) + status.getFamily match { + case Family.SUCCESSFUL | Family.REDIRECTION | Family.INFORMATIONAL => process(reader.read(resp)) + case _ => throw new ApiException(resp.statusCode, resp.statusText) + } + } + } + + def getPetById(petId: Long)(implicit reader: ClientResponseReader[Pet]): Future[Pet] = { + // create path and map variables + val path = (addFmt("/pet/{petId}") + replaceAll("\\{" + "petId" + "\\}", petId.toString)) + + // query params + val queryParams = new mutable.HashMap[String, String] + val headerParams = new mutable.HashMap[String, String] + + + val resFuture = client.submit("GET", path, queryParams.toMap, headerParams.toMap, "") + resFuture flatMap { resp => + val status = Response.Status.fromStatusCode(resp.statusCode) + status.getFamily match { + case Family.SUCCESSFUL | Family.REDIRECTION | Family.INFORMATIONAL => process(reader.read(resp)) + case _ => throw new ApiException(resp.statusCode, resp.statusText) + } + } + } + + def updatePet(pet: Pet)(implicit reader: ClientResponseReader[Pet], writer: RequestWriter[Pet]): Future[Pet] = { + // create path and map variables + val path = (addFmt("/pet")) + + // query params + val queryParams = new mutable.HashMap[String, String] + val headerParams = new mutable.HashMap[String, String] + + if (pet == null) throw new Exception("Missing required parameter 'pet' when calling PetApi->updatePet") + + val resFuture = client.submit("PUT", path, queryParams.toMap, headerParams.toMap, writer.write(pet)) + resFuture flatMap { resp => + val status = Response.Status.fromStatusCode(resp.statusCode) + status.getFamily match { + case Family.SUCCESSFUL | Family.REDIRECTION | Family.INFORMATIONAL => process(reader.read(resp)) + case _ => throw new ApiException(resp.statusCode, resp.statusText) + } + } + } + + def updatePetWithForm(petId: Long, + name: Option[String] = None, + status: Option[String] = None + )(implicit reader: ClientResponseReader[Unit]): Future[Unit] = { + // create path and map variables + val path = (addFmt("/pet/{petId}") + replaceAll("\\{" + "petId" + "\\}", petId.toString)) + + // query params + val queryParams = new mutable.HashMap[String, String] + val headerParams = new mutable.HashMap[String, String] + + + val resFuture = client.submit("POST", path, queryParams.toMap, headerParams.toMap, "") + resFuture flatMap { resp => + val status = Response.Status.fromStatusCode(resp.statusCode) + status.getFamily match { + case Family.SUCCESSFUL | Family.REDIRECTION | Family.INFORMATIONAL => process(reader.read(resp)) + case _ => throw new ApiException(resp.statusCode, resp.statusText) + } + } + } + + def uploadFile(petId: Long, + additionalMetadata: Option[String] = None, + file: Option[File] = None + )(implicit reader: ClientResponseReader[ApiResponse]): Future[ApiResponse] = { + // create path and map variables + val path = (addFmt("/pet/{petId}/uploadImage") + replaceAll("\\{" + "petId" + "\\}", petId.toString)) + + // query params + val queryParams = new mutable.HashMap[String, String] + val headerParams = new mutable.HashMap[String, String] + + + val resFuture = client.submit("POST", path, queryParams.toMap, headerParams.toMap, "") + resFuture flatMap { resp => + val status = Response.Status.fromStatusCode(resp.statusCode) + status.getFamily match { + case Family.SUCCESSFUL | Family.REDIRECTION | Family.INFORMATIONAL => process(reader.read(resp)) + case _ => throw new ApiException(resp.statusCode, resp.statusText) + } + } + } + + +} diff --git a/samples/client/petstore/scala-httpclient-deprecated/src/main/scala/org/openapitools/example/api/StoreApi.scala b/samples/client/petstore/scala-httpclient-deprecated/src/main/scala/org/openapitools/example/api/StoreApi.scala new file mode 100644 index 00000000000..949585575e9 --- /dev/null +++ b/samples/client/petstore/scala-httpclient-deprecated/src/main/scala/org/openapitools/example/api/StoreApi.scala @@ -0,0 +1,265 @@ +/** + * 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.example.api + +import java.text.SimpleDateFormat + +import org.openapitools.client.model.Order +import org.openapitools.example.invoker.{ApiInvoker, ApiException} + +import collection.mutable +import com.sun.jersey.multipart.FormDataMultiPart +import com.sun.jersey.multipart.file.FileDataBodyPart +import com.wordnik.swagger.client._ +import com.wordnik.swagger.client.ClientResponseReaders.Json4sFormatsReader._ +import com.wordnik.swagger.client.RequestWriters.Json4sFormatsWriter._ +import javax.ws.rs.core.Response.Status.Family + +import java.net.URI +import java.io.File +import java.util.Date +import java.util.TimeZone +import javax.ws.rs.core.{MediaType, Response} + +import scala.concurrent.ExecutionContext.Implicits.global +import scala.concurrent._ +import scala.concurrent.duration._ +import scala.collection.mutable.HashMap +import scala.util.{Failure, Success, Try} + +import org.json4s._ + +class StoreApi( + val defBasePath: String = "http://petstore.swagger.io/v2", + defApiInvoker: ApiInvoker = ApiInvoker +) { + private lazy val dateTimeFormatter = { + val formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ") + formatter.setTimeZone(TimeZone.getTimeZone("UTC")) + formatter + } + private val dateFormatter = { + val formatter = new SimpleDateFormat("yyyy-MM-dd") + formatter.setTimeZone(TimeZone.getTimeZone("UTC")) + formatter + } + implicit val formats = new org.json4s.DefaultFormats { + override def dateFormatter = dateTimeFormatter + } + implicit val stringReader: ClientResponseReader[String] = ClientResponseReaders.StringReader + implicit val unitReader: ClientResponseReader[Unit] = ClientResponseReaders.UnitReader + implicit val jvalueReader: ClientResponseReader[JValue] = ClientResponseReaders.JValueReader + implicit val jsonReader: ClientResponseReader[Nothing] = JsonFormatsReader + implicit val stringWriter: RequestWriter[String] = RequestWriters.StringWriter + implicit val jsonWriter: RequestWriter[Nothing] = JsonFormatsWriter + + var basePath: String = defBasePath + var apiInvoker: ApiInvoker = defApiInvoker + + def addHeader(key: String, value: String): mutable.HashMap[String, String] = { + apiInvoker.defaultHeaders += key -> value + } + + val config: SwaggerConfig = SwaggerConfig.forUrl(new URI(defBasePath)) + val client = new RestClient(config) + val helper = new StoreApiAsyncHelper(client, config) + + /** + * 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 + */ + def deleteOrder(orderId: String) = { + val await = Try(Await.result(deleteOrderAsync(orderId), Duration.Inf)) + await match { + case Success(i) => Some(await.get) + case Failure(t) => None + } + } + + /** + * Delete purchase order by ID asynchronously + * 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 Future(void) + */ + def deleteOrderAsync(orderId: String) = { + helper.deleteOrder(orderId) + } + + /** + * Returns pet inventories by status + * Returns a map of status codes to quantities + * + * @return Map[String, Integer] + */ + def getInventory(): Option[Map[String, Integer]] = { + val await = Try(Await.result(getInventoryAsync(), Duration.Inf)) + await match { + case Success(i) => Some(await.get) + case Failure(t) => None + } + } + + /** + * Returns pet inventories by status asynchronously + * Returns a map of status codes to quantities + * + * @return Future(Map[String, Integer]) + */ + def getInventoryAsync(): Future[Map[String, Integer]] = { + helper.getInventory() + } + + /** + * Find purchase order by ID + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + * + * @param orderId ID of pet that needs to be fetched + * @return Order + */ + def getOrderById(orderId: Long): Option[Order] = { + val await = Try(Await.result(getOrderByIdAsync(orderId), Duration.Inf)) + await match { + case Success(i) => Some(await.get) + case Failure(t) => None + } + } + + /** + * Find purchase order by ID asynchronously + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + * + * @param orderId ID of pet that needs to be fetched + * @return Future(Order) + */ + def getOrderByIdAsync(orderId: Long): Future[Order] = { + helper.getOrderById(orderId) + } + + /** + * Place an order for a pet + * + * + * @param order order placed for purchasing the pet + * @return Order + */ + def placeOrder(order: Order): Option[Order] = { + val await = Try(Await.result(placeOrderAsync(order), Duration.Inf)) + await match { + case Success(i) => Some(await.get) + case Failure(t) => None + } + } + + /** + * Place an order for a pet asynchronously + * + * + * @param order order placed for purchasing the pet + * @return Future(Order) + */ + def placeOrderAsync(order: Order): Future[Order] = { + helper.placeOrder(order) + } + +} + +class StoreApiAsyncHelper(client: TransportClient, config: SwaggerConfig) extends ApiClient(client, config) { + + def deleteOrder(orderId: String)(implicit reader: ClientResponseReader[Unit]): Future[Unit] = { + // create path and map variables + val path = (addFmt("/store/order/{orderId}") + replaceAll("\\{" + "orderId" + "\\}", orderId.toString)) + + // query params + val queryParams = new mutable.HashMap[String, String] + val headerParams = new mutable.HashMap[String, String] + + if (orderId == null) throw new Exception("Missing required parameter 'orderId' when calling StoreApi->deleteOrder") + + + val resFuture = client.submit("DELETE", path, queryParams.toMap, headerParams.toMap, "") + resFuture flatMap { resp => + val status = Response.Status.fromStatusCode(resp.statusCode) + status.getFamily match { + case Family.SUCCESSFUL | Family.REDIRECTION | Family.INFORMATIONAL => process(reader.read(resp)) + case _ => throw new ApiException(resp.statusCode, resp.statusText) + } + } + } + + def getInventory()(implicit reader: ClientResponseReader[Map[String, Integer]]): Future[Map[String, Integer]] = { + // create path and map variables + val path = (addFmt("/store/inventory")) + + // query params + val queryParams = new mutable.HashMap[String, String] + val headerParams = new mutable.HashMap[String, String] + + + val resFuture = client.submit("GET", path, queryParams.toMap, headerParams.toMap, "") + resFuture flatMap { resp => + val status = Response.Status.fromStatusCode(resp.statusCode) + status.getFamily match { + case Family.SUCCESSFUL | Family.REDIRECTION | Family.INFORMATIONAL => process(reader.read(resp)) + case _ => throw new ApiException(resp.statusCode, resp.statusText) + } + } + } + + def getOrderById(orderId: Long)(implicit reader: ClientResponseReader[Order]): Future[Order] = { + // create path and map variables + val path = (addFmt("/store/order/{orderId}") + replaceAll("\\{" + "orderId" + "\\}", orderId.toString)) + + // query params + val queryParams = new mutable.HashMap[String, String] + val headerParams = new mutable.HashMap[String, String] + + + val resFuture = client.submit("GET", path, queryParams.toMap, headerParams.toMap, "") + resFuture flatMap { resp => + val status = Response.Status.fromStatusCode(resp.statusCode) + status.getFamily match { + case Family.SUCCESSFUL | Family.REDIRECTION | Family.INFORMATIONAL => process(reader.read(resp)) + case _ => throw new ApiException(resp.statusCode, resp.statusText) + } + } + } + + def placeOrder(order: Order)(implicit reader: ClientResponseReader[Order], writer: RequestWriter[Order]): Future[Order] = { + // create path and map variables + val path = (addFmt("/store/order")) + + // query params + val queryParams = new mutable.HashMap[String, String] + val headerParams = new mutable.HashMap[String, String] + + if (order == null) throw new Exception("Missing required parameter 'order' when calling StoreApi->placeOrder") + + val resFuture = client.submit("POST", path, queryParams.toMap, headerParams.toMap, writer.write(order)) + resFuture flatMap { resp => + val status = Response.Status.fromStatusCode(resp.statusCode) + status.getFamily match { + case Family.SUCCESSFUL | Family.REDIRECTION | Family.INFORMATIONAL => process(reader.read(resp)) + case _ => throw new ApiException(resp.statusCode, resp.statusText) + } + } + } + + +} diff --git a/samples/client/petstore/scala-httpclient-deprecated/src/main/scala/org/openapitools/example/api/UserApi.scala b/samples/client/petstore/scala-httpclient-deprecated/src/main/scala/org/openapitools/example/api/UserApi.scala new file mode 100644 index 00000000000..d39a90e5741 --- /dev/null +++ b/samples/client/petstore/scala-httpclient-deprecated/src/main/scala/org/openapitools/example/api/UserApi.scala @@ -0,0 +1,465 @@ +/** + * 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.example.api + +import java.text.SimpleDateFormat + +import org.openapitools.client.model.User +import org.openapitools.example.invoker.{ApiInvoker, ApiException} + +import collection.mutable +import com.sun.jersey.multipart.FormDataMultiPart +import com.sun.jersey.multipart.file.FileDataBodyPart +import com.wordnik.swagger.client._ +import com.wordnik.swagger.client.ClientResponseReaders.Json4sFormatsReader._ +import com.wordnik.swagger.client.RequestWriters.Json4sFormatsWriter._ +import javax.ws.rs.core.Response.Status.Family + +import java.net.URI +import java.io.File +import java.util.Date +import java.util.TimeZone +import javax.ws.rs.core.{MediaType, Response} + +import scala.concurrent.ExecutionContext.Implicits.global +import scala.concurrent._ +import scala.concurrent.duration._ +import scala.collection.mutable.HashMap +import scala.util.{Failure, Success, Try} + +import org.json4s._ + +class UserApi( + val defBasePath: String = "http://petstore.swagger.io/v2", + defApiInvoker: ApiInvoker = ApiInvoker +) { + private lazy val dateTimeFormatter = { + val formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ") + formatter.setTimeZone(TimeZone.getTimeZone("UTC")) + formatter + } + private val dateFormatter = { + val formatter = new SimpleDateFormat("yyyy-MM-dd") + formatter.setTimeZone(TimeZone.getTimeZone("UTC")) + formatter + } + implicit val formats = new org.json4s.DefaultFormats { + override def dateFormatter = dateTimeFormatter + } + implicit val stringReader: ClientResponseReader[String] = ClientResponseReaders.StringReader + implicit val unitReader: ClientResponseReader[Unit] = ClientResponseReaders.UnitReader + implicit val jvalueReader: ClientResponseReader[JValue] = ClientResponseReaders.JValueReader + implicit val jsonReader: ClientResponseReader[Nothing] = JsonFormatsReader + implicit val stringWriter: RequestWriter[String] = RequestWriters.StringWriter + implicit val jsonWriter: RequestWriter[Nothing] = JsonFormatsWriter + + var basePath: String = defBasePath + var apiInvoker: ApiInvoker = defApiInvoker + + def addHeader(key: String, value: String): mutable.HashMap[String, String] = { + apiInvoker.defaultHeaders += key -> value + } + + val config: SwaggerConfig = SwaggerConfig.forUrl(new URI(defBasePath)) + val client = new RestClient(config) + val helper = new UserApiAsyncHelper(client, config) + + /** + * Create user + * This can only be done by the logged in user. + * + * @param user Created user object + * @return void + */ + def createUser(user: User) = { + val await = Try(Await.result(createUserAsync(user), Duration.Inf)) + await match { + case Success(i) => Some(await.get) + case Failure(t) => None + } + } + + /** + * Create user asynchronously + * This can only be done by the logged in user. + * + * @param user Created user object + * @return Future(void) + */ + def createUserAsync(user: User) = { + helper.createUser(user) + } + + /** + * Creates list of users with given input array + * + * + * @param user List of user object + * @return void + */ + def createUsersWithArrayInput(user: List[User]) = { + val await = Try(Await.result(createUsersWithArrayInputAsync(user), Duration.Inf)) + await match { + case Success(i) => Some(await.get) + case Failure(t) => None + } + } + + /** + * Creates list of users with given input array asynchronously + * + * + * @param user List of user object + * @return Future(void) + */ + def createUsersWithArrayInputAsync(user: List[User]) = { + helper.createUsersWithArrayInput(user) + } + + /** + * Creates list of users with given input array + * + * + * @param user List of user object + * @return void + */ + def createUsersWithListInput(user: List[User]) = { + val await = Try(Await.result(createUsersWithListInputAsync(user), Duration.Inf)) + await match { + case Success(i) => Some(await.get) + case Failure(t) => None + } + } + + /** + * Creates list of users with given input array asynchronously + * + * + * @param user List of user object + * @return Future(void) + */ + def createUsersWithListInputAsync(user: List[User]) = { + helper.createUsersWithListInput(user) + } + + /** + * Delete user + * This can only be done by the logged in user. + * + * @param username The name that needs to be deleted + * @return void + */ + def deleteUser(username: String) = { + val await = Try(Await.result(deleteUserAsync(username), Duration.Inf)) + await match { + case Success(i) => Some(await.get) + case Failure(t) => None + } + } + + /** + * Delete user asynchronously + * This can only be done by the logged in user. + * + * @param username The name that needs to be deleted + * @return Future(void) + */ + def deleteUserAsync(username: String) = { + helper.deleteUser(username) + } + + /** + * Get user by user name + * + * + * @param username The name that needs to be fetched. Use user1 for testing. + * @return User + */ + def getUserByName(username: String): Option[User] = { + val await = Try(Await.result(getUserByNameAsync(username), Duration.Inf)) + await match { + case Success(i) => Some(await.get) + case Failure(t) => None + } + } + + /** + * Get user by user name asynchronously + * + * + * @param username The name that needs to be fetched. Use user1 for testing. + * @return Future(User) + */ + def getUserByNameAsync(username: String): Future[User] = { + helper.getUserByName(username) + } + + /** + * Logs user into the system + * + * + * @param username The user name for login + * @param password The password for login in clear text + * @return String + */ + def loginUser(username: String, password: String): Option[String] = { + val await = Try(Await.result(loginUserAsync(username, password), Duration.Inf)) + await match { + case Success(i) => Some(await.get) + case Failure(t) => None + } + } + + /** + * Logs user into the system asynchronously + * + * + * @param username The user name for login + * @param password The password for login in clear text + * @return Future(String) + */ + def loginUserAsync(username: String, password: String): Future[String] = { + helper.loginUser(username, password) + } + + /** + * Logs out current logged in user session + * + * + * @return void + */ + def logoutUser() = { + val await = Try(Await.result(logoutUserAsync(), Duration.Inf)) + await match { + case Success(i) => Some(await.get) + case Failure(t) => None + } + } + + /** + * Logs out current logged in user session asynchronously + * + * + * @return Future(void) + */ + def logoutUserAsync() = { + helper.logoutUser() + } + + /** + * Updated user + * This can only be done by the logged in user. + * + * @param username name that need to be deleted + * @param user Updated user object + * @return void + */ + def updateUser(username: String, user: User) = { + val await = Try(Await.result(updateUserAsync(username, user), Duration.Inf)) + await match { + case Success(i) => Some(await.get) + case Failure(t) => None + } + } + + /** + * Updated user asynchronously + * This can only be done by the logged in user. + * + * @param username name that need to be deleted + * @param user Updated user object + * @return Future(void) + */ + def updateUserAsync(username: String, user: User) = { + helper.updateUser(username, user) + } + +} + +class UserApiAsyncHelper(client: TransportClient, config: SwaggerConfig) extends ApiClient(client, config) { + + def createUser(user: User)(implicit reader: ClientResponseReader[Unit], writer: RequestWriter[User]): Future[Unit] = { + // create path and map variables + val path = (addFmt("/user")) + + // query params + val queryParams = new mutable.HashMap[String, String] + val headerParams = new mutable.HashMap[String, String] + + if (user == null) throw new Exception("Missing required parameter 'user' when calling UserApi->createUser") + + val resFuture = client.submit("POST", path, queryParams.toMap, headerParams.toMap, writer.write(user)) + resFuture flatMap { resp => + val status = Response.Status.fromStatusCode(resp.statusCode) + status.getFamily match { + case Family.SUCCESSFUL | Family.REDIRECTION | Family.INFORMATIONAL => process(reader.read(resp)) + case _ => throw new ApiException(resp.statusCode, resp.statusText) + } + } + } + + def createUsersWithArrayInput(user: List[User])(implicit reader: ClientResponseReader[Unit], writer: RequestWriter[List[User]]): Future[Unit] = { + // create path and map variables + val path = (addFmt("/user/createWithArray")) + + // query params + val queryParams = new mutable.HashMap[String, String] + val headerParams = new mutable.HashMap[String, String] + + if (user == null) throw new Exception("Missing required parameter 'user' when calling UserApi->createUsersWithArrayInput") + + val resFuture = client.submit("POST", path, queryParams.toMap, headerParams.toMap, writer.write(user)) + resFuture flatMap { resp => + val status = Response.Status.fromStatusCode(resp.statusCode) + status.getFamily match { + case Family.SUCCESSFUL | Family.REDIRECTION | Family.INFORMATIONAL => process(reader.read(resp)) + case _ => throw new ApiException(resp.statusCode, resp.statusText) + } + } + } + + def createUsersWithListInput(user: List[User])(implicit reader: ClientResponseReader[Unit], writer: RequestWriter[List[User]]): Future[Unit] = { + // create path and map variables + val path = (addFmt("/user/createWithList")) + + // query params + val queryParams = new mutable.HashMap[String, String] + val headerParams = new mutable.HashMap[String, String] + + if (user == null) throw new Exception("Missing required parameter 'user' when calling UserApi->createUsersWithListInput") + + val resFuture = client.submit("POST", path, queryParams.toMap, headerParams.toMap, writer.write(user)) + resFuture flatMap { resp => + val status = Response.Status.fromStatusCode(resp.statusCode) + status.getFamily match { + case Family.SUCCESSFUL | Family.REDIRECTION | Family.INFORMATIONAL => process(reader.read(resp)) + case _ => throw new ApiException(resp.statusCode, resp.statusText) + } + } + } + + def deleteUser(username: String)(implicit reader: ClientResponseReader[Unit]): Future[Unit] = { + // create path and map variables + val path = (addFmt("/user/{username}") + replaceAll("\\{" + "username" + "\\}", username.toString)) + + // query params + val queryParams = new mutable.HashMap[String, String] + val headerParams = new mutable.HashMap[String, String] + + if (username == null) throw new Exception("Missing required parameter 'username' when calling UserApi->deleteUser") + + + val resFuture = client.submit("DELETE", path, queryParams.toMap, headerParams.toMap, "") + resFuture flatMap { resp => + val status = Response.Status.fromStatusCode(resp.statusCode) + status.getFamily match { + case Family.SUCCESSFUL | Family.REDIRECTION | Family.INFORMATIONAL => process(reader.read(resp)) + case _ => throw new ApiException(resp.statusCode, resp.statusText) + } + } + } + + def getUserByName(username: String)(implicit reader: ClientResponseReader[User]): Future[User] = { + // create path and map variables + val path = (addFmt("/user/{username}") + replaceAll("\\{" + "username" + "\\}", username.toString)) + + // query params + val queryParams = new mutable.HashMap[String, String] + val headerParams = new mutable.HashMap[String, String] + + if (username == null) throw new Exception("Missing required parameter 'username' when calling UserApi->getUserByName") + + + val resFuture = client.submit("GET", path, queryParams.toMap, headerParams.toMap, "") + resFuture flatMap { resp => + val status = Response.Status.fromStatusCode(resp.statusCode) + status.getFamily match { + case Family.SUCCESSFUL | Family.REDIRECTION | Family.INFORMATIONAL => process(reader.read(resp)) + case _ => throw new ApiException(resp.statusCode, resp.statusText) + } + } + } + + def loginUser(username: String, + password: String)(implicit reader: ClientResponseReader[String]): Future[String] = { + // create path and map variables + val path = (addFmt("/user/login")) + + // query params + val queryParams = new mutable.HashMap[String, String] + val headerParams = new mutable.HashMap[String, String] + + if (username == null) throw new Exception("Missing required parameter 'username' when calling UserApi->loginUser") + + if (password == null) throw new Exception("Missing required parameter 'password' when calling UserApi->loginUser") + + queryParams += "username" -> username.toString + queryParams += "password" -> password.toString + + val resFuture = client.submit("GET", path, queryParams.toMap, headerParams.toMap, "") + resFuture flatMap { resp => + val status = Response.Status.fromStatusCode(resp.statusCode) + status.getFamily match { + case Family.SUCCESSFUL | Family.REDIRECTION | Family.INFORMATIONAL => process(reader.read(resp)) + case _ => throw new ApiException(resp.statusCode, resp.statusText) + } + } + } + + def logoutUser()(implicit reader: ClientResponseReader[Unit]): Future[Unit] = { + // create path and map variables + val path = (addFmt("/user/logout")) + + // query params + val queryParams = new mutable.HashMap[String, String] + val headerParams = new mutable.HashMap[String, String] + + + val resFuture = client.submit("GET", path, queryParams.toMap, headerParams.toMap, "") + resFuture flatMap { resp => + val status = Response.Status.fromStatusCode(resp.statusCode) + status.getFamily match { + case Family.SUCCESSFUL | Family.REDIRECTION | Family.INFORMATIONAL => process(reader.read(resp)) + case _ => throw new ApiException(resp.statusCode, resp.statusText) + } + } + } + + def updateUser(username: String, + user: User)(implicit reader: ClientResponseReader[Unit], writer: RequestWriter[User]): Future[Unit] = { + // create path and map variables + val path = (addFmt("/user/{username}") + replaceAll("\\{" + "username" + "\\}", username.toString)) + + // query params + val queryParams = new mutable.HashMap[String, String] + val headerParams = new mutable.HashMap[String, String] + + if (username == null) throw new Exception("Missing required parameter 'username' when calling UserApi->updateUser") + + if (user == null) throw new Exception("Missing required parameter 'user' when calling UserApi->updateUser") + + val resFuture = client.submit("PUT", path, queryParams.toMap, headerParams.toMap, writer.write(user)) + resFuture flatMap { resp => + val status = Response.Status.fromStatusCode(resp.statusCode) + status.getFamily match { + case Family.SUCCESSFUL | Family.REDIRECTION | Family.INFORMATIONAL => process(reader.read(resp)) + case _ => throw new ApiException(resp.statusCode, resp.statusText) + } + } + } + + +} diff --git a/samples/client/petstore/scala-httpclient-deprecated/src/main/scala/org/openapitools/example/invoker/ApiInvoker.scala b/samples/client/petstore/scala-httpclient-deprecated/src/main/scala/org/openapitools/example/invoker/ApiInvoker.scala new file mode 100644 index 00000000000..f04c9fa6a1e --- /dev/null +++ b/samples/client/petstore/scala-httpclient-deprecated/src/main/scala/org/openapitools/example/invoker/ApiInvoker.scala @@ -0,0 +1,237 @@ +/** + * 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.example.invoker + +import com.sun.jersey.api.client.Client +import com.sun.jersey.api.client.ClientResponse +import com.sun.jersey.api.client.config.ClientConfig +import com.sun.jersey.api.client.config.DefaultClientConfig +import com.sun.jersey.api.client.filter.LoggingFilter + +import com.sun.jersey.core.util.MultivaluedMapImpl +import com.sun.jersey.multipart.FormDataMultiPart +import com.sun.jersey.multipart.file.FileDataBodyPart + +import java.io.File +import java.net.URLEncoder +import java.util.UUID +import javax.ws.rs.core.MediaType + +import scala.collection.JavaConverters._ +import scala.collection.mutable + +import com.fasterxml.jackson.module.scala.DefaultScalaModule +import com.fasterxml.jackson.datatype.joda.JodaModule +import com.fasterxml.jackson.core.JsonGenerator.Feature +import com.fasterxml.jackson.databind._ +import com.fasterxml.jackson.annotation._ +import com.fasterxml.jackson.databind.annotation.JsonSerialize + +object ScalaJsonUtil { + def getJsonMapper: ObjectMapper = { + val mapper = new ObjectMapper() + mapper.registerModule(new DefaultScalaModule()) + mapper.registerModule(new JodaModule()) + mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL) + mapper.setSerializationInclusion(JsonInclude.Include.NON_DEFAULT) + mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false) + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) + mapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY) + mapper + } +} + +class ApiInvoker(val mapper: ObjectMapper = ScalaJsonUtil.getJsonMapper, + httpHeaders: mutable.HashMap[String, String] = mutable.HashMap(), + hostMap: mutable.HashMap[String, Client] = mutable.HashMap(), + asyncHttpClient: Boolean = false, + authScheme: String = "", + authPreemptive: Boolean = false +) { + + var defaultHeaders: mutable.HashMap[String, String] = httpHeaders + + def escape(value: String): String = { + URLEncoder.encode(value, "utf-8").replaceAll("\\+", "%20") + } + def escape(values: List[String]): String = { + values.map(escape).mkString(",") + } + + def escape(value: Long): String = value.toString + def escape(value: Double): String = value.toString + def escape(value: Float): String = value.toString + def escape(value: UUID): String = value.toString + + def deserialize(json: String, containerType: String, cls: Class[_]) = { + if (cls == classOf[String]) { + json match { + case s: String => + if (s.startsWith("\"") && s.endsWith("\"") && s.length > 1) { + s.substring(1, s.length - 1) + } else { + s + } + case _ => null + } + } else { + containerType.toLowerCase match { + case "array" => + val typeInfo = mapper.getTypeFactory.constructCollectionType(classOf[java.util.List[_]], cls) + val response = mapper.readValue(json, typeInfo).asInstanceOf[java.util.List[_]] + response.asScala.toList + case "list" => + val typeInfo = mapper.getTypeFactory.constructCollectionType(classOf[java.util.List[_]], cls) + val response = mapper.readValue(json, typeInfo).asInstanceOf[java.util.List[_]] + response.asScala.toList + case _ => + json match { + case e: String if "\"\"" == e => null + case _ => mapper.readValue(json, cls) + } + } + } + } + + def serialize(obj: AnyRef): String = { + if (obj != null) { + obj match { + case e: List[_] => mapper.writeValueAsString(obj.asInstanceOf[List[_]].asJava) + case _ => mapper.writeValueAsString(obj) + } + } else { + null + } + } + + def invokeApi( + host: String, + path: String, + method: String, + queryParams: Map[String, String], + formParams: Map[String, String], + body: AnyRef, + headerParams: Map[String, String], + contentType: String +): String = { + val client = getClient(host) + + val querystring = queryParams.filter(k => k._2 != null).map(k => escape(k._1) + "=" + escape(k._2)).mkString("?", "&", "") + val builder = client.resource(host + path + querystring).accept(contentType) + headerParams.map(p => builder.header(p._1, p._2)) + defaultHeaders.foreach(p => { + if (!headerParams.contains(p._1) && p._2 != null) { + builder.header(p._1, p._2) + } + }) + var formData: MultivaluedMapImpl = null + if (contentType == "application/x-www-form-urlencoded") { + formData = new MultivaluedMapImpl() + formParams.foreach(p => formData.add(p._1, p._2)) + } + + val response: ClientResponse = method match { + case "GET" => builder.get(classOf[ClientResponse]) + case "POST" => + if (formData != null && formData.size() > 0) { + builder.post(classOf[ClientResponse], formData) + } else if (body != null && body.isInstanceOf[File]) { + val file = body.asInstanceOf[File] + val form = new FormDataMultiPart() + form.field("filename", file.getName) + form.bodyPart(new FileDataBodyPart("file", file, MediaType.MULTIPART_FORM_DATA_TYPE)) + builder.post(classOf[ClientResponse], form) + } else { + if (body == null) { + builder.post(classOf[ClientResponse], serialize(body)) + } else { + builder.`type`(contentType).post(classOf[ClientResponse], serialize(body)) + } + } + case "PUT" => + if (formData != null) { + builder.post(classOf[ClientResponse], formData) + } else if (body == null) { + builder.put(classOf[ClientResponse], null) + } else { + builder.`type`(contentType).put(classOf[ClientResponse], serialize(body)) + } + case "DELETE" => builder.delete(classOf[ClientResponse]) + case "PATCH" => + if(formData != null) { + builder.header("X-HTTP-Method-Override", "PATCH").post(classOf[ClientResponse], formData) + } else if(body == null) { + builder.header("X-HTTP-Method-Override", "PATCH").post(classOf[ClientResponse], null) + } else { + builder.header("X-HTTP-Method-Override", "PATCH").`type`(contentType).post(classOf[ClientResponse], serialize(body)) + } + case _ => null + } + response.getStatusInfo.getStatusCode match { + case 204 => "" + case code: Int if Range(200, 299).contains(code) => + if (response.hasEntity) { + response.getEntity(classOf[String]) + } else { + "" + } + case _ => + val entity = if (response.hasEntity) { + response.getEntity(classOf[String]) + } else { + "no data" + } + throw new ApiException(response.getStatusInfo.getStatusCode, entity) + } + } + + def getClient(host: String): Client = { + if (hostMap.contains(host)) { + hostMap(host) + } else { + val client = newClient(host) + // client.addFilter(new LoggingFilter()) + hostMap += host -> client + client + } + } + + def newClient(host: String): Client = if (asyncHttpClient) { + import com.ning.http.client.Realm + import org.sonatype.spice.jersey.client.ahc.AhcHttpClient + import org.sonatype.spice.jersey.client.ahc.config.DefaultAhcConfig + + val config: DefaultAhcConfig = new DefaultAhcConfig() + if (!authScheme.isEmpty) { + val authSchemeEnum = Realm.AuthScheme.valueOf(authScheme) + config + .getAsyncHttpClientConfigBuilder + .setRealm(new Realm.RealmBuilder().setScheme(authSchemeEnum) + .setUsePreemptiveAuth(authPreemptive).build) + } + AhcHttpClient.create(config) + } else { + Client.create() + } +} + +object ApiInvoker extends ApiInvoker( + mapper = ScalaJsonUtil.getJsonMapper, + httpHeaders = mutable.HashMap(), + hostMap = mutable.HashMap(), + asyncHttpClient = false, + authScheme = "", + authPreemptive = false +) + +class ApiException(val code: Int, msg: String) extends RuntimeException(msg) diff --git a/samples/client/petstore/scala-httpclient-deprecated/src/main/scala/org/openapitools/example/invoker/AsyncClient.scala b/samples/client/petstore/scala-httpclient-deprecated/src/main/scala/org/openapitools/example/invoker/AsyncClient.scala new file mode 100644 index 00000000000..60e423b51cb --- /dev/null +++ b/samples/client/petstore/scala-httpclient-deprecated/src/main/scala/org/openapitools/example/invoker/AsyncClient.scala @@ -0,0 +1,20 @@ +package org.openapitools.example.invoker + +import org.openapitools.example.api._ + +import com.wordnik.swagger.client._ + +import java.io.Closeable + +class AsyncClient(config: SwaggerConfig) extends Closeable { + lazy val locator: ServiceLocator = config.locator + lazy val name: String = config.name + + private[this] val client = transportClient + + protected def transportClient: TransportClient = new RestClient(config) + + def close() { + client.close() + } +} diff --git a/samples/client/petstore/scala-sttp/.openapi-generator/VERSION b/samples/client/petstore/scala-sttp/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/client/petstore/scala-sttp/.openapi-generator/VERSION +++ b/samples/client/petstore/scala-sttp/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/client/petstore/spring-cloud-async/.openapi-generator/VERSION b/samples/client/petstore/spring-cloud-async/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/client/petstore/spring-cloud-async/.openapi-generator/VERSION +++ b/samples/client/petstore/spring-cloud-async/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/client/petstore/spring-cloud-async/src/main/java/org/openapitools/api/PetApi.java b/samples/client/petstore/spring-cloud-async/src/main/java/org/openapitools/api/PetApi.java index c677ea9ac0d..e52921530ee 100644 --- a/samples/client/petstore/spring-cloud-async/src/main/java/org/openapitools/api/PetApi.java +++ b/samples/client/petstore/spring-cloud-async/src/main/java/org/openapitools/api/PetApi.java @@ -1,5 +1,9 @@ /** +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (6.0.0-SNAPSHOT). +======= + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.3.0-SNAPSHOT). +>>>>>>> origin/5.3.x * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/spring-cloud-async/src/main/java/org/openapitools/api/StoreApi.java b/samples/client/petstore/spring-cloud-async/src/main/java/org/openapitools/api/StoreApi.java index d6a4be0e7c1..d6891577a1f 100644 --- a/samples/client/petstore/spring-cloud-async/src/main/java/org/openapitools/api/StoreApi.java +++ b/samples/client/petstore/spring-cloud-async/src/main/java/org/openapitools/api/StoreApi.java @@ -1,5 +1,9 @@ /** +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (6.0.0-SNAPSHOT). +======= + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.3.0-SNAPSHOT). +>>>>>>> origin/5.3.x * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/spring-cloud-async/src/main/java/org/openapitools/api/UserApi.java b/samples/client/petstore/spring-cloud-async/src/main/java/org/openapitools/api/UserApi.java index f2a54b8b12d..46bdca806be 100644 --- a/samples/client/petstore/spring-cloud-async/src/main/java/org/openapitools/api/UserApi.java +++ b/samples/client/petstore/spring-cloud-async/src/main/java/org/openapitools/api/UserApi.java @@ -1,5 +1,9 @@ /** +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (6.0.0-SNAPSHOT). +======= + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.3.0-SNAPSHOT). +>>>>>>> origin/5.3.x * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/spring-cloud-no-nullable/.openapi-generator/VERSION b/samples/client/petstore/spring-cloud-no-nullable/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/client/petstore/spring-cloud-no-nullable/.openapi-generator/VERSION +++ b/samples/client/petstore/spring-cloud-no-nullable/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/client/petstore/spring-cloud-no-nullable/src/main/java/org/openapitools/api/PetApi.java b/samples/client/petstore/spring-cloud-no-nullable/src/main/java/org/openapitools/api/PetApi.java index 89decbf82ea..b97e3113c7f 100644 --- a/samples/client/petstore/spring-cloud-no-nullable/src/main/java/org/openapitools/api/PetApi.java +++ b/samples/client/petstore/spring-cloud-no-nullable/src/main/java/org/openapitools/api/PetApi.java @@ -1,5 +1,9 @@ /** +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (6.0.0-SNAPSHOT). +======= + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.3.0-SNAPSHOT). +>>>>>>> origin/5.3.x * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/spring-cloud-no-nullable/src/main/java/org/openapitools/api/StoreApi.java b/samples/client/petstore/spring-cloud-no-nullable/src/main/java/org/openapitools/api/StoreApi.java index c6ce94145ab..00e115beae3 100644 --- a/samples/client/petstore/spring-cloud-no-nullable/src/main/java/org/openapitools/api/StoreApi.java +++ b/samples/client/petstore/spring-cloud-no-nullable/src/main/java/org/openapitools/api/StoreApi.java @@ -1,5 +1,9 @@ /** +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (6.0.0-SNAPSHOT). +======= + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.3.0-SNAPSHOT). +>>>>>>> origin/5.3.x * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/spring-cloud-no-nullable/src/main/java/org/openapitools/api/UserApi.java b/samples/client/petstore/spring-cloud-no-nullable/src/main/java/org/openapitools/api/UserApi.java index f237b4d0866..2bc17cffa3d 100644 --- a/samples/client/petstore/spring-cloud-no-nullable/src/main/java/org/openapitools/api/UserApi.java +++ b/samples/client/petstore/spring-cloud-no-nullable/src/main/java/org/openapitools/api/UserApi.java @@ -1,5 +1,9 @@ /** +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (6.0.0-SNAPSHOT). +======= + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.3.0-SNAPSHOT). +>>>>>>> origin/5.3.x * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/spring-cloud-spring-pageable/.openapi-generator/VERSION b/samples/client/petstore/spring-cloud-spring-pageable/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/client/petstore/spring-cloud-spring-pageable/.openapi-generator/VERSION +++ b/samples/client/petstore/spring-cloud-spring-pageable/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/client/petstore/spring-cloud-spring-pageable/src/main/java/org/openapitools/api/PetApi.java b/samples/client/petstore/spring-cloud-spring-pageable/src/main/java/org/openapitools/api/PetApi.java index 2c7192cf68d..0dd8dfabef1 100644 --- a/samples/client/petstore/spring-cloud-spring-pageable/src/main/java/org/openapitools/api/PetApi.java +++ b/samples/client/petstore/spring-cloud-spring-pageable/src/main/java/org/openapitools/api/PetApi.java @@ -1,5 +1,9 @@ /** +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (6.0.0-SNAPSHOT). +======= + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.3.0-SNAPSHOT). +>>>>>>> origin/5.3.x * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/spring-cloud-spring-pageable/src/main/java/org/openapitools/api/StoreApi.java b/samples/client/petstore/spring-cloud-spring-pageable/src/main/java/org/openapitools/api/StoreApi.java index 7ae36b7b13c..f558be7f66a 100644 --- a/samples/client/petstore/spring-cloud-spring-pageable/src/main/java/org/openapitools/api/StoreApi.java +++ b/samples/client/petstore/spring-cloud-spring-pageable/src/main/java/org/openapitools/api/StoreApi.java @@ -1,5 +1,9 @@ /** +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (6.0.0-SNAPSHOT). +======= + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.3.0-SNAPSHOT). +>>>>>>> origin/5.3.x * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/spring-cloud-spring-pageable/src/main/java/org/openapitools/api/UserApi.java b/samples/client/petstore/spring-cloud-spring-pageable/src/main/java/org/openapitools/api/UserApi.java index 1eb79e642e7..777302ffa21 100644 --- a/samples/client/petstore/spring-cloud-spring-pageable/src/main/java/org/openapitools/api/UserApi.java +++ b/samples/client/petstore/spring-cloud-spring-pageable/src/main/java/org/openapitools/api/UserApi.java @@ -1,5 +1,9 @@ /** +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (6.0.0-SNAPSHOT). +======= + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.3.0-SNAPSHOT). +>>>>>>> origin/5.3.x * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/spring-cloud/.openapi-generator/VERSION b/samples/client/petstore/spring-cloud/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/client/petstore/spring-cloud/.openapi-generator/VERSION +++ b/samples/client/petstore/spring-cloud/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x 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 89decbf82ea..b97e3113c7f 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,9 @@ /** +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (6.0.0-SNAPSHOT). +======= + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.3.0-SNAPSHOT). +>>>>>>> origin/5.3.x * 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 c6ce94145ab..00e115beae3 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,9 @@ /** +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (6.0.0-SNAPSHOT). +======= + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.3.0-SNAPSHOT). +>>>>>>> origin/5.3.x * 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 f237b4d0866..2bc17cffa3d 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,9 @@ /** +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (6.0.0-SNAPSHOT). +======= + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.3.0-SNAPSHOT). +>>>>>>> origin/5.3.x * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/spring-stubs/.openapi-generator/VERSION b/samples/client/petstore/spring-stubs/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/client/petstore/spring-stubs/.openapi-generator/VERSION +++ b/samples/client/petstore/spring-stubs/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/client/petstore/spring-stubs/src/main/java/org/openapitools/api/PetApi.java b/samples/client/petstore/spring-stubs/src/main/java/org/openapitools/api/PetApi.java index 6b2cb5666f4..c568685ec20 100644 --- a/samples/client/petstore/spring-stubs/src/main/java/org/openapitools/api/PetApi.java +++ b/samples/client/petstore/spring-stubs/src/main/java/org/openapitools/api/PetApi.java @@ -1,5 +1,9 @@ /** +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (6.0.0-SNAPSHOT). +======= + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.3.0-SNAPSHOT). +>>>>>>> origin/5.3.x * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/spring-stubs/src/main/java/org/openapitools/api/StoreApi.java b/samples/client/petstore/spring-stubs/src/main/java/org/openapitools/api/StoreApi.java index a002e472853..aca7bc44064 100644 --- a/samples/client/petstore/spring-stubs/src/main/java/org/openapitools/api/StoreApi.java +++ b/samples/client/petstore/spring-stubs/src/main/java/org/openapitools/api/StoreApi.java @@ -1,5 +1,9 @@ /** +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (6.0.0-SNAPSHOT). +======= + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.3.0-SNAPSHOT). +>>>>>>> origin/5.3.x * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/spring-stubs/src/main/java/org/openapitools/api/UserApi.java b/samples/client/petstore/spring-stubs/src/main/java/org/openapitools/api/UserApi.java index 225a00aa60a..f057e05f8c6 100644 --- a/samples/client/petstore/spring-stubs/src/main/java/org/openapitools/api/UserApi.java +++ b/samples/client/petstore/spring-stubs/src/main/java/org/openapitools/api/UserApi.java @@ -1,5 +1,9 @@ /** +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (6.0.0-SNAPSHOT). +======= + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.3.0-SNAPSHOT). +>>>>>>> origin/5.3.x * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/swift5/alamofireLibrary/.gitignore b/samples/client/petstore/swift5/alamofireLibrary/.gitignore index 5e5d5cebcf4..627d360a903 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/.gitignore +++ b/samples/client/petstore/swift5/alamofireLibrary/.gitignore @@ -1,12 +1,22 @@ +# Created by https://www.toptal.com/developers/gitignore/api/swift,xcode +# Edit at https://www.toptal.com/developers/gitignore?templates=swift,xcode + +### Swift ### # Xcode # # gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore -## Build generated -build/ -DerivedData +## User settings +xcuserdata/ -## Various settings +## compatibility with Xcode 8 and earlier (ignoring not required starting Xcode 9) +*.xcscmblueprint +*.xccheckout + +## compatibility with Xcode 3 and earlier (ignoring not required starting Xcode 4) +build/ +DerivedData/ +*.moved-aside *.pbxuser !default.pbxuser *.mode1v3 @@ -15,49 +25,81 @@ DerivedData !default.mode2v3 *.perspectivev3 !default.perspectivev3 -xcuserdata - -## Other -*.xccheckout -*.moved-aside -*.xcuserstate -*.xcscmblueprint ## Obj-C/Swift specific *.hmap + +## App packaging *.ipa +*.dSYM.zip +*.dSYM ## Playgrounds timeline.xctimeline playground.xcworkspace # Swift Package Manager -# # Add this line if you want to avoid checking in source code from Swift Package Manager dependencies. # Packages/ +# Package.pins +# Package.resolved +# *.xcodeproj +# Xcode automatically generates this directory with a .xcworkspacedata file and xcuserdata +# hence it is not needed unless you have added a package configuration file to your project +# .swiftpm + .build/ # CocoaPods -# # We recommend against adding the Pods directory to your .gitignore. However # you should judge for yourself, the pros and cons are mentioned at: # https://guides.cocoapods.org/using/using-cocoapods.html#should-i-check-the-pods-directory-into-source-control -# # Pods/ +# Add this line if you want to avoid checking in source code from the Xcode workspace +# *.xcworkspace # Carthage -# # Add this line if you want to avoid checking in source code from Carthage dependencies. # Carthage/Checkouts -Carthage/Build +Carthage/Build/ + +# Add this lines if you are using Accio dependency management (Deprecated since Xcode 12) +# Dependencies/ +# .accio/ # fastlane -# -# It is recommended to not store the screenshots in the git repo. Instead, use fastlane to re-generate the -# screenshots whenever they are needed. +# It is recommended to not store the screenshots in the git repo. +# Instead, use fastlane to re-generate the screenshots whenever they are needed. # For more information about the recommended setup visit: -# https://github.com/fastlane/fastlane/blob/master/docs/Gitignore.md +# https://docs.fastlane.tools/best-practices/source-control/#source-control fastlane/report.xml -fastlane/screenshots +fastlane/Preview.html +fastlane/screenshots/**/*.png +fastlane/test_output + +# Code Injection +# After new code Injection tools there's a generated folder /iOSInjectionProject +# https://github.com/johnno1962/injectionforxcode + +iOSInjectionProject/ + +### Xcode ### +# Xcode +# gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore + + + + +## Gcc Patch +/*.gcno + +### Xcode Patch ### +*.xcodeproj/* +!*.xcodeproj/project.pbxproj +!*.xcodeproj/xcshareddata/ +!*.xcworkspace/contents.xcworkspacedata +**/xcshareddata/WorkspaceSettings.xcsettings + +# End of https://www.toptal.com/developers/gitignore/api/swift,xcode diff --git a/samples/client/petstore/swift5/alamofireLibrary/.openapi-generator/VERSION b/samples/client/petstore/swift5/alamofireLibrary/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/.openapi-generator/VERSION +++ b/samples/client/petstore/swift5/alamofireLibrary/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/client/petstore/swift5/alamofireLibrary/Cartfile b/samples/client/petstore/swift5/alamofireLibrary/Cartfile index cf67badb850..5404871742d 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/Cartfile +++ b/samples/client/petstore/swift5/alamofireLibrary/Cartfile @@ -1,2 +1,2 @@ github "Alamofire/Alamofire" ~> 4.9.1 -github "Flight-School/AnyCodable" ~> 0.4.0 +github "Flight-School/AnyCodable" ~> 0.6.1 diff --git a/samples/client/petstore/swift5/alamofireLibrary/Package.resolved b/samples/client/petstore/swift5/alamofireLibrary/Package.resolved index ca6137050eb..d1d000eb332 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/Package.resolved +++ b/samples/client/petstore/swift5/alamofireLibrary/Package.resolved @@ -3,12 +3,21 @@ "pins": [ { "package": "Alamofire", - "repositoryURL": "https://github.com/Alamofire/Alamofire.git", + "repositoryURL": "https://github.com/Alamofire/Alamofire", "state": { "branch": null, "revision": "747c8db8d57b68d5e35275f10c92d55f982adbd4", "version": "4.9.1" } + }, + { + "package": "AnyCodable", + "repositoryURL": "https://github.com/Flight-School/AnyCodable", + "state": { + "branch": null, + "revision": "69261f239f0fffaf51495dadc4f8483fbfe97025", + "version": "0.6.1" + } } ] }, diff --git a/samples/client/petstore/swift5/alamofireLibrary/Package.swift b/samples/client/petstore/swift5/alamofireLibrary/Package.swift index 41b3c7aba32..1860a02d85b 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/Package.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/Package.swift @@ -19,8 +19,8 @@ let package = Package( ], dependencies: [ // Dependencies declare other packages that this package depends on. - .package(url: "https://github.com/Flight-School/AnyCodable", .exact("0.4.0")), - .package(url: "https://github.com/Alamofire/Alamofire.git", from: "4.9.1"), + .package(url: "https://github.com/Flight-School/AnyCodable", from: "0.6.1"), + .package(url: "https://github.com/Alamofire/Alamofire", from: "4.9.1"), ], targets: [ // Targets are the basic building blocks of a package. A target can define a module or a test suite. diff --git a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient.podspec b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient.podspec index 23fbf094106..7ce1a61d409 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient.podspec +++ b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient.podspec @@ -12,5 +12,5 @@ Pod::Spec.new do |s| s.summary = 'PetstoreClient' s.source_files = 'PetstoreClient/Classes/**/*.swift' s.dependency 'Alamofire', '~> 4.9.1' - s.dependency 'AnyCodable-FlightSchool', '~> 0.4.0' + s.dependency 'AnyCodable-FlightSchool', '~> 0.6.1' end diff --git a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs.swift b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs.swift index c6beeedf9a4..82eb3630aa6 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs.swift @@ -6,10 +6,13 @@ import Foundation -open class PetstoreClientAPI { +@available(*, deprecated, renamed: "PetstoreClient") +public typealias PetstoreClientAPI = PetstoreClient + +open class PetstoreClient { public static var basePath = "http://petstore.swagger.io:80/v2" - public static var credential: URLCredential? public static var customHeaders: [String: String] = [:] + public static var credential: URLCredential? public static var requestBuilderFactory: RequestBuilderFactory = AlamofireRequestBuilderFactory() public static var apiResponseQueue: DispatchQueue = .main } @@ -30,7 +33,7 @@ open class RequestBuilder { self.parameters = parameters self.headers = headers - addHeaders(PetstoreClientAPI.customHeaders) + addHeaders(PetstoreClient.customHeaders) } open func addHeaders(_ aHeaders: [String: String]) { @@ -39,7 +42,7 @@ open class RequestBuilder { } } - open func execute(_ apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, _ completion: @escaping (_ result: Swift.Result, Error>) -> Void) { } + open func execute(_ apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, _ completion: @escaping (_ result: Swift.Result, Error>) -> Void) { } public func addHeader(name: String, value: String) -> Self { if !value.isEmpty { @@ -49,7 +52,7 @@ open class RequestBuilder { } open func addCredential() -> Self { - credential = PetstoreClientAPI.credential + credential = PetstoreClient.credential return self } } 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 72b89640eeb..ac9dd9b74f2 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 @@ -6,8 +6,12 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif open class AnotherFakeAPI { + /** To test special tags @@ -15,7 +19,7 @@ open class AnotherFakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func call123testSpecialTags(body: Client, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Client?, _ error: Error?) -> Void)) { + open class func call123testSpecialTags(body: Client, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Client?, _ error: Error?) -> Void)) { call123testSpecialTagsWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -34,21 +38,20 @@ open class AnotherFakeAPI { - returns: RequestBuilder */ open class func call123testSpecialTagsWithRequestBuilder(body: Client) -> RequestBuilder { - let path = "/another-fake/dummy" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/another-fake/dummy" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "PATCH", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "PATCH", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } - } 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 cf92424d9cc..d7260ca2e3a 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 @@ -6,15 +6,19 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif open class FakeAPI { + /** - parameter body: (body) Input boolean as post body (optional) - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func fakeOuterBooleanSerialize(body: Bool? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Bool?, _ error: Error?) -> Void)) { + open class func fakeOuterBooleanSerialize(body: Bool? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Bool?, _ error: Error?) -> Void)) { fakeOuterBooleanSerializeWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -32,21 +36,21 @@ open class FakeAPI { - returns: RequestBuilder */ open class func fakeOuterBooleanSerializeWithRequestBuilder(body: Bool? = nil) -> RequestBuilder { - let path = "/fake/outer/boolean" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/fake/outer/boolean" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -55,7 +59,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func fakeOuterCompositeSerialize(body: OuterComposite? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: OuterComposite?, _ error: Error?) -> Void)) { + open class func fakeOuterCompositeSerialize(body: OuterComposite? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: OuterComposite?, _ error: Error?) -> Void)) { fakeOuterCompositeSerializeWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -73,21 +77,21 @@ open class FakeAPI { - returns: RequestBuilder */ open class func fakeOuterCompositeSerializeWithRequestBuilder(body: OuterComposite? = nil) -> RequestBuilder { - let path = "/fake/outer/composite" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/fake/outer/composite" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -96,7 +100,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func fakeOuterNumberSerialize(body: Double? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Double?, _ error: Error?) -> Void)) { + open class func fakeOuterNumberSerialize(body: Double? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Double?, _ error: Error?) -> Void)) { fakeOuterNumberSerializeWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -114,21 +118,21 @@ open class FakeAPI { - returns: RequestBuilder */ open class func fakeOuterNumberSerializeWithRequestBuilder(body: Double? = nil) -> RequestBuilder { - let path = "/fake/outer/number" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/fake/outer/number" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -137,7 +141,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func fakeOuterStringSerialize(body: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: String?, _ error: Error?) -> Void)) { + open class func fakeOuterStringSerialize(body: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: String?, _ error: Error?) -> Void)) { fakeOuterStringSerializeWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -155,21 +159,21 @@ open class FakeAPI { - returns: RequestBuilder */ open class func fakeOuterStringSerializeWithRequestBuilder(body: String? = nil) -> RequestBuilder { - let path = "/fake/outer/string" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/fake/outer/string" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -178,7 +182,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func testBodyWithFileSchema(body: FileSchemaTestClass, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func testBodyWithFileSchema(body: FileSchemaTestClass, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { testBodyWithFileSchemaWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -196,21 +200,21 @@ open class FakeAPI { - returns: RequestBuilder */ open class func testBodyWithFileSchemaWithRequestBuilder(body: FileSchemaTestClass) -> RequestBuilder { - let path = "/fake/body-with-file-schema" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/fake/body-with-file-schema" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "PUT", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -220,7 +224,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func testBodyWithQueryParams(query: String, body: User, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func testBodyWithQueryParams(query: String, body: User, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { testBodyWithQueryParamsWithRequestBuilder(query: query, body: body).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -238,24 +242,24 @@ open class FakeAPI { - returns: RequestBuilder */ open class func testBodyWithQueryParamsWithRequestBuilder(query: String, body: User) -> RequestBuilder { - let path = "/fake/body-with-query-params" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/fake/body-with-query-params" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - var urlComponents = URLComponents(string: URLString) - urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ + var localVariableUrlComponents = URLComponents(string: localVariableURLString) + localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ "query": query.encodeToJSON(), ]) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "PUT", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -265,7 +269,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func testClientModel(body: Client, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Client?, _ error: Error?) -> Void)) { + open class func testClientModel(body: Client, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Client?, _ error: Error?) -> Void)) { testClientModelWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -284,21 +288,21 @@ open class FakeAPI { - returns: RequestBuilder */ open class func testClientModelWithRequestBuilder(body: Client) -> RequestBuilder { - let path = "/fake" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/fake" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "PATCH", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "PATCH", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -321,7 +325,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func testEndpointParameters(number: Double, double: Double, patternWithoutDelimiter: String, byte: Data, integer: Int? = nil, int32: Int? = nil, int64: Int64? = nil, float: Float? = nil, string: String? = nil, binary: URL? = nil, date: Date? = nil, dateTime: Date? = nil, password: String? = nil, callback: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func testEndpointParameters(number: Double, double: Double, patternWithoutDelimiter: String, byte: Data, integer: Int? = nil, int32: Int? = nil, int64: Int64? = nil, float: Float? = nil, string: String? = nil, binary: URL? = nil, date: Date? = nil, dateTime: Date? = nil, password: String? = nil, callback: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { testEndpointParametersWithRequestBuilder(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(apiResponseQueue) { result -> Void in switch result { case .success: @@ -356,9 +360,9 @@ open class FakeAPI { - returns: RequestBuilder */ open class func testEndpointParametersWithRequestBuilder(number: Double, double: Double, patternWithoutDelimiter: String, byte: Data, integer: Int? = nil, int32: Int? = nil, int64: Int64? = nil, float: Float? = nil, string: String? = nil, binary: URL? = nil, date: Date? = nil, dateTime: Date? = nil, password: String? = nil, callback: String? = nil) -> RequestBuilder { - let path = "/fake" - let URLString = PetstoreClientAPI.basePath + path - let formParams: [String: Any?] = [ + let localVariablePath = "/fake" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableFormParams: [String: Any?] = [ "integer": integer?.encodeToJSON(), "int32": int32?.encodeToJSON(), "int64": int64?.encodeToJSON(), @@ -375,20 +379,20 @@ open class FakeAPI { "callback": callback?.encodeToJSON(), ] - let nonNullParameters = APIHelper.rejectNil(formParams) - let parameters = APIHelper.convertBoolToString(nonNullParameters) + let localVariableNonNullParameters = APIHelper.rejectNil(localVariableFormParams) + let localVariableParameters = APIHelper.convertBoolToString(localVariableNonNullParameters) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ "Content-Type": "application/x-www-form-urlencoded", ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -472,7 +476,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func testEnumParameters(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func testEnumParameters(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { testEnumParametersWithRequestBuilder(enumHeaderStringArray: enumHeaderStringArray, enumHeaderString: enumHeaderString, enumQueryStringArray: enumQueryStringArray, enumQueryString: enumQueryString, enumQueryInteger: enumQueryInteger, enumQueryDouble: enumQueryDouble, enumFormStringArray: enumFormStringArray, enumFormString: enumFormString).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -498,35 +502,35 @@ open class FakeAPI { - returns: RequestBuilder */ open class func testEnumParametersWithRequestBuilder(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil) -> RequestBuilder { - let path = "/fake" - let URLString = PetstoreClientAPI.basePath + path - let formParams: [String: Any?] = [ + let localVariablePath = "/fake" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableFormParams: [String: Any?] = [ "enum_form_string_array": enumFormStringArray?.encodeToJSON(), "enum_form_string": enumFormString?.encodeToJSON(), ] - let nonNullParameters = APIHelper.rejectNil(formParams) - let parameters = APIHelper.convertBoolToString(nonNullParameters) + let localVariableNonNullParameters = APIHelper.rejectNil(localVariableFormParams) + let localVariableParameters = APIHelper.convertBoolToString(localVariableNonNullParameters) - var urlComponents = URLComponents(string: URLString) - urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ + var localVariableUrlComponents = URLComponents(string: localVariableURLString) + localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ "enum_query_string_array": enumQueryStringArray?.encodeToJSON(), "enum_query_string": enumQueryString?.encodeToJSON(), "enum_query_integer": enumQueryInteger?.encodeToJSON(), "enum_query_double": enumQueryDouble?.encodeToJSON(), ]) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ "Content-Type": "application/x-www-form-urlencoded", "enum_header_string_array": enumHeaderStringArray?.encodeToJSON(), "enum_header_string": enumHeaderString?.encodeToJSON(), ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -541,7 +545,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func testGroupParameters(requiredStringGroup: Int, requiredBooleanGroup: Bool, requiredInt64Group: Int64, stringGroup: Int? = nil, booleanGroup: Bool? = nil, int64Group: Int64? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func testGroupParameters(requiredStringGroup: Int, requiredBooleanGroup: Bool, requiredInt64Group: Int64, stringGroup: Int? = nil, booleanGroup: Bool? = nil, int64Group: Int64? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { testGroupParametersWithRequestBuilder(requiredStringGroup: requiredStringGroup, requiredBooleanGroup: requiredBooleanGroup, requiredInt64Group: requiredInt64Group, stringGroup: stringGroup, booleanGroup: booleanGroup, int64Group: int64Group).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -565,28 +569,28 @@ open class FakeAPI { - returns: RequestBuilder */ open class func testGroupParametersWithRequestBuilder(requiredStringGroup: Int, requiredBooleanGroup: Bool, requiredInt64Group: Int64, stringGroup: Int? = nil, booleanGroup: Bool? = nil, int64Group: Int64? = nil) -> RequestBuilder { - let path = "/fake" - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + let localVariablePath = "/fake" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - var urlComponents = URLComponents(string: URLString) - urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ + var localVariableUrlComponents = URLComponents(string: localVariableURLString) + localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ "required_string_group": requiredStringGroup.encodeToJSON(), "required_int64_group": requiredInt64Group.encodeToJSON(), "string_group": stringGroup?.encodeToJSON(), "int64_group": int64Group?.encodeToJSON(), ]) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ "required_boolean_group": requiredBooleanGroup.encodeToJSON(), "boolean_group": booleanGroup?.encodeToJSON(), ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "DELETE", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -596,7 +600,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func testInlineAdditionalProperties(param: [String: String], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func testInlineAdditionalProperties(param: [String: String], apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { testInlineAdditionalPropertiesWithRequestBuilder(param: param).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -614,21 +618,21 @@ open class FakeAPI { - returns: RequestBuilder */ open class func testInlineAdditionalPropertiesWithRequestBuilder(param: [String: String]) -> RequestBuilder { - let path = "/fake/inline-additionalProperties" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: param) + let localVariablePath = "/fake/inline-additionalProperties" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: param) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -639,7 +643,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func testJsonFormData(param: String, param2: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func testJsonFormData(param: String, param2: String, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { testJsonFormDataWithRequestBuilder(param: param, param2: param2).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -658,27 +662,26 @@ open class FakeAPI { - returns: RequestBuilder */ open class func testJsonFormDataWithRequestBuilder(param: String, param2: String) -> RequestBuilder { - let path = "/fake/jsonFormData" - let URLString = PetstoreClientAPI.basePath + path - let formParams: [String: Any?] = [ + let localVariablePath = "/fake/jsonFormData" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableFormParams: [String: Any?] = [ "param": param.encodeToJSON(), "param2": param2.encodeToJSON(), ] - let nonNullParameters = APIHelper.rejectNil(formParams) - let parameters = APIHelper.convertBoolToString(nonNullParameters) + let localVariableNonNullParameters = APIHelper.rejectNil(localVariableFormParams) + let localVariableParameters = APIHelper.convertBoolToString(localVariableNonNullParameters) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ "Content-Type": "application/x-www-form-urlencoded", ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } - } 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 d4d65166496..a6ca6c66b51 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 @@ -6,8 +6,12 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif open class FakeClassnameTags123API { + /** To test class name in snake case @@ -15,7 +19,7 @@ open class FakeClassnameTags123API { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func testClassname(body: Client, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Client?, _ error: Error?) -> Void)) { + open class func testClassname(body: Client, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Client?, _ error: Error?) -> Void)) { testClassnameWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -37,21 +41,20 @@ open class FakeClassnameTags123API { - returns: RequestBuilder */ open class func testClassnameWithRequestBuilder(body: Client) -> RequestBuilder { - let path = "/fake_classname_test" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/fake_classname_test" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "PATCH", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "PATCH", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } - } 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 a1fe0d12b1d..8b97def931c 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 @@ -6,8 +6,12 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif open class PetAPI { + /** Add a new pet to the store @@ -15,7 +19,7 @@ open class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func addPet(body: Pet, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func addPet(body: Pet, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { addPetWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -36,21 +40,21 @@ open class PetAPI { - returns: RequestBuilder */ open class func addPetWithRequestBuilder(body: Pet) -> RequestBuilder { - let path = "/pet" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/pet" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -61,7 +65,7 @@ open class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func deletePet(petId: Int64, apiKey: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func deletePet(petId: Int64, apiKey: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { deletePetWithRequestBuilder(petId: petId, apiKey: apiKey).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -83,24 +87,24 @@ open class PetAPI { - returns: RequestBuilder */ open class func deletePetWithRequestBuilder(petId: Int64, apiKey: String? = nil) -> RequestBuilder { - var path = "/pet/{petId}" + var localVariablePath = "/pet/{petId}" let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))" let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" - path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + localVariablePath = localVariablePath.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ "api_key": apiKey?.encodeToJSON(), ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "DELETE", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -119,7 +123,7 @@ open class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func findPetsByStatus(status: [String], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: [Pet]?, _ error: Error?) -> Void)) { + open class func findPetsByStatus(status: [String], apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: [Pet]?, _ error: Error?) -> Void)) { findPetsByStatusWithRequestBuilder(status: status).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -141,24 +145,24 @@ open class PetAPI { - returns: RequestBuilder<[Pet]> */ open class func findPetsByStatusWithRequestBuilder(status: [String]) -> RequestBuilder<[Pet]> { - let path = "/pet/findByStatus" - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + let localVariablePath = "/pet/findByStatus" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - var urlComponents = URLComponents(string: URLString) - urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ + var localVariableUrlComponents = URLComponents(string: localVariableURLString) + localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ "status": status.encodeToJSON(), ]) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -169,7 +173,7 @@ open class PetAPI { - parameter completion: completion handler to receive the data and the error objects */ @available(*, deprecated, message: "This operation is deprecated.") - open class func findPetsByTags(tags: [String], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: [Pet]?, _ error: Error?) -> Void)) { + open class func findPetsByTags(tags: [String], apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: [Pet]?, _ error: Error?) -> Void)) { findPetsByTagsWithRequestBuilder(tags: tags).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -192,24 +196,24 @@ open class PetAPI { */ @available(*, deprecated, message: "This operation is deprecated.") open class func findPetsByTagsWithRequestBuilder(tags: [String]) -> RequestBuilder<[Pet]> { - let path = "/pet/findByTags" - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + let localVariablePath = "/pet/findByTags" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - var urlComponents = URLComponents(string: URLString) - urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ + var localVariableUrlComponents = URLComponents(string: localVariableURLString) + localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ "tags": tags.encodeToJSON(), ]) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -219,7 +223,7 @@ open class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func getPetById(petId: Int64, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Pet?, _ error: Error?) -> Void)) { + open class func getPetById(petId: Int64, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Pet?, _ error: Error?) -> Void)) { getPetByIdWithRequestBuilder(petId: petId).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -241,24 +245,24 @@ open class PetAPI { - returns: RequestBuilder */ open class func getPetByIdWithRequestBuilder(petId: Int64) -> RequestBuilder { - var path = "/pet/{petId}" + var localVariablePath = "/pet/{petId}" let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))" let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" - path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + localVariablePath = localVariablePath.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -268,7 +272,7 @@ open class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func updatePet(body: Pet, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func updatePet(body: Pet, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { updatePetWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -289,21 +293,21 @@ open class PetAPI { - returns: RequestBuilder */ open class func updatePetWithRequestBuilder(body: Pet) -> RequestBuilder { - let path = "/pet" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/pet" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "PUT", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -315,7 +319,7 @@ open class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func updatePetWithForm(petId: Int64, name: String? = nil, status: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func updatePetWithForm(petId: Int64, name: String? = nil, status: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { updatePetWithFormWithRequestBuilder(petId: petId, name: name, status: status).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -338,30 +342,30 @@ open class PetAPI { - returns: RequestBuilder */ open class func updatePetWithFormWithRequestBuilder(petId: Int64, name: String? = nil, status: String? = nil) -> RequestBuilder { - var path = "/pet/{petId}" + var localVariablePath = "/pet/{petId}" let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))" let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" - path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path - let formParams: [String: Any?] = [ + localVariablePath = localVariablePath.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableFormParams: [String: Any?] = [ "name": name?.encodeToJSON(), "status": status?.encodeToJSON(), ] - let nonNullParameters = APIHelper.rejectNil(formParams) - let parameters = APIHelper.convertBoolToString(nonNullParameters) + let localVariableNonNullParameters = APIHelper.rejectNil(localVariableFormParams) + let localVariableParameters = APIHelper.convertBoolToString(localVariableNonNullParameters) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ "Content-Type": "application/x-www-form-urlencoded", ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -373,7 +377,7 @@ open class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func uploadFile(petId: Int64, additionalMetadata: String? = nil, file: URL? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: ApiResponse?, _ error: Error?) -> Void)) { + open class func uploadFile(petId: Int64, additionalMetadata: String? = nil, file: URL? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: ApiResponse?, _ error: Error?) -> Void)) { uploadFileWithRequestBuilder(petId: petId, additionalMetadata: additionalMetadata, file: file).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -396,30 +400,30 @@ open class PetAPI { - returns: RequestBuilder */ open class func uploadFileWithRequestBuilder(petId: Int64, additionalMetadata: String? = nil, file: URL? = nil) -> RequestBuilder { - var path = "/pet/{petId}/uploadImage" + var localVariablePath = "/pet/{petId}/uploadImage" let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))" let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" - path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path - let formParams: [String: Any?] = [ + localVariablePath = localVariablePath.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableFormParams: [String: Any?] = [ "additionalMetadata": additionalMetadata?.encodeToJSON(), "file": file?.encodeToJSON(), ] - let nonNullParameters = APIHelper.rejectNil(formParams) - let parameters = APIHelper.convertBoolToString(nonNullParameters) + let localVariableNonNullParameters = APIHelper.rejectNil(localVariableFormParams) + let localVariableParameters = APIHelper.convertBoolToString(localVariableNonNullParameters) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ "Content-Type": "multipart/form-data", ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -431,7 +435,7 @@ open class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func uploadFileWithRequiredFile(petId: Int64, requiredFile: URL, additionalMetadata: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: ApiResponse?, _ error: Error?) -> Void)) { + open class func uploadFileWithRequiredFile(petId: Int64, requiredFile: URL, additionalMetadata: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: ApiResponse?, _ error: Error?) -> Void)) { uploadFileWithRequiredFileWithRequestBuilder(petId: petId, requiredFile: requiredFile, additionalMetadata: additionalMetadata).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -454,30 +458,29 @@ open class PetAPI { - returns: RequestBuilder */ open class func uploadFileWithRequiredFileWithRequestBuilder(petId: Int64, requiredFile: URL, additionalMetadata: String? = nil) -> RequestBuilder { - var path = "/fake/{petId}/uploadImageWithRequiredFile" + var localVariablePath = "/fake/{petId}/uploadImageWithRequiredFile" let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))" let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" - path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path - let formParams: [String: Any?] = [ + localVariablePath = localVariablePath.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableFormParams: [String: Any?] = [ "additionalMetadata": additionalMetadata?.encodeToJSON(), "requiredFile": requiredFile.encodeToJSON(), ] - let nonNullParameters = APIHelper.rejectNil(formParams) - let parameters = APIHelper.convertBoolToString(nonNullParameters) + let localVariableNonNullParameters = APIHelper.rejectNil(localVariableFormParams) + let localVariableParameters = APIHelper.convertBoolToString(localVariableNonNullParameters) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ "Content-Type": "multipart/form-data", ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } - } diff --git a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift index 501f11f5f21..53c1fed1eb3 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift @@ -6,8 +6,12 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif open class StoreAPI { + /** Delete purchase order by ID @@ -15,7 +19,7 @@ open class StoreAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func deleteOrder(orderId: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func deleteOrder(orderId: String, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { deleteOrderWithRequestBuilder(orderId: orderId).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -34,24 +38,24 @@ open class StoreAPI { - returns: RequestBuilder */ open class func deleteOrderWithRequestBuilder(orderId: String) -> RequestBuilder { - var path = "/store/order/{order_id}" + var localVariablePath = "/store/order/{order_id}" let orderIdPreEscape = "\(APIHelper.mapValueToPathItem(orderId))" let orderIdPostEscape = orderIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" - path = path.replacingOccurrences(of: "{order_id}", with: orderIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + localVariablePath = localVariablePath.replacingOccurrences(of: "{order_id}", with: orderIdPostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "DELETE", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -60,7 +64,7 @@ open class StoreAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func getInventory(apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: [String: Int]?, _ error: Error?) -> Void)) { + open class func getInventory(apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: [String: Int]?, _ error: Error?) -> Void)) { getInventoryWithRequestBuilder().execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -81,21 +85,21 @@ open class StoreAPI { - returns: RequestBuilder<[String: Int]> */ open class func getInventoryWithRequestBuilder() -> RequestBuilder<[String: Int]> { - let path = "/store/inventory" - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + let localVariablePath = "/store/inventory" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder<[String: Int]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder<[String: Int]>.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -105,7 +109,7 @@ open class StoreAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func getOrderById(orderId: Int64, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Order?, _ error: Error?) -> Void)) { + open class func getOrderById(orderId: Int64, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Order?, _ error: Error?) -> Void)) { getOrderByIdWithRequestBuilder(orderId: orderId).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -124,24 +128,24 @@ open class StoreAPI { - returns: RequestBuilder */ open class func getOrderByIdWithRequestBuilder(orderId: Int64) -> RequestBuilder { - var path = "/store/order/{order_id}" + var localVariablePath = "/store/order/{order_id}" let orderIdPreEscape = "\(APIHelper.mapValueToPathItem(orderId))" let orderIdPostEscape = orderIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" - path = path.replacingOccurrences(of: "{order_id}", with: orderIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + localVariablePath = localVariablePath.replacingOccurrences(of: "{order_id}", with: orderIdPostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -151,7 +155,7 @@ open class StoreAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func placeOrder(body: Order, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Order?, _ error: Error?) -> Void)) { + open class func placeOrder(body: Order, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Order?, _ error: Error?) -> Void)) { placeOrderWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -169,21 +173,20 @@ open class StoreAPI { - returns: RequestBuilder */ open class func placeOrderWithRequestBuilder(body: Order) -> RequestBuilder { - let path = "/store/order" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/store/order" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } - } diff --git a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift index 254474014d3..c1e5691390e 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift @@ -6,8 +6,12 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif open class UserAPI { + /** Create user @@ -15,7 +19,7 @@ open class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func createUser(body: User, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func createUser(body: User, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { createUserWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -34,21 +38,21 @@ open class UserAPI { - returns: RequestBuilder */ open class func createUserWithRequestBuilder(body: User) -> RequestBuilder { - let path = "/user" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/user" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -58,7 +62,7 @@ open class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func createUsersWithArrayInput(body: [User], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func createUsersWithArrayInput(body: [User], apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { createUsersWithArrayInputWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -76,21 +80,21 @@ open class UserAPI { - returns: RequestBuilder */ open class func createUsersWithArrayInputWithRequestBuilder(body: [User]) -> RequestBuilder { - let path = "/user/createWithArray" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/user/createWithArray" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -100,7 +104,7 @@ open class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func createUsersWithListInput(body: [User], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func createUsersWithListInput(body: [User], apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { createUsersWithListInputWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -118,21 +122,21 @@ open class UserAPI { - returns: RequestBuilder */ open class func createUsersWithListInputWithRequestBuilder(body: [User]) -> RequestBuilder { - let path = "/user/createWithList" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/user/createWithList" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -142,7 +146,7 @@ open class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func deleteUser(username: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func deleteUser(username: String, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { deleteUserWithRequestBuilder(username: username).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -161,24 +165,24 @@ open class UserAPI { - returns: RequestBuilder */ open class func deleteUserWithRequestBuilder(username: String) -> RequestBuilder { - var path = "/user/{username}" + var localVariablePath = "/user/{username}" let usernamePreEscape = "\(APIHelper.mapValueToPathItem(username))" let usernamePostEscape = usernamePreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" - path = path.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + localVariablePath = localVariablePath.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "DELETE", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -188,7 +192,7 @@ open class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func getUserByName(username: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: User?, _ error: Error?) -> Void)) { + open class func getUserByName(username: String, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: User?, _ error: Error?) -> Void)) { getUserByNameWithRequestBuilder(username: username).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -206,24 +210,24 @@ open class UserAPI { - returns: RequestBuilder */ open class func getUserByNameWithRequestBuilder(username: String) -> RequestBuilder { - var path = "/user/{username}" + var localVariablePath = "/user/{username}" let usernamePreEscape = "\(APIHelper.mapValueToPathItem(username))" let usernamePostEscape = usernamePreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" - path = path.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + localVariablePath = localVariablePath.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -234,7 +238,7 @@ open class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func loginUser(username: String, password: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: String?, _ error: Error?) -> Void)) { + open class func loginUser(username: String, password: String, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: String?, _ error: Error?) -> Void)) { loginUserWithRequestBuilder(username: username, password: password).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -254,25 +258,25 @@ open class UserAPI { - returns: RequestBuilder */ open class func loginUserWithRequestBuilder(username: String, password: String) -> RequestBuilder { - let path = "/user/login" - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + let localVariablePath = "/user/login" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - var urlComponents = URLComponents(string: URLString) - urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ + var localVariableUrlComponents = URLComponents(string: localVariableURLString) + localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ "username": username.encodeToJSON(), "password": password.encodeToJSON(), ]) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -281,7 +285,7 @@ open class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func logoutUser(apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func logoutUser(apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { logoutUserWithRequestBuilder().execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -298,21 +302,21 @@ open class UserAPI { - returns: RequestBuilder */ open class func logoutUserWithRequestBuilder() -> RequestBuilder { - let path = "/user/logout" - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + let localVariablePath = "/user/logout" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -323,7 +327,7 @@ open class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func updateUser(username: String, body: User, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func updateUser(username: String, body: User, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { updateUserWithRequestBuilder(username: username, body: body).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -343,24 +347,23 @@ open class UserAPI { - returns: RequestBuilder */ open class func updateUserWithRequestBuilder(username: String, body: User) -> RequestBuilder { - var path = "/user/{username}" + var localVariablePath = "/user/{username}" let usernamePreEscape = "\(APIHelper.mapValueToPathItem(username))" let usernamePostEscape = usernamePreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" - path = path.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + localVariablePath = localVariablePath.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "PUT", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } - } diff --git a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/AlamofireImplementations.swift b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/AlamofireImplementations.swift index f26fae21f71..aa8dcad9b65 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/AlamofireImplementations.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/AlamofireImplementations.swift @@ -40,7 +40,7 @@ open class AlamofireRequestBuilder: RequestBuilder { */ open func createURLRequest() -> URLRequest? { guard let xMethod = Alamofire.HTTPMethod(rawValue: method) else { - fatalError("Unsuported Http method - \(method)") + fatalError("Unsupported Http method - \(method)") } let encoding: ParameterEncoding @@ -76,14 +76,14 @@ open class AlamofireRequestBuilder: RequestBuilder { return manager.request(URLString, method: method, parameters: parameters, encoding: encoding, headers: headers) } - override open func execute(_ apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, _ completion: @escaping (_ result: Swift.Result, Error>) -> Void) { + override open func execute(_ apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, _ completion: @escaping (_ result: Swift.Result, Error>) -> Void) { let managerId = UUID().uuidString // Create a new manager for each request to customize its request header let manager = createSessionManager() managerStore[managerId] = manager guard let xMethod = Alamofire.HTTPMethod(rawValue: method) else { - fatalError("Unsuported Http method - \(method)") + fatalError("Unsupported Http method - \(method)") } let encoding: ParameterEncoding? @@ -133,7 +133,7 @@ open class AlamofireRequestBuilder: RequestBuilder { } else if contentType == "application/x-www-form-urlencoded" { encoding = URLEncoding(destination: .httpBody) } else { - fatalError("Unsuported Media Type - \(contentType)") + fatalError("Unsupported Media Type - \(contentType)") } } @@ -190,16 +190,18 @@ open class AlamofireRequestBuilder: RequestBuilder { let fileManager = FileManager.default let urlRequest = try request.asURLRequest() - let documentsDirectory = fileManager.urls(for: .documentDirectory, in: .userDomainMask)[0] + let cachesDirectory = fileManager.urls(for: .cachesDirectory, in: .userDomainMask)[0] let requestURL = try self.getURL(from: urlRequest) var requestPath = try self.getPath(from: requestURL) if let headerFileName = self.getFileName(fromContentDisposition: dataResponse.response?.allHeaderFields["Content-Disposition"] as? String) { requestPath = requestPath.appending("/\(headerFileName)") + } else { + requestPath = requestPath.appending("/tmp.PetstoreClient.\(UUID().uuidString)") } - let filePath = documentsDirectory.appendingPathComponent(requestPath) + let filePath = cachesDirectory.appendingPathComponent(requestPath) let directoryPath = filePath.deletingLastPathComponent().path try fileManager.createDirectory(atPath: directoryPath, withIntermediateDirectories: true, attributes: nil) @@ -225,6 +227,18 @@ open class AlamofireRequestBuilder: RequestBuilder { completion(.failure(ErrorResponse.error(voidResponse.response?.statusCode ?? 500, voidResponse.data, voidResponse.response, error))) } + }) + case is Data.Type: + validatedRequest.responseData(queue: apiResponseQueue, completionHandler: { dataResponse in + cleanupRequest() + + switch dataResponse.result { + case .success: + completion(.success(Response(response: dataResponse.response!, body: dataResponse.data as? T))) + case let .failure(error): + completion(.failure(ErrorResponse.error(dataResponse.response?.statusCode ?? 500, dataResponse.data, dataResponse.response, error))) + } + }) default: validatedRequest.responseData(queue: apiResponseQueue, completionHandler: { dataResponse in @@ -328,6 +342,52 @@ open class AlamofireDecodableRequestBuilder: AlamofireRequestBuild } }) + case is URL.Type: + validatedRequest.responseData(queue: apiResponseQueue, completionHandler: { dataResponse in + cleanupRequest() + + do { + + guard !dataResponse.result.isFailure else { + throw DownloadException.responseFailed + } + + guard let data = dataResponse.data else { + throw DownloadException.responseDataMissing + } + + guard let request = request.request else { + throw DownloadException.requestMissing + } + + let fileManager = FileManager.default + let urlRequest = try request.asURLRequest() + let cachesDirectory = fileManager.urls(for: .cachesDirectory, in: .userDomainMask)[0] + let requestURL = try self.getURL(from: urlRequest) + + var requestPath = try self.getPath(from: requestURL) + + if let headerFileName = self.getFileName(fromContentDisposition: dataResponse.response?.allHeaderFields["Content-Disposition"] as? String) { + requestPath = requestPath.appending("/\(headerFileName)") + } else { + requestPath = requestPath.appending("/tmp.PetstoreClient.\(UUID().uuidString)") + } + + let filePath = cachesDirectory.appendingPathComponent(requestPath) + let directoryPath = filePath.deletingLastPathComponent().path + + try fileManager.createDirectory(atPath: directoryPath, withIntermediateDirectories: true, attributes: nil) + try data.write(to: filePath, options: .atomic) + + completion(.success(Response(response: dataResponse.response!, body: filePath as? T))) + + } catch let requestParserError as DownloadException { + completion(.failure(ErrorResponse.error(400, dataResponse.data, dataResponse.response, requestParserError))) + } catch { + completion(.failure(ErrorResponse.error(400, dataResponse.data, dataResponse.response, error))) + } + return + }) case is Void.Type: validatedRequest.responseData(queue: apiResponseQueue, completionHandler: { voidResponse in cleanupRequest() diff --git a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Configuration.swift b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Configuration.swift index 18edabbed78..8fb05331889 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Configuration.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Configuration.swift @@ -7,6 +7,7 @@ import Foundation open class Configuration { + // This value is used to configure the date formatter that is used to serialize dates into JSON format. // You must set it prior to encoding any dates, and it will only be read once. @available(*, unavailable, message: "To set a different date format, use CodableHelper.dateFormatter instead.") diff --git a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Extensions.swift b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Extensions.swift index 3aef2d1d6c5..e23035dde30 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Extensions.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Extensions.swift @@ -5,7 +5,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif extension Bool: JSONEncodable { func encodeToJSON() -> Any { return self as Any } @@ -184,44 +186,3 @@ extension HTTPURLResponse { return Array(200 ..< 300).contains(statusCode) } } - -extension AnyCodable: Hashable { - public func hash(into hasher: inout Hasher) { - switch value { - case let value as Bool: - hasher.combine(value) - case let value as Int: - hasher.combine(value) - case let value as Int8: - hasher.combine(value) - case let value as Int16: - hasher.combine(value) - case let value as Int32: - hasher.combine(value) - case let value as Int64: - hasher.combine(value) - case let value as UInt: - hasher.combine(value) - case let value as UInt8: - hasher.combine(value) - case let value as UInt16: - hasher.combine(value) - case let value as UInt32: - hasher.combine(value) - case let value as UInt64: - hasher.combine(value) - case let value as Float: - hasher.combine(value) - case let value as Double: - hasher.combine(value) - case let value as String: - hasher.combine(value) - case let value as [String: AnyCodable]: - hasher.combine(value) - case let value as [AnyCodable]: - hasher.combine(value) - default: - hasher.combine(0) - } - } -} \ No newline at end of file diff --git a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesClass.swift b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesClass.swift index 75ab9bc8d0a..621afb93561 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesClass.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesClass.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct AdditionalPropertiesClass: Codable, Hashable { @@ -17,6 +19,7 @@ public struct AdditionalPropertiesClass: Codable, Hashable { self.mapString = mapString self.mapMapString = mapMapString } + public enum CodingKeys: String, CodingKey, CaseIterable { case mapString = "map_string" case mapMapString = "map_map_string" @@ -29,7 +32,5 @@ public struct AdditionalPropertiesClass: Codable, Hashable { try container.encodeIfPresent(mapString, forKey: .mapString) try container.encodeIfPresent(mapMapString, forKey: .mapMapString) } - - - } + diff --git a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/Animal.swift b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/Animal.swift index 0f825cf24d0..cdd4f5335b9 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/Animal.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/Animal.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct Animal: Codable, Hashable { @@ -17,6 +19,7 @@ public struct Animal: Codable, Hashable { self.className = className self.color = color } + public enum CodingKeys: String, CodingKey, CaseIterable { case className case color @@ -29,7 +32,5 @@ public struct Animal: Codable, Hashable { try container.encode(className, forKey: .className) try container.encodeIfPresent(color, forKey: .color) } - - - } + diff --git a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/AnimalFarm.swift b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/AnimalFarm.swift index b20b894a1ad..a0b09cb9761 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/AnimalFarm.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/AnimalFarm.swift @@ -6,6 +6,8 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public typealias AnimalFarm = [Animal] diff --git a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift index 2b66af2dc94..c365505ab9d 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct ApiResponse: Codable, Hashable { @@ -19,6 +21,7 @@ public struct ApiResponse: Codable, Hashable { self.type = type self.message = message } + public enum CodingKeys: String, CodingKey, CaseIterable { case code case type @@ -33,7 +36,5 @@ public struct ApiResponse: Codable, Hashable { try container.encodeIfPresent(type, forKey: .type) try container.encodeIfPresent(message, forKey: .message) } - - - } + diff --git a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfArrayOfNumberOnly.swift b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfArrayOfNumberOnly.swift index 06f0640475c..226f7456181 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfArrayOfNumberOnly.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfArrayOfNumberOnly.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct ArrayOfArrayOfNumberOnly: Codable, Hashable { @@ -15,6 +17,7 @@ public struct ArrayOfArrayOfNumberOnly: Codable, Hashable { public init(arrayArrayNumber: [[Double]]? = nil) { self.arrayArrayNumber = arrayArrayNumber } + public enum CodingKeys: String, CodingKey, CaseIterable { case arrayArrayNumber = "ArrayArrayNumber" } @@ -25,7 +28,5 @@ public struct ArrayOfArrayOfNumberOnly: Codable, Hashable { var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(arrayArrayNumber, forKey: .arrayArrayNumber) } - - - } + diff --git a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfNumberOnly.swift b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfNumberOnly.swift index 8c50c7fa1e4..39831127871 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfNumberOnly.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfNumberOnly.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct ArrayOfNumberOnly: Codable, Hashable { @@ -15,6 +17,7 @@ public struct ArrayOfNumberOnly: Codable, Hashable { public init(arrayNumber: [Double]? = nil) { self.arrayNumber = arrayNumber } + public enum CodingKeys: String, CodingKey, CaseIterable { case arrayNumber = "ArrayNumber" } @@ -25,7 +28,5 @@ public struct ArrayOfNumberOnly: Codable, Hashable { var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(arrayNumber, forKey: .arrayNumber) } - - - } + diff --git a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayTest.swift b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayTest.swift index 461ec7cd9ac..8865d76bef2 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayTest.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayTest.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct ArrayTest: Codable, Hashable { @@ -19,6 +21,7 @@ public struct ArrayTest: Codable, Hashable { self.arrayArrayOfInteger = arrayArrayOfInteger self.arrayArrayOfModel = arrayArrayOfModel } + public enum CodingKeys: String, CodingKey, CaseIterable { case arrayOfString = "array_of_string" case arrayArrayOfInteger = "array_array_of_integer" @@ -33,7 +36,5 @@ public struct ArrayTest: Codable, Hashable { try container.encodeIfPresent(arrayArrayOfInteger, forKey: .arrayArrayOfInteger) try container.encodeIfPresent(arrayArrayOfModel, forKey: .arrayArrayOfModel) } - - - } + diff --git a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/Capitalization.swift b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/Capitalization.swift index fbe62983d5e..71cd93bce5f 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/Capitalization.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/Capitalization.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct Capitalization: Codable, Hashable { @@ -26,6 +28,7 @@ public struct Capitalization: Codable, Hashable { self.sCAETHFlowPoints = sCAETHFlowPoints self.ATT_NAME = ATT_NAME } + public enum CodingKeys: String, CodingKey, CaseIterable { case smallCamel case capitalCamel = "CapitalCamel" @@ -46,7 +49,5 @@ public struct Capitalization: Codable, Hashable { try container.encodeIfPresent(sCAETHFlowPoints, forKey: .sCAETHFlowPoints) try container.encodeIfPresent(ATT_NAME, forKey: .ATT_NAME) } - - - } + diff --git a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/Cat.swift b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/Cat.swift index 7f3a86932f1..457e04bd475 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/Cat.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/Cat.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct Cat: Codable, Hashable { @@ -19,6 +21,7 @@ public struct Cat: Codable, Hashable { self.color = color self.declawed = declawed } + public enum CodingKeys: String, CodingKey, CaseIterable { case className case color @@ -33,7 +36,5 @@ public struct Cat: Codable, Hashable { try container.encodeIfPresent(color, forKey: .color) try container.encodeIfPresent(declawed, forKey: .declawed) } - - - } + diff --git a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/CatAllOf.swift b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/CatAllOf.swift index 8df23954832..8caebb1c206 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/CatAllOf.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/CatAllOf.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct CatAllOf: Codable, Hashable { @@ -15,6 +17,7 @@ public struct CatAllOf: Codable, Hashable { public init(declawed: Bool? = nil) { self.declawed = declawed } + public enum CodingKeys: String, CodingKey, CaseIterable { case declawed } @@ -25,7 +28,5 @@ public struct CatAllOf: Codable, Hashable { var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(declawed, forKey: .declawed) } - - - } + diff --git a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/Category.swift b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/Category.swift index 4109db4d1ef..89016ca353d 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/Category.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/Category.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct Category: Codable, Hashable { @@ -17,6 +19,7 @@ public struct Category: Codable, Hashable { self.id = id self.name = name } + public enum CodingKeys: String, CodingKey, CaseIterable { case id case name @@ -29,7 +32,5 @@ public struct Category: Codable, Hashable { try container.encodeIfPresent(id, forKey: .id) try container.encode(name, forKey: .name) } - - - } + diff --git a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/ClassModel.swift b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/ClassModel.swift index 7269ddbef6f..16e69e560bd 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/ClassModel.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/ClassModel.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif /** Model for testing model with \"_class\" property */ public struct ClassModel: Codable, Hashable { @@ -16,6 +18,7 @@ public struct ClassModel: Codable, Hashable { public init(_class: String? = nil) { self._class = _class } + public enum CodingKeys: String, CodingKey, CaseIterable { case _class } @@ -26,7 +29,5 @@ public struct ClassModel: Codable, Hashable { var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(_class, forKey: ._class) } - - - } + diff --git a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/Client.swift b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/Client.swift index 7d6eff2ffe1..60dbc5dc5c1 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/Client.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/Client.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct Client: Codable, Hashable { @@ -15,6 +17,7 @@ public struct Client: Codable, Hashable { public init(client: String? = nil) { self.client = client } + public enum CodingKeys: String, CodingKey, CaseIterable { case client } @@ -25,7 +28,5 @@ public struct Client: Codable, Hashable { var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(client, forKey: .client) } - - - } + diff --git a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/Dog.swift b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/Dog.swift index b5f2bcea38a..658732a7f36 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/Dog.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/Dog.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct Dog: Codable, Hashable { @@ -19,6 +21,7 @@ public struct Dog: Codable, Hashable { self.color = color self.breed = breed } + public enum CodingKeys: String, CodingKey, CaseIterable { case className case color @@ -33,7 +36,5 @@ public struct Dog: Codable, Hashable { try container.encodeIfPresent(color, forKey: .color) try container.encodeIfPresent(breed, forKey: .breed) } - - - } + diff --git a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/DogAllOf.swift b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/DogAllOf.swift index 1bfa23d7bc6..82b0dedf35b 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/DogAllOf.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/DogAllOf.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct DogAllOf: Codable, Hashable { @@ -15,6 +17,7 @@ public struct DogAllOf: Codable, Hashable { public init(breed: String? = nil) { self.breed = breed } + public enum CodingKeys: String, CodingKey, CaseIterable { case breed } @@ -25,7 +28,5 @@ public struct DogAllOf: Codable, Hashable { var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(breed, forKey: .breed) } - - - } + diff --git a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumArrays.swift b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumArrays.swift index 73368c42143..1d8ce99539c 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumArrays.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumArrays.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct EnumArrays: Codable, Hashable { @@ -25,6 +27,7 @@ public struct EnumArrays: Codable, Hashable { self.justSymbol = justSymbol self.arrayEnum = arrayEnum } + public enum CodingKeys: String, CodingKey, CaseIterable { case justSymbol = "just_symbol" case arrayEnum = "array_enum" @@ -37,7 +40,5 @@ public struct EnumArrays: Codable, Hashable { try container.encodeIfPresent(justSymbol, forKey: .justSymbol) try container.encodeIfPresent(arrayEnum, forKey: .arrayEnum) } - - - } + diff --git a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumClass.swift b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumClass.swift index ab01cf297f8..6ea2895aee5 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumClass.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumClass.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public enum EnumClass: String, Codable, CaseIterable { case abc = "_abc" diff --git a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumTest.swift b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumTest.swift index 60a81bcac77..8c8bca49774 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumTest.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumTest.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct EnumTest: Codable, Hashable { @@ -41,6 +43,7 @@ public struct EnumTest: Codable, Hashable { self.enumNumber = enumNumber self.outerEnum = outerEnum } + public enum CodingKeys: String, CodingKey, CaseIterable { case enumString = "enum_string" case enumStringRequired = "enum_string_required" @@ -59,7 +62,5 @@ public struct EnumTest: Codable, Hashable { try container.encodeIfPresent(enumNumber, forKey: .enumNumber) try container.encodeIfPresent(outerEnum, forKey: .outerEnum) } - - - } + diff --git a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/File.swift b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/File.swift index 90283656d1b..05dd5b1a825 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/File.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/File.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif /** Must be named `File` for test. */ public struct File: Codable, Hashable { @@ -17,6 +19,7 @@ public struct File: Codable, Hashable { public init(sourceURI: String? = nil) { self.sourceURI = sourceURI } + public enum CodingKeys: String, CodingKey, CaseIterable { case sourceURI } @@ -27,7 +30,5 @@ public struct File: Codable, Hashable { var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(sourceURI, forKey: .sourceURI) } - - - } + diff --git a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/FileSchemaTestClass.swift b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/FileSchemaTestClass.swift index cff92673bbe..3ca66a31359 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/FileSchemaTestClass.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/FileSchemaTestClass.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct FileSchemaTestClass: Codable, Hashable { @@ -17,6 +19,7 @@ public struct FileSchemaTestClass: Codable, Hashable { self.file = file self.files = files } + public enum CodingKeys: String, CodingKey, CaseIterable { case file case files @@ -29,7 +32,5 @@ public struct FileSchemaTestClass: Codable, Hashable { try container.encodeIfPresent(file, forKey: .file) try container.encodeIfPresent(files, forKey: .files) } - - - } + diff --git a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/FormatTest.swift b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/FormatTest.swift index fc86676eec3..a7a4b39e720 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/FormatTest.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/FormatTest.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct FormatTest: Codable, Hashable { @@ -39,6 +41,7 @@ public struct FormatTest: Codable, Hashable { self.uuid = uuid self.password = password } + public enum CodingKeys: String, CodingKey, CaseIterable { case integer case int32 @@ -73,7 +76,5 @@ public struct FormatTest: Codable, Hashable { try container.encodeIfPresent(uuid, forKey: .uuid) try container.encode(password, forKey: .password) } - - - } + diff --git a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/HasOnlyReadOnly.swift b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/HasOnlyReadOnly.swift index d7960f5c800..54ed8a723c6 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/HasOnlyReadOnly.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/HasOnlyReadOnly.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct HasOnlyReadOnly: Codable, Hashable { @@ -17,6 +19,7 @@ public struct HasOnlyReadOnly: Codable, Hashable { self.bar = bar self.foo = foo } + public enum CodingKeys: String, CodingKey, CaseIterable { case bar case foo @@ -29,7 +32,5 @@ public struct HasOnlyReadOnly: Codable, Hashable { try container.encodeIfPresent(bar, forKey: .bar) try container.encodeIfPresent(foo, forKey: .foo) } - - - } + diff --git a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/List.swift b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/List.swift index c5d4f2cae56..67e3048469f 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/List.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/List.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct List: Codable, Hashable { @@ -15,6 +17,7 @@ public struct List: Codable, Hashable { public init(_123list: String? = nil) { self._123list = _123list } + public enum CodingKeys: String, CodingKey, CaseIterable { case _123list = "123-list" } @@ -25,7 +28,5 @@ public struct List: Codable, Hashable { var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(_123list, forKey: ._123list) } - - - } + diff --git a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/MapTest.swift b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/MapTest.swift index b54bd01e5dc..1e728fcdf58 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/MapTest.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/MapTest.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct MapTest: Codable, Hashable { @@ -25,6 +27,7 @@ public struct MapTest: Codable, Hashable { self.directMap = directMap self.indirectMap = indirectMap } + public enum CodingKeys: String, CodingKey, CaseIterable { case mapMapOfString = "map_map_of_string" case mapOfEnumString = "map_of_enum_string" @@ -41,7 +44,5 @@ public struct MapTest: Codable, Hashable { try container.encodeIfPresent(directMap, forKey: .directMap) try container.encodeIfPresent(indirectMap, forKey: .indirectMap) } - - - } + diff --git a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/MixedPropertiesAndAdditionalPropertiesClass.swift b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/MixedPropertiesAndAdditionalPropertiesClass.swift index c8f639ef43d..c79ca459217 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/MixedPropertiesAndAdditionalPropertiesClass.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/MixedPropertiesAndAdditionalPropertiesClass.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct MixedPropertiesAndAdditionalPropertiesClass: Codable, Hashable { @@ -19,6 +21,7 @@ public struct MixedPropertiesAndAdditionalPropertiesClass: Codable, Hashable { self.dateTime = dateTime self.map = map } + public enum CodingKeys: String, CodingKey, CaseIterable { case uuid case dateTime @@ -33,7 +36,5 @@ public struct MixedPropertiesAndAdditionalPropertiesClass: Codable, Hashable { try container.encodeIfPresent(dateTime, forKey: .dateTime) try container.encodeIfPresent(map, forKey: .map) } - - - } + diff --git a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/Model200Response.swift b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/Model200Response.swift index 5368032f09b..23402143f71 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/Model200Response.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/Model200Response.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif /** Model for testing model name starting with number */ public struct Model200Response: Codable, Hashable { @@ -18,6 +20,7 @@ public struct Model200Response: Codable, Hashable { self.name = name self._class = _class } + public enum CodingKeys: String, CodingKey, CaseIterable { case name case _class = "class" @@ -30,7 +33,5 @@ public struct Model200Response: Codable, Hashable { try container.encodeIfPresent(name, forKey: .name) try container.encodeIfPresent(_class, forKey: ._class) } - - - } + diff --git a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/Name.swift b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/Name.swift index 84a40e1c101..a28f46a33ce 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/Name.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/Name.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif /** Model for testing model name same as property name */ public struct Name: Codable, Hashable { @@ -22,6 +24,7 @@ public struct Name: Codable, Hashable { self.property = property self._123number = _123number } + public enum CodingKeys: String, CodingKey, CaseIterable { case name case snakeCase = "snake_case" @@ -38,7 +41,5 @@ public struct Name: Codable, Hashable { try container.encodeIfPresent(property, forKey: .property) try container.encodeIfPresent(_123number, forKey: ._123number) } - - - } + diff --git a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/NumberOnly.swift b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/NumberOnly.swift index 710f41648f9..87ceb64bb97 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/NumberOnly.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/NumberOnly.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct NumberOnly: Codable, Hashable { @@ -15,6 +17,7 @@ public struct NumberOnly: Codable, Hashable { public init(justNumber: Double? = nil) { self.justNumber = justNumber } + public enum CodingKeys: String, CodingKey, CaseIterable { case justNumber = "JustNumber" } @@ -25,7 +28,5 @@ public struct NumberOnly: Codable, Hashable { var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(justNumber, forKey: .justNumber) } - - - } + diff --git a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/Order.swift b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/Order.swift index 15726ab16a4..e2eeced4c57 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/Order.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/Order.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct Order: Codable, Hashable { @@ -31,6 +33,7 @@ public struct Order: Codable, Hashable { self.status = status self.complete = complete } + public enum CodingKeys: String, CodingKey, CaseIterable { case id case petId @@ -51,7 +54,5 @@ public struct Order: Codable, Hashable { try container.encodeIfPresent(status, forKey: .status) try container.encodeIfPresent(complete, forKey: .complete) } - - - } + diff --git a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/OuterComposite.swift b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/OuterComposite.swift index 36904afbd50..edeaccaeaa6 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/OuterComposite.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/OuterComposite.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct OuterComposite: Codable, Hashable { @@ -19,6 +21,7 @@ public struct OuterComposite: Codable, Hashable { self.myString = myString self.myBoolean = myBoolean } + public enum CodingKeys: String, CodingKey, CaseIterable { case myNumber = "my_number" case myString = "my_string" @@ -33,7 +36,5 @@ public struct OuterComposite: Codable, Hashable { try container.encodeIfPresent(myString, forKey: .myString) try container.encodeIfPresent(myBoolean, forKey: .myBoolean) } - - - } + diff --git a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/OuterEnum.swift b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/OuterEnum.swift index 9bd6f3bef8f..76c34b3c2ce 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/OuterEnum.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/OuterEnum.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public enum OuterEnum: String, Codable, CaseIterable { case placed = "placed" diff --git a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/Pet.swift b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/Pet.swift index 7a1c2826a19..ddd1186b891 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/Pet.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/Pet.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct Pet: Codable, Hashable { @@ -31,6 +33,7 @@ public struct Pet: Codable, Hashable { self.tags = tags self.status = status } + public enum CodingKeys: String, CodingKey, CaseIterable { case id case category @@ -51,7 +54,5 @@ public struct Pet: Codable, Hashable { try container.encodeIfPresent(tags, forKey: .tags) try container.encodeIfPresent(status, forKey: .status) } - - - } + diff --git a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/ReadOnlyFirst.swift b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/ReadOnlyFirst.swift index 38fb57af328..57ba3f577c8 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/ReadOnlyFirst.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/ReadOnlyFirst.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct ReadOnlyFirst: Codable, Hashable { @@ -17,6 +19,7 @@ public struct ReadOnlyFirst: Codable, Hashable { self.bar = bar self.baz = baz } + public enum CodingKeys: String, CodingKey, CaseIterable { case bar case baz @@ -29,7 +32,5 @@ public struct ReadOnlyFirst: Codable, Hashable { try container.encodeIfPresent(bar, forKey: .bar) try container.encodeIfPresent(baz, forKey: .baz) } - - - } + diff --git a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/Return.swift b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/Return.swift index ed7e538a06d..afc2b51f8f3 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/Return.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/Return.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif /** Model for testing reserved words */ public struct Return: Codable, Hashable { @@ -16,6 +18,7 @@ public struct Return: Codable, Hashable { public init(_return: Int? = nil) { self._return = _return } + public enum CodingKeys: String, CodingKey, CaseIterable { case _return = "return" } @@ -26,7 +29,5 @@ public struct Return: Codable, Hashable { var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(_return, forKey: ._return) } - - - } + diff --git a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/SpecialModelName.swift b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/SpecialModelName.swift index 18747e071bc..bfe9723f888 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/SpecialModelName.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/SpecialModelName.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct SpecialModelName: Codable, Hashable { @@ -15,6 +17,7 @@ public struct SpecialModelName: Codable, Hashable { public init(specialPropertyName: Int64? = nil) { self.specialPropertyName = specialPropertyName } + public enum CodingKeys: String, CodingKey, CaseIterable { case specialPropertyName = "$special[property.name]" } @@ -25,7 +28,5 @@ public struct SpecialModelName: Codable, Hashable { var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(specialPropertyName, forKey: .specialPropertyName) } - - - } + diff --git a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/StringBooleanMap.swift b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/StringBooleanMap.swift index 0699c25ff7e..126c35c85a6 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/StringBooleanMap.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/StringBooleanMap.swift @@ -6,12 +6,16 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct StringBooleanMap: Codable, Hashable { + public enum CodingKeys: CodingKey, CaseIterable { } + public var additionalProperties: [String: Bool] = [:] public subscript(key: String) -> Bool? { @@ -38,11 +42,11 @@ public struct StringBooleanMap: Codable, Hashable { // Decodable protocol methods public init(from decoder: Decoder) throws { - let container = try decoder.container(keyedBy: String.self) + let container = try decoder.container(keyedBy: CodingKeys.self) var nonAdditionalPropertyKeys = Set() - additionalProperties = try container.decodeMap(Bool.self, excludedKeys: nonAdditionalPropertyKeys) + let additionalPropertiesContainer = try decoder.container(keyedBy: String.self) + additionalProperties = try additionalPropertiesContainer.decodeMap(Bool.self, excludedKeys: nonAdditionalPropertyKeys) } - - } + diff --git a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift index 11c5f7a750b..07b826264f3 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct Tag: Codable, Hashable { @@ -17,6 +19,7 @@ public struct Tag: Codable, Hashable { self.id = id self.name = name } + public enum CodingKeys: String, CodingKey, CaseIterable { case id case name @@ -29,7 +32,5 @@ public struct Tag: Codable, Hashable { try container.encodeIfPresent(id, forKey: .id) try container.encodeIfPresent(name, forKey: .name) } - - - } + diff --git a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderDefault.swift b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderDefault.swift index 35b1a5833b9..e58eecd960f 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderDefault.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderDefault.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct TypeHolderDefault: Codable, Hashable { @@ -23,6 +25,7 @@ public struct TypeHolderDefault: Codable, Hashable { self.boolItem = boolItem self.arrayItem = arrayItem } + public enum CodingKeys: String, CodingKey, CaseIterable { case stringItem = "string_item" case numberItem = "number_item" @@ -41,7 +44,5 @@ public struct TypeHolderDefault: Codable, Hashable { try container.encode(boolItem, forKey: .boolItem) try container.encode(arrayItem, forKey: .arrayItem) } - - - } + diff --git a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderExample.swift b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderExample.swift index 37277a4ac00..6c22fdbae7a 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderExample.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderExample.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct TypeHolderExample: Codable, Hashable { @@ -23,6 +25,7 @@ public struct TypeHolderExample: Codable, Hashable { self.boolItem = boolItem self.arrayItem = arrayItem } + public enum CodingKeys: String, CodingKey, CaseIterable { case stringItem = "string_item" case numberItem = "number_item" @@ -41,7 +44,5 @@ public struct TypeHolderExample: Codable, Hashable { try container.encode(boolItem, forKey: .boolItem) try container.encode(arrayItem, forKey: .arrayItem) } - - - } + diff --git a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/User.swift b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/User.swift index 2bbc31806ff..7afe359ae40 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/User.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/User.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct User: Codable, Hashable { @@ -30,6 +32,7 @@ public struct User: Codable, Hashable { self.phone = phone self.userStatus = userStatus } + public enum CodingKeys: String, CodingKey, CaseIterable { case id case username @@ -54,7 +57,5 @@ public struct User: Codable, Hashable { try container.encodeIfPresent(phone, forKey: .phone) try container.encodeIfPresent(userStatus, forKey: .userStatus) } - - - } + diff --git a/samples/client/petstore/swift5/alamofireLibrary/SwaggerClientTests/.gitignore b/samples/client/petstore/swift5/alamofireLibrary/SwaggerClientTests/.gitignore index 0269c2f56db..22029d2f644 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/SwaggerClientTests/.gitignore +++ b/samples/client/petstore/swift5/alamofireLibrary/SwaggerClientTests/.gitignore @@ -1,14 +1,22 @@ -### https://raw.github.com/github/gitignore/7792e50daeaa6c07460484704671d1dc9f0045a7/Swift.gitignore +# Created by https://www.toptal.com/developers/gitignore/api/swift,xcode +# Edit at https://www.toptal.com/developers/gitignore?templates=swift,xcode +### Swift ### # Xcode # # gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore -## Build generated +## User settings +xcuserdata/ + +## compatibility with Xcode 8 and earlier (ignoring not required starting Xcode 9) +*.xcscmblueprint +*.xccheckout + +## compatibility with Xcode 3 and earlier (ignoring not required starting Xcode 4) build/ DerivedData/ - -## Various settings +*.moved-aside *.pbxuser !default.pbxuser *.mode1v3 @@ -17,15 +25,11 @@ DerivedData/ !default.mode2v3 *.perspectivev3 !default.perspectivev3 -xcuserdata/ - -## Other -*.moved-aside -*.xccheckout -*.xcscmblueprint ## Obj-C/Swift specific *.hmap + +## App packaging *.ipa *.dSYM.zip *.dSYM @@ -35,38 +39,67 @@ timeline.xctimeline playground.xcworkspace # Swift Package Manager -# # Add this line if you want to avoid checking in source code from Swift Package Manager dependencies. # Packages/ # Package.pins # Package.resolved +# *.xcodeproj +# Xcode automatically generates this directory with a .xcworkspacedata file and xcuserdata +# hence it is not needed unless you have added a package configuration file to your project +# .swiftpm + .build/ # CocoaPods -# # We recommend against adding the Pods directory to your .gitignore. However # you should judge for yourself, the pros and cons are mentioned at: # https://guides.cocoapods.org/using/using-cocoapods.html#should-i-check-the-pods-directory-into-source-control -# -Pods/ +# Pods/ +# Add this line if you want to avoid checking in source code from the Xcode workspace +# *.xcworkspace # Carthage -# # Add this line if you want to avoid checking in source code from Carthage dependencies. -Carthage/Checkouts +# Carthage/Checkouts -Carthage/Build +Carthage/Build/ + +# Add this lines if you are using Accio dependency management (Deprecated since Xcode 12) +# Dependencies/ +# .accio/ # fastlane -# -# It is recommended to not store the screenshots in the git repo. Instead, use fastlane to re-generate the -# screenshots whenever they are needed. +# It is recommended to not store the screenshots in the git repo. +# Instead, use fastlane to re-generate the screenshots whenever they are needed. # For more information about the recommended setup visit: # https://docs.fastlane.tools/best-practices/source-control/#source-control fastlane/report.xml fastlane/Preview.html -fastlane/screenshots +fastlane/screenshots/**/*.png fastlane/test_output +# Code Injection +# After new code Injection tools there's a generated folder /iOSInjectionProject +# https://github.com/johnno1962/injectionforxcode +iOSInjectionProject/ + +### Xcode ### +# Xcode +# gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore + + + + +## Gcc Patch +/*.gcno + +### Xcode Patch ### +*.xcodeproj/* +!*.xcodeproj/project.pbxproj +!*.xcodeproj/xcshareddata/ +!*.xcworkspace/contents.xcworkspacedata +**/xcshareddata/WorkspaceSettings.xcsettings + +# End of https://www.toptal.com/developers/gitignore/api/swift,xcode \ No newline at end of file diff --git a/samples/client/petstore/swift5/alamofireLibrary/SwaggerClientTests/Podfile b/samples/client/petstore/swift5/alamofireLibrary/SwaggerClientTests/Podfile deleted file mode 100644 index 77432f9eee9..00000000000 --- a/samples/client/petstore/swift5/alamofireLibrary/SwaggerClientTests/Podfile +++ /dev/null @@ -1,13 +0,0 @@ -platform :ios, '9.0' - -source 'https://cdn.cocoapods.org/' - -use_frameworks! - -target 'SwaggerClient' do - pod "PetstoreClient", :path => "../" - - target 'SwaggerClientTests' do - inherit! :search_paths - end -end diff --git a/samples/client/petstore/swift5/alamofireLibrary/SwaggerClientTests/Podfile.lock b/samples/client/petstore/swift5/alamofireLibrary/SwaggerClientTests/Podfile.lock deleted file mode 100644 index 30f84a6b9c3..00000000000 --- a/samples/client/petstore/swift5/alamofireLibrary/SwaggerClientTests/Podfile.lock +++ /dev/null @@ -1,23 +0,0 @@ -PODS: - - Alamofire (4.9.1) - - PetstoreClient (1.0.0): - - Alamofire (~> 4.9.1) - -DEPENDENCIES: - - PetstoreClient (from `../`) - -SPEC REPOS: - trunk: - - Alamofire - -EXTERNAL SOURCES: - PetstoreClient: - :path: "../" - -SPEC CHECKSUMS: - Alamofire: 85e8a02c69d6020a0d734f6054870d7ecb75cf18 - PetstoreClient: bc687d8c4d0c762098d72690e220cae37e281311 - -PODFILE CHECKSUM: 509bec696cc1d8641751b52e4fe4bef04ac4542c - -COCOAPODS: 1.10.0 diff --git a/samples/client/petstore/swift5/alamofireLibrary/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj b/samples/client/petstore/swift5/alamofireLibrary/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj index 901182fb107..03aed8e5f82 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj +++ b/samples/client/petstore/swift5/alamofireLibrary/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj @@ -3,11 +3,10 @@ archiveVersion = 1; classes = { }; - objectVersion = 46; + objectVersion = 52; objects = { /* Begin PBXBuildFile section */ - 198019EEC6E3CB01FC884C7A /* Pods_SwaggerClientTests.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = D829DFE4E137D91D6174D75A /* Pods_SwaggerClientTests.framework */; }; 1A501F48219C3DC600F372F6 /* DateFormatTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1A501F47219C3DC600F372F6 /* DateFormatTests.swift */; }; 6D4EFB951C692C6300B96B06 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6D4EFB941C692C6300B96B06 /* AppDelegate.swift */; }; 6D4EFB971C692C6300B96B06 /* ViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6D4EFB961C692C6300B96B06 /* ViewController.swift */; }; @@ -18,9 +17,9 @@ 6D4EFBB71C693BED00B96B06 /* StoreAPITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6D4EFBB61C693BED00B96B06 /* StoreAPITests.swift */; }; 6D4EFBB91C693BFC00B96B06 /* UserAPITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6D4EFBB81C693BFC00B96B06 /* UserAPITests.swift */; }; A5465873259E306E00C3929B /* BearerDecodableRequestBuilder.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5465872259E306E00C3929B /* BearerDecodableRequestBuilder.swift */; }; + A5782C6D2664F91D00CAA106 /* PetstoreClient in Frameworks */ = {isa = PBXBuildFile; productRef = A5782C6C2664F91D00CAA106 /* PetstoreClient */; }; A5EA12542419387200E30FC3 /* FileUtils.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5EA12522419387100E30FC3 /* FileUtils.swift */; }; A5EA12552419387200E30FC3 /* UIImage+Extras.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5EA12532419387100E30FC3 /* UIImage+Extras.swift */; }; - B68489033454646C60C16C88 /* Pods_SwaggerClient.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 79549D5237E5E83F567030EC /* Pods_SwaggerClient.framework */; }; /* End PBXBuildFile section */ /* Begin PBXContainerItemProxy section */ @@ -35,7 +34,6 @@ /* Begin PBXFileReference section */ 1A501F47219C3DC600F372F6 /* DateFormatTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DateFormatTests.swift; sourceTree = ""; }; - 32ED0E88E0B89A537075D9C9 /* Pods-SwaggerClient.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-SwaggerClient.debug.xcconfig"; path = "Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient.debug.xcconfig"; sourceTree = ""; }; 6D4EFB911C692C6300B96B06 /* SwaggerClient.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = SwaggerClient.app; sourceTree = BUILT_PRODUCTS_DIR; }; 6D4EFB941C692C6300B96B06 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; 6D4EFB961C692C6300B96B06 /* ViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ViewController.swift; sourceTree = ""; }; @@ -48,15 +46,9 @@ 6D4EFBB41C693BE200B96B06 /* PetAPITests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PetAPITests.swift; sourceTree = ""; }; 6D4EFBB61C693BED00B96B06 /* StoreAPITests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StoreAPITests.swift; sourceTree = ""; }; 6D4EFBB81C693BFC00B96B06 /* UserAPITests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = UserAPITests.swift; sourceTree = ""; }; - 74246FD63841F7C179AD697F /* Pods-SwaggerClientTests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-SwaggerClientTests.debug.xcconfig"; path = "Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests.debug.xcconfig"; sourceTree = ""; }; - 79549D5237E5E83F567030EC /* Pods_SwaggerClient.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_SwaggerClient.framework; sourceTree = BUILT_PRODUCTS_DIR; }; - 8ABA6AE59F792DAA1F79C48F /* Pods-SwaggerClientTests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-SwaggerClientTests.release.xcconfig"; path = "Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests.release.xcconfig"; sourceTree = ""; }; A5465872259E306E00C3929B /* BearerDecodableRequestBuilder.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BearerDecodableRequestBuilder.swift; sourceTree = ""; }; A5EA12522419387100E30FC3 /* FileUtils.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FileUtils.swift; sourceTree = ""; }; A5EA12532419387100E30FC3 /* UIImage+Extras.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "UIImage+Extras.swift"; sourceTree = ""; }; - C07EC0A94AA0F86D60668B32 /* Pods.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods.framework; sourceTree = BUILT_PRODUCTS_DIR; }; - D829DFE4E137D91D6174D75A /* Pods_SwaggerClientTests.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_SwaggerClientTests.framework; sourceTree = BUILT_PRODUCTS_DIR; }; - FB503FF47F354A87D697DD0A /* Pods-SwaggerClient.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-SwaggerClient.release.xcconfig"; path = "Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient.release.xcconfig"; sourceTree = ""; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ @@ -64,7 +56,7 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( - B68489033454646C60C16C88 /* Pods_SwaggerClient.framework in Frameworks */, + A5782C6D2664F91D00CAA106 /* PetstoreClient in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -72,7 +64,6 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( - 198019EEC6E3CB01FC884C7A /* Pods_SwaggerClientTests.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -82,9 +73,6 @@ 3FABC56EC0BA84CBF4F99564 /* Frameworks */ = { isa = PBXGroup; children = ( - C07EC0A94AA0F86D60668B32 /* Pods.framework */, - 79549D5237E5E83F567030EC /* Pods_SwaggerClient.framework */, - D829DFE4E137D91D6174D75A /* Pods_SwaggerClientTests.framework */, ); name = Frameworks; sourceTree = ""; @@ -96,7 +84,6 @@ 6D4EFBA81C692C6300B96B06 /* SwaggerClientTests */, 6D4EFB921C692C6300B96B06 /* Products */, 3FABC56EC0BA84CBF4F99564 /* Frameworks */, - AC485EA5DC51CA28F3F7FECF /* Pods */, ); sourceTree = ""; }; @@ -137,18 +124,6 @@ path = SwaggerClientTests; sourceTree = ""; }; - AC485EA5DC51CA28F3F7FECF /* Pods */ = { - isa = PBXGroup; - children = ( - 32ED0E88E0B89A537075D9C9 /* Pods-SwaggerClient.debug.xcconfig */, - FB503FF47F354A87D697DD0A /* Pods-SwaggerClient.release.xcconfig */, - 74246FD63841F7C179AD697F /* Pods-SwaggerClientTests.debug.xcconfig */, - 8ABA6AE59F792DAA1F79C48F /* Pods-SwaggerClientTests.release.xcconfig */, - ); - name = Pods; - path = Pods; - sourceTree = ""; - }; /* End PBXGroup section */ /* Begin PBXNativeTarget section */ @@ -156,17 +131,18 @@ isa = PBXNativeTarget; buildConfigurationList = 6D4EFBAE1C692C6300B96B06 /* Build configuration list for PBXNativeTarget "SwaggerClient" */; buildPhases = ( - 53EC90CFFB0E0FABA75F972D /* [CP] Check Pods Manifest.lock */, 6D4EFB8D1C692C6300B96B06 /* Sources */, 6D4EFB8E1C692C6300B96B06 /* Frameworks */, 6D4EFB8F1C692C6300B96B06 /* Resources */, - 3E0F8DF721D95AAFC75864D4 /* [CP] Embed Pods Frameworks */, ); buildRules = ( ); dependencies = ( ); name = SwaggerClient; + packageProductDependencies = ( + A5782C6C2664F91D00CAA106 /* PetstoreClient */, + ); productName = SwaggerClient; productReference = 6D4EFB911C692C6300B96B06 /* SwaggerClient.app */; productType = "com.apple.product-type.application"; @@ -175,7 +151,6 @@ isa = PBXNativeTarget; buildConfigurationList = 6D4EFBB11C692C6300B96B06 /* Build configuration list for PBXNativeTarget "SwaggerClientTests" */; buildPhases = ( - 89F684025365A60C007C7DA9 /* [CP] Check Pods Manifest.lock */, 6D4EFBA11C692C6300B96B06 /* Sources */, 6D4EFBA21C692C6300B96B06 /* Frameworks */, 6D4EFBA31C692C6300B96B06 /* Resources */, @@ -250,73 +225,6 @@ }; /* End PBXResourcesBuildPhase section */ -/* Begin PBXShellScriptBuildPhase section */ - 3E0F8DF721D95AAFC75864D4 /* [CP] Embed Pods Frameworks */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputPaths = ( - "${PODS_ROOT}/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-frameworks.sh", - "${BUILT_PRODUCTS_DIR}/Alamofire/Alamofire.framework", - "${BUILT_PRODUCTS_DIR}/PetstoreClient/PetstoreClient.framework", - ); - name = "[CP] Embed Pods Frameworks"; - outputPaths = ( - "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/Alamofire.framework", - "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/PetstoreClient.framework", - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-frameworks.sh\"\n"; - showEnvVarsInLog = 0; - }; - 53EC90CFFB0E0FABA75F972D /* [CP] Check Pods Manifest.lock */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputFileListPaths = ( - ); - inputPaths = ( - "${PODS_PODFILE_DIR_PATH}/Podfile.lock", - "${PODS_ROOT}/Manifest.lock", - ); - name = "[CP] Check Pods Manifest.lock"; - outputFileListPaths = ( - ); - outputPaths = ( - "$(DERIVED_FILE_DIR)/Pods-SwaggerClient-checkManifestLockResult.txt", - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; - showEnvVarsInLog = 0; - }; - 89F684025365A60C007C7DA9 /* [CP] Check Pods Manifest.lock */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputFileListPaths = ( - ); - inputPaths = ( - "${PODS_PODFILE_DIR_PATH}/Podfile.lock", - "${PODS_ROOT}/Manifest.lock", - ); - name = "[CP] Check Pods Manifest.lock"; - outputFileListPaths = ( - ); - outputPaths = ( - "$(DERIVED_FILE_DIR)/Pods-SwaggerClientTests-checkManifestLockResult.txt", - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; - showEnvVarsInLog = 0; - }; -/* End PBXShellScriptBuildPhase section */ - /* Begin PBXSourcesBuildPhase section */ 6D4EFB8D1C692C6300B96B06 /* Sources */ = { isa = PBXSourcesBuildPhase; @@ -481,11 +389,13 @@ }; 6D4EFBAF1C692C6300B96B06 /* Debug */ = { isa = XCBuildConfiguration; - baseConfigurationReference = 32ED0E88E0B89A537075D9C9 /* Pods-SwaggerClient.debug.xcconfig */; buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; INFOPLIST_FILE = SwaggerClient/Info.plist; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); PRODUCT_BUNDLE_IDENTIFIER = com.swagger.SwaggerClient; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_VERSION = 5.0; @@ -494,11 +404,13 @@ }; 6D4EFBB01C692C6300B96B06 /* Release */ = { isa = XCBuildConfiguration; - baseConfigurationReference = FB503FF47F354A87D697DD0A /* Pods-SwaggerClient.release.xcconfig */; buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; INFOPLIST_FILE = SwaggerClient/Info.plist; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); PRODUCT_BUNDLE_IDENTIFIER = com.swagger.SwaggerClient; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_VERSION = 5.0; @@ -507,11 +419,14 @@ }; 6D4EFBB21C692C6300B96B06 /* Debug */ = { isa = XCBuildConfiguration; - baseConfigurationReference = 74246FD63841F7C179AD697F /* Pods-SwaggerClientTests.debug.xcconfig */; buildSettings = { BUNDLE_LOADER = "$(TEST_HOST)"; INFOPLIST_FILE = SwaggerClientTests/Info.plist; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); PRODUCT_BUNDLE_IDENTIFIER = com.swagger.SwaggerClientTests; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_VERSION = 5.0; @@ -521,11 +436,14 @@ }; 6D4EFBB31C692C6300B96B06 /* Release */ = { isa = XCBuildConfiguration; - baseConfigurationReference = 8ABA6AE59F792DAA1F79C48F /* Pods-SwaggerClientTests.release.xcconfig */; buildSettings = { BUNDLE_LOADER = "$(TEST_HOST)"; INFOPLIST_FILE = SwaggerClientTests/Info.plist; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); PRODUCT_BUNDLE_IDENTIFIER = com.swagger.SwaggerClientTests; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_VERSION = 5.0; @@ -564,6 +482,13 @@ defaultConfigurationName = Release; }; /* End XCConfigurationList section */ + +/* Begin XCSwiftPackageProductDependency section */ + A5782C6C2664F91D00CAA106 /* PetstoreClient */ = { + isa = XCSwiftPackageProductDependency; + productName = PetstoreClient; + }; +/* End XCSwiftPackageProductDependency section */ }; rootObject = 6D4EFB891C692C6300B96B06 /* Project object */; } diff --git a/samples/client/petstore/swift5/alamofireLibrary/SwaggerClientTests/SwaggerClient.xcworkspace/contents.xcworkspacedata b/samples/client/petstore/swift5/alamofireLibrary/SwaggerClientTests/SwaggerClient.xcworkspace/contents.xcworkspacedata index 9b3fa18954f..00ec9b53a7f 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/SwaggerClientTests/SwaggerClient.xcworkspace/contents.xcworkspacedata +++ b/samples/client/petstore/swift5/alamofireLibrary/SwaggerClientTests/SwaggerClient.xcworkspace/contents.xcworkspacedata @@ -2,9 +2,9 @@ + location = "group:.."> + location = "group:SwaggerClient.xcodeproj"> diff --git a/samples/client/petstore/swift5/alamofireLibrary/SwaggerClientTests/SwaggerClient.xcworkspace/xcshareddata/swiftpm/Package.resolved b/samples/client/petstore/swift5/alamofireLibrary/SwaggerClientTests/SwaggerClient.xcworkspace/xcshareddata/swiftpm/Package.resolved new file mode 100644 index 00000000000..4c8626cac13 --- /dev/null +++ b/samples/client/petstore/swift5/alamofireLibrary/SwaggerClientTests/SwaggerClient.xcworkspace/xcshareddata/swiftpm/Package.resolved @@ -0,0 +1,25 @@ +{ + "object": { + "pins": [ + { + "package": "Alamofire", + "repositoryURL": "https://github.com/Alamofire/Alamofire.git", + "state": { + "branch": null, + "revision": "747c8db8d57b68d5e35275f10c92d55f982adbd4", + "version": "4.9.1" + } + }, + { + "package": "AnyCodable", + "repositoryURL": "https://github.com/Flight-School/AnyCodable", + "state": { + "branch": null, + "revision": "876d162385e9862ae8b3c8d65dc301312b040005", + "version": "0.6.0" + } + } + ] + }, + "version": 1 +} diff --git a/samples/client/petstore/swift5/alamofireLibrary/docs/FakeAPI.md b/samples/client/petstore/swift5/alamofireLibrary/docs/FakeAPI.md index 543869c0d2e..553a46281aa 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/docs/FakeAPI.md +++ b/samples/client/petstore/swift5/alamofireLibrary/docs/FakeAPI.md @@ -379,7 +379,7 @@ import PetstoreClient let number = 987 // Double | None let double = 987 // Double | None let patternWithoutDelimiter = "patternWithoutDelimiter_example" // String | None -let byte = 987 // Data | None +let byte = Data([9, 8, 7]) // Data | None let integer = 987 // Int | None (optional) let int32 = 987 // Int | None (optional) let int64 = 987 // Int64 | None (optional) diff --git a/samples/client/petstore/swift5/alamofireLibrary/project.yml b/samples/client/petstore/swift5/alamofireLibrary/project.yml index 148e2487eae..29a682f4478 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/project.yml +++ b/samples/client/petstore/swift5/alamofireLibrary/project.yml @@ -12,5 +12,5 @@ targets: APPLICATION_EXTENSION_API_ONLY: true scheme: {} dependencies: - - carthage: Alamofire - carthage: AnyCodable + - carthage: Alamofire diff --git a/samples/client/petstore/swift5/combineLibrary/.gitignore b/samples/client/petstore/swift5/combineLibrary/.gitignore index 5e5d5cebcf4..627d360a903 100644 --- a/samples/client/petstore/swift5/combineLibrary/.gitignore +++ b/samples/client/petstore/swift5/combineLibrary/.gitignore @@ -1,12 +1,22 @@ +# Created by https://www.toptal.com/developers/gitignore/api/swift,xcode +# Edit at https://www.toptal.com/developers/gitignore?templates=swift,xcode + +### Swift ### # Xcode # # gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore -## Build generated -build/ -DerivedData +## User settings +xcuserdata/ -## Various settings +## compatibility with Xcode 8 and earlier (ignoring not required starting Xcode 9) +*.xcscmblueprint +*.xccheckout + +## compatibility with Xcode 3 and earlier (ignoring not required starting Xcode 4) +build/ +DerivedData/ +*.moved-aside *.pbxuser !default.pbxuser *.mode1v3 @@ -15,49 +25,81 @@ DerivedData !default.mode2v3 *.perspectivev3 !default.perspectivev3 -xcuserdata - -## Other -*.xccheckout -*.moved-aside -*.xcuserstate -*.xcscmblueprint ## Obj-C/Swift specific *.hmap + +## App packaging *.ipa +*.dSYM.zip +*.dSYM ## Playgrounds timeline.xctimeline playground.xcworkspace # Swift Package Manager -# # Add this line if you want to avoid checking in source code from Swift Package Manager dependencies. # Packages/ +# Package.pins +# Package.resolved +# *.xcodeproj +# Xcode automatically generates this directory with a .xcworkspacedata file and xcuserdata +# hence it is not needed unless you have added a package configuration file to your project +# .swiftpm + .build/ # CocoaPods -# # We recommend against adding the Pods directory to your .gitignore. However # you should judge for yourself, the pros and cons are mentioned at: # https://guides.cocoapods.org/using/using-cocoapods.html#should-i-check-the-pods-directory-into-source-control -# # Pods/ +# Add this line if you want to avoid checking in source code from the Xcode workspace +# *.xcworkspace # Carthage -# # Add this line if you want to avoid checking in source code from Carthage dependencies. # Carthage/Checkouts -Carthage/Build +Carthage/Build/ + +# Add this lines if you are using Accio dependency management (Deprecated since Xcode 12) +# Dependencies/ +# .accio/ # fastlane -# -# It is recommended to not store the screenshots in the git repo. Instead, use fastlane to re-generate the -# screenshots whenever they are needed. +# It is recommended to not store the screenshots in the git repo. +# Instead, use fastlane to re-generate the screenshots whenever they are needed. # For more information about the recommended setup visit: -# https://github.com/fastlane/fastlane/blob/master/docs/Gitignore.md +# https://docs.fastlane.tools/best-practices/source-control/#source-control fastlane/report.xml -fastlane/screenshots +fastlane/Preview.html +fastlane/screenshots/**/*.png +fastlane/test_output + +# Code Injection +# After new code Injection tools there's a generated folder /iOSInjectionProject +# https://github.com/johnno1962/injectionforxcode + +iOSInjectionProject/ + +### Xcode ### +# Xcode +# gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore + + + + +## Gcc Patch +/*.gcno + +### Xcode Patch ### +*.xcodeproj/* +!*.xcodeproj/project.pbxproj +!*.xcodeproj/xcshareddata/ +!*.xcworkspace/contents.xcworkspacedata +**/xcshareddata/WorkspaceSettings.xcsettings + +# End of https://www.toptal.com/developers/gitignore/api/swift,xcode diff --git a/samples/client/petstore/swift5/combineLibrary/.openapi-generator/VERSION b/samples/client/petstore/swift5/combineLibrary/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/client/petstore/swift5/combineLibrary/.openapi-generator/VERSION +++ b/samples/client/petstore/swift5/combineLibrary/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/client/petstore/swift5/combineLibrary/Cartfile b/samples/client/petstore/swift5/combineLibrary/Cartfile index 84aaa61ef2d..a6a6bcacb1d 100644 --- a/samples/client/petstore/swift5/combineLibrary/Cartfile +++ b/samples/client/petstore/swift5/combineLibrary/Cartfile @@ -1,2 +1,2 @@ -github "Flight-School/AnyCodable" ~> 0.4.0 +github "Flight-School/AnyCodable" ~> 0.6.1 diff --git a/samples/client/petstore/swift5/combineLibrary/Package.resolved b/samples/client/petstore/swift5/combineLibrary/Package.resolved new file mode 100644 index 00000000000..79610c3b3b3 --- /dev/null +++ b/samples/client/petstore/swift5/combineLibrary/Package.resolved @@ -0,0 +1,16 @@ +{ + "object": { + "pins": [ + { + "package": "AnyCodable", + "repositoryURL": "https://github.com/Flight-School/AnyCodable", + "state": { + "branch": null, + "revision": "69261f239f0fffaf51495dadc4f8483fbfe97025", + "version": "0.6.1" + } + } + ] + }, + "version": 1 +} diff --git a/samples/client/petstore/swift5/combineLibrary/Package.swift b/samples/client/petstore/swift5/combineLibrary/Package.swift index b724838fe8d..87bb775fb72 100644 --- a/samples/client/petstore/swift5/combineLibrary/Package.swift +++ b/samples/client/petstore/swift5/combineLibrary/Package.swift @@ -19,7 +19,7 @@ let package = Package( ], dependencies: [ // Dependencies declare other packages that this package depends on. - .package(url: "https://github.com/Flight-School/AnyCodable", .exact("0.4.0")), + .package(url: "https://github.com/Flight-School/AnyCodable", from: "0.6.1"), ], targets: [ // Targets are the basic building blocks of a package. A target can define a module or a test suite. diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient.podspec b/samples/client/petstore/swift5/combineLibrary/PetstoreClient.podspec index de06558efbd..0e6bf7ec024 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient.podspec +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient.podspec @@ -11,5 +11,5 @@ Pod::Spec.new do |s| s.homepage = 'https://github.com/openapitools/openapi-generator' s.summary = 'PetstoreClient' s.source_files = 'PetstoreClient/Classes/**/*.swift' - s.dependency 'AnyCodable-FlightSchool', '~> 0.4.0' + s.dependency 'AnyCodable-FlightSchool', '~> 0.6.1' end diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs.swift b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs.swift index dbdab491ff7..941c61b713a 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs.swift @@ -6,10 +6,13 @@ import Foundation -open class PetstoreClientAPI { +@available(*, deprecated, renamed: "PetstoreClient") +public typealias PetstoreClientAPI = PetstoreClient + +open class PetstoreClient { public static var basePath = "http://petstore.swagger.io:80/v2" - public static var credential: URLCredential? public static var customHeaders: [String: String] = [:] + public static var credential: URLCredential? public static var requestBuilderFactory: RequestBuilderFactory = URLSessionRequestBuilderFactory() public static var apiResponseQueue: DispatchQueue = .main } @@ -32,7 +35,7 @@ open class RequestBuilder { self.parameters = parameters self.headers = headers - addHeaders(PetstoreClientAPI.customHeaders) + addHeaders(PetstoreClient.customHeaders) } open func addHeaders(_ aHeaders: [String: String]) { @@ -41,7 +44,7 @@ open class RequestBuilder { } } - open func execute(_ apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, _ completion: @escaping (_ result: Swift.Result, Error>) -> Void) { } + open func execute(_ apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, _ completion: @escaping (_ result: Swift.Result, Error>) -> Void) { } public func addHeader(name: String, value: String) -> Self { if !value.isEmpty { @@ -51,7 +54,7 @@ open class RequestBuilder { } open func addCredential() -> Self { - credential = PetstoreClientAPI.credential + credential = PetstoreClient.credential return self } } 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 9db7ad8a0d3..ebe06db329f 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 @@ -9,8 +9,12 @@ import Foundation #if canImport(Combine) import Combine #endif +#if canImport(AnyCodable) +import AnyCodable +#endif open class AnotherFakeAPI { + /** To test special tags @@ -20,7 +24,7 @@ open class AnotherFakeAPI { */ #if canImport(Combine) @available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) - open class func call123testSpecialTags(body: Client, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> AnyPublisher { + open class func call123testSpecialTags(body: Client, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> AnyPublisher { return Future.init { promise in call123testSpecialTagsWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { @@ -42,21 +46,20 @@ open class AnotherFakeAPI { - returns: RequestBuilder */ open class func call123testSpecialTagsWithRequestBuilder(body: Client) -> RequestBuilder { - let path = "/another-fake/dummy" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/another-fake/dummy" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "PATCH", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "PATCH", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } - } 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 20e0b55d9e8..f2292f67ada 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 @@ -9,8 +9,12 @@ import Foundation #if canImport(Combine) import Combine #endif +#if canImport(AnyCodable) +import AnyCodable +#endif open class FakeAPI { + /** - parameter body: (body) Input boolean as post body (optional) @@ -19,7 +23,7 @@ open class FakeAPI { */ #if canImport(Combine) @available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) - open class func fakeOuterBooleanSerialize(body: Bool? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> AnyPublisher { + open class func fakeOuterBooleanSerialize(body: Bool? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> AnyPublisher { return Future.init { promise in fakeOuterBooleanSerializeWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { @@ -40,21 +44,21 @@ open class FakeAPI { - returns: RequestBuilder */ open class func fakeOuterBooleanSerializeWithRequestBuilder(body: Bool? = nil) -> RequestBuilder { - let path = "/fake/outer/boolean" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/fake/outer/boolean" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -65,7 +69,7 @@ open class FakeAPI { */ #if canImport(Combine) @available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) - open class func fakeOuterCompositeSerialize(body: OuterComposite? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> AnyPublisher { + open class func fakeOuterCompositeSerialize(body: OuterComposite? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> AnyPublisher { return Future.init { promise in fakeOuterCompositeSerializeWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { @@ -86,21 +90,21 @@ open class FakeAPI { - returns: RequestBuilder */ open class func fakeOuterCompositeSerializeWithRequestBuilder(body: OuterComposite? = nil) -> RequestBuilder { - let path = "/fake/outer/composite" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/fake/outer/composite" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -111,7 +115,7 @@ open class FakeAPI { */ #if canImport(Combine) @available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) - open class func fakeOuterNumberSerialize(body: Double? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> AnyPublisher { + open class func fakeOuterNumberSerialize(body: Double? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> AnyPublisher { return Future.init { promise in fakeOuterNumberSerializeWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { @@ -132,21 +136,21 @@ open class FakeAPI { - returns: RequestBuilder */ open class func fakeOuterNumberSerializeWithRequestBuilder(body: Double? = nil) -> RequestBuilder { - let path = "/fake/outer/number" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/fake/outer/number" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -157,7 +161,7 @@ open class FakeAPI { */ #if canImport(Combine) @available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) - open class func fakeOuterStringSerialize(body: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> AnyPublisher { + open class func fakeOuterStringSerialize(body: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> AnyPublisher { return Future.init { promise in fakeOuterStringSerializeWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { @@ -178,21 +182,21 @@ open class FakeAPI { - returns: RequestBuilder */ open class func fakeOuterStringSerializeWithRequestBuilder(body: String? = nil) -> RequestBuilder { - let path = "/fake/outer/string" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/fake/outer/string" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -203,7 +207,7 @@ open class FakeAPI { */ #if canImport(Combine) @available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) - open class func testBodyWithFileSchema(body: FileSchemaTestClass, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> AnyPublisher { + open class func testBodyWithFileSchema(body: FileSchemaTestClass, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> AnyPublisher { return Future.init { promise in testBodyWithFileSchemaWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { @@ -224,21 +228,21 @@ open class FakeAPI { - returns: RequestBuilder */ open class func testBodyWithFileSchemaWithRequestBuilder(body: FileSchemaTestClass) -> RequestBuilder { - let path = "/fake/body-with-file-schema" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/fake/body-with-file-schema" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "PUT", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -250,7 +254,7 @@ open class FakeAPI { */ #if canImport(Combine) @available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) - open class func testBodyWithQueryParams(query: String, body: User, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> AnyPublisher { + open class func testBodyWithQueryParams(query: String, body: User, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> AnyPublisher { return Future.init { promise in testBodyWithQueryParamsWithRequestBuilder(query: query, body: body).execute(apiResponseQueue) { result -> Void in switch result { @@ -271,24 +275,24 @@ open class FakeAPI { - returns: RequestBuilder */ open class func testBodyWithQueryParamsWithRequestBuilder(query: String, body: User) -> RequestBuilder { - let path = "/fake/body-with-query-params" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/fake/body-with-query-params" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - var urlComponents = URLComponents(string: URLString) - urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ + var localVariableUrlComponents = URLComponents(string: localVariableURLString) + localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ "query": query.encodeToJSON(), ]) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "PUT", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -300,7 +304,7 @@ open class FakeAPI { */ #if canImport(Combine) @available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) - open class func testClientModel(body: Client, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> AnyPublisher { + open class func testClientModel(body: Client, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> AnyPublisher { return Future.init { promise in testClientModelWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { @@ -322,21 +326,21 @@ open class FakeAPI { - returns: RequestBuilder */ open class func testClientModelWithRequestBuilder(body: Client) -> RequestBuilder { - let path = "/fake" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/fake" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "PATCH", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "PATCH", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -361,7 +365,7 @@ open class FakeAPI { */ #if canImport(Combine) @available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) - open class func testEndpointParameters(number: Double, double: Double, patternWithoutDelimiter: String, byte: Data, integer: Int? = nil, int32: Int? = nil, int64: Int64? = nil, float: Float? = nil, string: String? = nil, binary: URL? = nil, date: Date? = nil, dateTime: Date? = nil, password: String? = nil, callback: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> AnyPublisher { + open class func testEndpointParameters(number: Double, double: Double, patternWithoutDelimiter: String, byte: Data, integer: Int? = nil, int32: Int? = nil, int64: Int64? = nil, float: Float? = nil, string: String? = nil, binary: URL? = nil, date: Date? = nil, dateTime: Date? = nil, password: String? = nil, callback: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> AnyPublisher { return Future.init { promise in testEndpointParametersWithRequestBuilder(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(apiResponseQueue) { result -> Void in switch result { @@ -399,9 +403,9 @@ open class FakeAPI { - returns: RequestBuilder */ open class func testEndpointParametersWithRequestBuilder(number: Double, double: Double, patternWithoutDelimiter: String, byte: Data, integer: Int? = nil, int32: Int? = nil, int64: Int64? = nil, float: Float? = nil, string: String? = nil, binary: URL? = nil, date: Date? = nil, dateTime: Date? = nil, password: String? = nil, callback: String? = nil) -> RequestBuilder { - let path = "/fake" - let URLString = PetstoreClientAPI.basePath + path - let formParams: [String: Any?] = [ + let localVariablePath = "/fake" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableFormParams: [String: Any?] = [ "integer": integer?.encodeToJSON(), "int32": int32?.encodeToJSON(), "int64": int64?.encodeToJSON(), @@ -418,20 +422,20 @@ open class FakeAPI { "callback": callback?.encodeToJSON(), ] - let nonNullParameters = APIHelper.rejectNil(formParams) - let parameters = APIHelper.convertBoolToString(nonNullParameters) + let localVariableNonNullParameters = APIHelper.rejectNil(localVariableFormParams) + let localVariableParameters = APIHelper.convertBoolToString(localVariableNonNullParameters) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ "Content-Type": "application/x-www-form-urlencoded", ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -517,7 +521,7 @@ open class FakeAPI { */ #if canImport(Combine) @available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) - open class func testEnumParameters(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> AnyPublisher { + open class func testEnumParameters(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> AnyPublisher { return Future.init { promise in testEnumParametersWithRequestBuilder(enumHeaderStringArray: enumHeaderStringArray, enumHeaderString: enumHeaderString, enumQueryStringArray: enumQueryStringArray, enumQueryString: enumQueryString, enumQueryInteger: enumQueryInteger, enumQueryDouble: enumQueryDouble, enumFormStringArray: enumFormStringArray, enumFormString: enumFormString).execute(apiResponseQueue) { result -> Void in switch result { @@ -546,35 +550,35 @@ open class FakeAPI { - returns: RequestBuilder */ open class func testEnumParametersWithRequestBuilder(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil) -> RequestBuilder { - let path = "/fake" - let URLString = PetstoreClientAPI.basePath + path - let formParams: [String: Any?] = [ + let localVariablePath = "/fake" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableFormParams: [String: Any?] = [ "enum_form_string_array": enumFormStringArray?.encodeToJSON(), "enum_form_string": enumFormString?.encodeToJSON(), ] - let nonNullParameters = APIHelper.rejectNil(formParams) - let parameters = APIHelper.convertBoolToString(nonNullParameters) + let localVariableNonNullParameters = APIHelper.rejectNil(localVariableFormParams) + let localVariableParameters = APIHelper.convertBoolToString(localVariableNonNullParameters) - var urlComponents = URLComponents(string: URLString) - urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ + var localVariableUrlComponents = URLComponents(string: localVariableURLString) + localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ "enum_query_string_array": enumQueryStringArray?.encodeToJSON(), "enum_query_string": enumQueryString?.encodeToJSON(), "enum_query_integer": enumQueryInteger?.encodeToJSON(), "enum_query_double": enumQueryDouble?.encodeToJSON(), ]) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ "Content-Type": "application/x-www-form-urlencoded", "enum_header_string_array": enumHeaderStringArray?.encodeToJSON(), "enum_header_string": enumHeaderString?.encodeToJSON(), ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -591,7 +595,7 @@ open class FakeAPI { */ #if canImport(Combine) @available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) - open class func testGroupParameters(requiredStringGroup: Int, requiredBooleanGroup: Bool, requiredInt64Group: Int64, stringGroup: Int? = nil, booleanGroup: Bool? = nil, int64Group: Int64? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> AnyPublisher { + open class func testGroupParameters(requiredStringGroup: Int, requiredBooleanGroup: Bool, requiredInt64Group: Int64, stringGroup: Int? = nil, booleanGroup: Bool? = nil, int64Group: Int64? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> AnyPublisher { return Future.init { promise in testGroupParametersWithRequestBuilder(requiredStringGroup: requiredStringGroup, requiredBooleanGroup: requiredBooleanGroup, requiredInt64Group: requiredInt64Group, stringGroup: stringGroup, booleanGroup: booleanGroup, int64Group: int64Group).execute(apiResponseQueue) { result -> Void in switch result { @@ -618,28 +622,28 @@ open class FakeAPI { - returns: RequestBuilder */ open class func testGroupParametersWithRequestBuilder(requiredStringGroup: Int, requiredBooleanGroup: Bool, requiredInt64Group: Int64, stringGroup: Int? = nil, booleanGroup: Bool? = nil, int64Group: Int64? = nil) -> RequestBuilder { - let path = "/fake" - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + let localVariablePath = "/fake" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - var urlComponents = URLComponents(string: URLString) - urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ + var localVariableUrlComponents = URLComponents(string: localVariableURLString) + localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ "required_string_group": requiredStringGroup.encodeToJSON(), "required_int64_group": requiredInt64Group.encodeToJSON(), "string_group": stringGroup?.encodeToJSON(), "int64_group": int64Group?.encodeToJSON(), ]) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ "required_boolean_group": requiredBooleanGroup.encodeToJSON(), "boolean_group": booleanGroup?.encodeToJSON(), ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "DELETE", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -651,7 +655,7 @@ open class FakeAPI { */ #if canImport(Combine) @available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) - open class func testInlineAdditionalProperties(param: [String: String], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> AnyPublisher { + open class func testInlineAdditionalProperties(param: [String: String], apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> AnyPublisher { return Future.init { promise in testInlineAdditionalPropertiesWithRequestBuilder(param: param).execute(apiResponseQueue) { result -> Void in switch result { @@ -672,21 +676,21 @@ open class FakeAPI { - returns: RequestBuilder */ open class func testInlineAdditionalPropertiesWithRequestBuilder(param: [String: String]) -> RequestBuilder { - let path = "/fake/inline-additionalProperties" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: param) + let localVariablePath = "/fake/inline-additionalProperties" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: param) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -699,7 +703,7 @@ open class FakeAPI { */ #if canImport(Combine) @available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) - open class func testJsonFormData(param: String, param2: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> AnyPublisher { + open class func testJsonFormData(param: String, param2: String, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> AnyPublisher { return Future.init { promise in testJsonFormDataWithRequestBuilder(param: param, param2: param2).execute(apiResponseQueue) { result -> Void in switch result { @@ -721,27 +725,26 @@ open class FakeAPI { - returns: RequestBuilder */ open class func testJsonFormDataWithRequestBuilder(param: String, param2: String) -> RequestBuilder { - let path = "/fake/jsonFormData" - let URLString = PetstoreClientAPI.basePath + path - let formParams: [String: Any?] = [ + let localVariablePath = "/fake/jsonFormData" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableFormParams: [String: Any?] = [ "param": param.encodeToJSON(), "param2": param2.encodeToJSON(), ] - let nonNullParameters = APIHelper.rejectNil(formParams) - let parameters = APIHelper.convertBoolToString(nonNullParameters) + let localVariableNonNullParameters = APIHelper.rejectNil(localVariableFormParams) + let localVariableParameters = APIHelper.convertBoolToString(localVariableNonNullParameters) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ "Content-Type": "application/x-www-form-urlencoded", ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } - } 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 85eab81386f..3edea3454e6 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 @@ -9,8 +9,12 @@ import Foundation #if canImport(Combine) import Combine #endif +#if canImport(AnyCodable) +import AnyCodable +#endif open class FakeClassnameTags123API { + /** To test class name in snake case @@ -20,7 +24,7 @@ open class FakeClassnameTags123API { */ #if canImport(Combine) @available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) - open class func testClassname(body: Client, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> AnyPublisher { + open class func testClassname(body: Client, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> AnyPublisher { return Future.init { promise in testClassnameWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { @@ -45,21 +49,20 @@ open class FakeClassnameTags123API { - returns: RequestBuilder */ open class func testClassnameWithRequestBuilder(body: Client) -> RequestBuilder { - let path = "/fake_classname_test" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/fake_classname_test" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "PATCH", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "PATCH", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } - } 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 10ce86076cf..269e48d35d8 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 @@ -9,8 +9,12 @@ import Foundation #if canImport(Combine) import Combine #endif +#if canImport(AnyCodable) +import AnyCodable +#endif open class PetAPI { + /** Add a new pet to the store @@ -20,7 +24,7 @@ open class PetAPI { */ #if canImport(Combine) @available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) - open class func addPet(body: Pet, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> AnyPublisher { + open class func addPet(body: Pet, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> AnyPublisher { return Future.init { promise in addPetWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { @@ -44,21 +48,21 @@ open class PetAPI { - returns: RequestBuilder */ open class func addPetWithRequestBuilder(body: Pet) -> RequestBuilder { - let path = "/pet" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/pet" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -71,7 +75,7 @@ open class PetAPI { */ #if canImport(Combine) @available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) - open class func deletePet(petId: Int64, apiKey: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> AnyPublisher { + open class func deletePet(petId: Int64, apiKey: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> AnyPublisher { return Future.init { promise in deletePetWithRequestBuilder(petId: petId, apiKey: apiKey).execute(apiResponseQueue) { result -> Void in switch result { @@ -96,24 +100,24 @@ open class PetAPI { - returns: RequestBuilder */ open class func deletePetWithRequestBuilder(petId: Int64, apiKey: String? = nil) -> RequestBuilder { - var path = "/pet/{petId}" + var localVariablePath = "/pet/{petId}" let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))" let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" - path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + localVariablePath = localVariablePath.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ "api_key": apiKey?.encodeToJSON(), ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "DELETE", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -134,7 +138,7 @@ open class PetAPI { */ #if canImport(Combine) @available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) - open class func findPetsByStatus(status: [String], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> AnyPublisher<[Pet], Error> { + open class func findPetsByStatus(status: [String], apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> AnyPublisher<[Pet], Error> { return Future<[Pet], Error>.init { promise in findPetsByStatusWithRequestBuilder(status: status).execute(apiResponseQueue) { result -> Void in switch result { @@ -159,24 +163,24 @@ open class PetAPI { - returns: RequestBuilder<[Pet]> */ open class func findPetsByStatusWithRequestBuilder(status: [String]) -> RequestBuilder<[Pet]> { - let path = "/pet/findByStatus" - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + let localVariablePath = "/pet/findByStatus" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - var urlComponents = URLComponents(string: URLString) - urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ + var localVariableUrlComponents = URLComponents(string: localVariableURLString) + localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ "status": status.encodeToJSON(), ]) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -189,7 +193,7 @@ open class PetAPI { #if canImport(Combine) @available(*, deprecated, message: "This operation is deprecated.") @available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) - open class func findPetsByTags(tags: [String], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> AnyPublisher<[Pet], Error> { + open class func findPetsByTags(tags: [String], apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> AnyPublisher<[Pet], Error> { return Future<[Pet], Error>.init { promise in findPetsByTagsWithRequestBuilder(tags: tags).execute(apiResponseQueue) { result -> Void in switch result { @@ -215,24 +219,24 @@ open class PetAPI { */ @available(*, deprecated, message: "This operation is deprecated.") open class func findPetsByTagsWithRequestBuilder(tags: [String]) -> RequestBuilder<[Pet]> { - let path = "/pet/findByTags" - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + let localVariablePath = "/pet/findByTags" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - var urlComponents = URLComponents(string: URLString) - urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ + var localVariableUrlComponents = URLComponents(string: localVariableURLString) + localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ "tags": tags.encodeToJSON(), ]) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -244,7 +248,7 @@ open class PetAPI { */ #if canImport(Combine) @available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) - open class func getPetById(petId: Int64, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> AnyPublisher { + open class func getPetById(petId: Int64, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> AnyPublisher { return Future.init { promise in getPetByIdWithRequestBuilder(petId: petId).execute(apiResponseQueue) { result -> Void in switch result { @@ -269,24 +273,24 @@ open class PetAPI { - returns: RequestBuilder */ open class func getPetByIdWithRequestBuilder(petId: Int64) -> RequestBuilder { - var path = "/pet/{petId}" + var localVariablePath = "/pet/{petId}" let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))" let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" - path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + localVariablePath = localVariablePath.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -298,7 +302,7 @@ open class PetAPI { */ #if canImport(Combine) @available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) - open class func updatePet(body: Pet, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> AnyPublisher { + open class func updatePet(body: Pet, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> AnyPublisher { return Future.init { promise in updatePetWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { @@ -322,21 +326,21 @@ open class PetAPI { - returns: RequestBuilder */ open class func updatePetWithRequestBuilder(body: Pet) -> RequestBuilder { - let path = "/pet" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/pet" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "PUT", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -350,7 +354,7 @@ open class PetAPI { */ #if canImport(Combine) @available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) - open class func updatePetWithForm(petId: Int64, name: String? = nil, status: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> AnyPublisher { + open class func updatePetWithForm(petId: Int64, name: String? = nil, status: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> AnyPublisher { return Future.init { promise in updatePetWithFormWithRequestBuilder(petId: petId, name: name, status: status).execute(apiResponseQueue) { result -> Void in switch result { @@ -376,30 +380,30 @@ open class PetAPI { - returns: RequestBuilder */ open class func updatePetWithFormWithRequestBuilder(petId: Int64, name: String? = nil, status: String? = nil) -> RequestBuilder { - var path = "/pet/{petId}" + var localVariablePath = "/pet/{petId}" let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))" let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" - path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path - let formParams: [String: Any?] = [ + localVariablePath = localVariablePath.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableFormParams: [String: Any?] = [ "name": name?.encodeToJSON(), "status": status?.encodeToJSON(), ] - let nonNullParameters = APIHelper.rejectNil(formParams) - let parameters = APIHelper.convertBoolToString(nonNullParameters) + let localVariableNonNullParameters = APIHelper.rejectNil(localVariableFormParams) + let localVariableParameters = APIHelper.convertBoolToString(localVariableNonNullParameters) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ "Content-Type": "application/x-www-form-urlencoded", ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -413,7 +417,7 @@ open class PetAPI { */ #if canImport(Combine) @available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) - open class func uploadFile(petId: Int64, additionalMetadata: String? = nil, file: URL? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> AnyPublisher { + open class func uploadFile(petId: Int64, additionalMetadata: String? = nil, file: URL? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> AnyPublisher { return Future.init { promise in uploadFileWithRequestBuilder(petId: petId, additionalMetadata: additionalMetadata, file: file).execute(apiResponseQueue) { result -> Void in switch result { @@ -439,30 +443,30 @@ open class PetAPI { - returns: RequestBuilder */ open class func uploadFileWithRequestBuilder(petId: Int64, additionalMetadata: String? = nil, file: URL? = nil) -> RequestBuilder { - var path = "/pet/{petId}/uploadImage" + var localVariablePath = "/pet/{petId}/uploadImage" let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))" let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" - path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path - let formParams: [String: Any?] = [ + localVariablePath = localVariablePath.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableFormParams: [String: Any?] = [ "additionalMetadata": additionalMetadata?.encodeToJSON(), "file": file?.encodeToJSON(), ] - let nonNullParameters = APIHelper.rejectNil(formParams) - let parameters = APIHelper.convertBoolToString(nonNullParameters) + let localVariableNonNullParameters = APIHelper.rejectNil(localVariableFormParams) + let localVariableParameters = APIHelper.convertBoolToString(localVariableNonNullParameters) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ "Content-Type": "multipart/form-data", ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -476,7 +480,7 @@ open class PetAPI { */ #if canImport(Combine) @available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) - open class func uploadFileWithRequiredFile(petId: Int64, requiredFile: URL, additionalMetadata: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> AnyPublisher { + open class func uploadFileWithRequiredFile(petId: Int64, requiredFile: URL, additionalMetadata: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> AnyPublisher { return Future.init { promise in uploadFileWithRequiredFileWithRequestBuilder(petId: petId, requiredFile: requiredFile, additionalMetadata: additionalMetadata).execute(apiResponseQueue) { result -> Void in switch result { @@ -502,30 +506,29 @@ open class PetAPI { - returns: RequestBuilder */ open class func uploadFileWithRequiredFileWithRequestBuilder(petId: Int64, requiredFile: URL, additionalMetadata: String? = nil) -> RequestBuilder { - var path = "/fake/{petId}/uploadImageWithRequiredFile" + var localVariablePath = "/fake/{petId}/uploadImageWithRequiredFile" let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))" let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" - path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path - let formParams: [String: Any?] = [ + localVariablePath = localVariablePath.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableFormParams: [String: Any?] = [ "additionalMetadata": additionalMetadata?.encodeToJSON(), "requiredFile": requiredFile.encodeToJSON(), ] - let nonNullParameters = APIHelper.rejectNil(formParams) - let parameters = APIHelper.convertBoolToString(nonNullParameters) + let localVariableNonNullParameters = APIHelper.rejectNil(localVariableFormParams) + let localVariableParameters = APIHelper.convertBoolToString(localVariableNonNullParameters) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ "Content-Type": "multipart/form-data", ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } - } diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift index 12a0d5688d5..9cd38825ece 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift @@ -9,8 +9,12 @@ import Foundation #if canImport(Combine) import Combine #endif +#if canImport(AnyCodable) +import AnyCodable +#endif open class StoreAPI { + /** Delete purchase order by ID @@ -20,7 +24,7 @@ open class StoreAPI { */ #if canImport(Combine) @available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) - open class func deleteOrder(orderId: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> AnyPublisher { + open class func deleteOrder(orderId: String, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> AnyPublisher { return Future.init { promise in deleteOrderWithRequestBuilder(orderId: orderId).execute(apiResponseQueue) { result -> Void in switch result { @@ -42,24 +46,24 @@ open class StoreAPI { - returns: RequestBuilder */ open class func deleteOrderWithRequestBuilder(orderId: String) -> RequestBuilder { - var path = "/store/order/{order_id}" + var localVariablePath = "/store/order/{order_id}" let orderIdPreEscape = "\(APIHelper.mapValueToPathItem(orderId))" let orderIdPostEscape = orderIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" - path = path.replacingOccurrences(of: "{order_id}", with: orderIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + localVariablePath = localVariablePath.replacingOccurrences(of: "{order_id}", with: orderIdPostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "DELETE", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -70,7 +74,7 @@ open class StoreAPI { */ #if canImport(Combine) @available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) - open class func getInventory(apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> AnyPublisher<[String: Int], Error> { + open class func getInventory(apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> AnyPublisher<[String: Int], Error> { return Future<[String: Int], Error>.init { promise in getInventoryWithRequestBuilder().execute(apiResponseQueue) { result -> Void in switch result { @@ -94,21 +98,21 @@ open class StoreAPI { - returns: RequestBuilder<[String: Int]> */ open class func getInventoryWithRequestBuilder() -> RequestBuilder<[String: Int]> { - let path = "/store/inventory" - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + let localVariablePath = "/store/inventory" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder<[String: Int]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder<[String: Int]>.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -120,7 +124,7 @@ open class StoreAPI { */ #if canImport(Combine) @available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) - open class func getOrderById(orderId: Int64, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> AnyPublisher { + open class func getOrderById(orderId: Int64, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> AnyPublisher { return Future.init { promise in getOrderByIdWithRequestBuilder(orderId: orderId).execute(apiResponseQueue) { result -> Void in switch result { @@ -142,24 +146,24 @@ open class StoreAPI { - returns: RequestBuilder */ open class func getOrderByIdWithRequestBuilder(orderId: Int64) -> RequestBuilder { - var path = "/store/order/{order_id}" + var localVariablePath = "/store/order/{order_id}" let orderIdPreEscape = "\(APIHelper.mapValueToPathItem(orderId))" let orderIdPostEscape = orderIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" - path = path.replacingOccurrences(of: "{order_id}", with: orderIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + localVariablePath = localVariablePath.replacingOccurrences(of: "{order_id}", with: orderIdPostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -171,7 +175,7 @@ open class StoreAPI { */ #if canImport(Combine) @available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) - open class func placeOrder(body: Order, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> AnyPublisher { + open class func placeOrder(body: Order, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> AnyPublisher { return Future.init { promise in placeOrderWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { @@ -192,21 +196,20 @@ open class StoreAPI { - returns: RequestBuilder */ open class func placeOrderWithRequestBuilder(body: Order) -> RequestBuilder { - let path = "/store/order" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/store/order" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } - } diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift index cbee9448a00..ce24afbc75c 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift @@ -9,8 +9,12 @@ import Foundation #if canImport(Combine) import Combine #endif +#if canImport(AnyCodable) +import AnyCodable +#endif open class UserAPI { + /** Create user @@ -20,7 +24,7 @@ open class UserAPI { */ #if canImport(Combine) @available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) - open class func createUser(body: User, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> AnyPublisher { + open class func createUser(body: User, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> AnyPublisher { return Future.init { promise in createUserWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { @@ -42,21 +46,21 @@ open class UserAPI { - returns: RequestBuilder */ open class func createUserWithRequestBuilder(body: User) -> RequestBuilder { - let path = "/user" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/user" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -68,7 +72,7 @@ open class UserAPI { */ #if canImport(Combine) @available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) - open class func createUsersWithArrayInput(body: [User], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> AnyPublisher { + open class func createUsersWithArrayInput(body: [User], apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> AnyPublisher { return Future.init { promise in createUsersWithArrayInputWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { @@ -89,21 +93,21 @@ open class UserAPI { - returns: RequestBuilder */ open class func createUsersWithArrayInputWithRequestBuilder(body: [User]) -> RequestBuilder { - let path = "/user/createWithArray" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/user/createWithArray" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -115,7 +119,7 @@ open class UserAPI { */ #if canImport(Combine) @available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) - open class func createUsersWithListInput(body: [User], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> AnyPublisher { + open class func createUsersWithListInput(body: [User], apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> AnyPublisher { return Future.init { promise in createUsersWithListInputWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { @@ -136,21 +140,21 @@ open class UserAPI { - returns: RequestBuilder */ open class func createUsersWithListInputWithRequestBuilder(body: [User]) -> RequestBuilder { - let path = "/user/createWithList" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/user/createWithList" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -162,7 +166,7 @@ open class UserAPI { */ #if canImport(Combine) @available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) - open class func deleteUser(username: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> AnyPublisher { + open class func deleteUser(username: String, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> AnyPublisher { return Future.init { promise in deleteUserWithRequestBuilder(username: username).execute(apiResponseQueue) { result -> Void in switch result { @@ -184,24 +188,24 @@ open class UserAPI { - returns: RequestBuilder */ open class func deleteUserWithRequestBuilder(username: String) -> RequestBuilder { - var path = "/user/{username}" + var localVariablePath = "/user/{username}" let usernamePreEscape = "\(APIHelper.mapValueToPathItem(username))" let usernamePostEscape = usernamePreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" - path = path.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + localVariablePath = localVariablePath.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "DELETE", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -213,7 +217,7 @@ open class UserAPI { */ #if canImport(Combine) @available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) - open class func getUserByName(username: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> AnyPublisher { + open class func getUserByName(username: String, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> AnyPublisher { return Future.init { promise in getUserByNameWithRequestBuilder(username: username).execute(apiResponseQueue) { result -> Void in switch result { @@ -234,24 +238,24 @@ open class UserAPI { - returns: RequestBuilder */ open class func getUserByNameWithRequestBuilder(username: String) -> RequestBuilder { - var path = "/user/{username}" + var localVariablePath = "/user/{username}" let usernamePreEscape = "\(APIHelper.mapValueToPathItem(username))" let usernamePostEscape = usernamePreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" - path = path.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + localVariablePath = localVariablePath.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -264,7 +268,7 @@ open class UserAPI { */ #if canImport(Combine) @available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) - open class func loginUser(username: String, password: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> AnyPublisher { + open class func loginUser(username: String, password: String, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> AnyPublisher { return Future.init { promise in loginUserWithRequestBuilder(username: username, password: password).execute(apiResponseQueue) { result -> Void in switch result { @@ -287,25 +291,25 @@ open class UserAPI { - returns: RequestBuilder */ open class func loginUserWithRequestBuilder(username: String, password: String) -> RequestBuilder { - let path = "/user/login" - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + let localVariablePath = "/user/login" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - var urlComponents = URLComponents(string: URLString) - urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ + var localVariableUrlComponents = URLComponents(string: localVariableURLString) + localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ "username": username.encodeToJSON(), "password": password.encodeToJSON(), ]) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -316,7 +320,7 @@ open class UserAPI { */ #if canImport(Combine) @available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) - open class func logoutUser(apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> AnyPublisher { + open class func logoutUser(apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> AnyPublisher { return Future.init { promise in logoutUserWithRequestBuilder().execute(apiResponseQueue) { result -> Void in switch result { @@ -336,21 +340,21 @@ open class UserAPI { - returns: RequestBuilder */ open class func logoutUserWithRequestBuilder() -> RequestBuilder { - let path = "/user/logout" - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + let localVariablePath = "/user/logout" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -363,7 +367,7 @@ open class UserAPI { */ #if canImport(Combine) @available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) - open class func updateUser(username: String, body: User, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> AnyPublisher { + open class func updateUser(username: String, body: User, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> AnyPublisher { return Future.init { promise in updateUserWithRequestBuilder(username: username, body: body).execute(apiResponseQueue) { result -> Void in switch result { @@ -386,24 +390,23 @@ open class UserAPI { - returns: RequestBuilder */ open class func updateUserWithRequestBuilder(username: String, body: User) -> RequestBuilder { - var path = "/user/{username}" + var localVariablePath = "/user/{username}" let usernamePreEscape = "\(APIHelper.mapValueToPathItem(username))" let usernamePostEscape = usernamePreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" - path = path.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + localVariablePath = localVariablePath.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "PUT", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } - } diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Configuration.swift b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Configuration.swift index 18edabbed78..8fb05331889 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Configuration.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Configuration.swift @@ -7,6 +7,7 @@ import Foundation open class Configuration { + // This value is used to configure the date formatter that is used to serialize dates into JSON format. // You must set it prior to encoding any dates, and it will only be read once. @available(*, unavailable, message: "To set a different date format, use CodableHelper.dateFormatter instead.") diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Extensions.swift b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Extensions.swift index 3aef2d1d6c5..e23035dde30 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Extensions.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Extensions.swift @@ -5,7 +5,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif extension Bool: JSONEncodable { func encodeToJSON() -> Any { return self as Any } @@ -184,44 +186,3 @@ extension HTTPURLResponse { return Array(200 ..< 300).contains(statusCode) } } - -extension AnyCodable: Hashable { - public func hash(into hasher: inout Hasher) { - switch value { - case let value as Bool: - hasher.combine(value) - case let value as Int: - hasher.combine(value) - case let value as Int8: - hasher.combine(value) - case let value as Int16: - hasher.combine(value) - case let value as Int32: - hasher.combine(value) - case let value as Int64: - hasher.combine(value) - case let value as UInt: - hasher.combine(value) - case let value as UInt8: - hasher.combine(value) - case let value as UInt16: - hasher.combine(value) - case let value as UInt32: - hasher.combine(value) - case let value as UInt64: - hasher.combine(value) - case let value as Float: - hasher.combine(value) - case let value as Double: - hasher.combine(value) - case let value as String: - hasher.combine(value) - case let value as [String: AnyCodable]: - hasher.combine(value) - case let value as [AnyCodable]: - hasher.combine(value) - default: - hasher.combine(0) - } - } -} \ No newline at end of file diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesClass.swift b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesClass.swift index 75ab9bc8d0a..621afb93561 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesClass.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesClass.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct AdditionalPropertiesClass: Codable, Hashable { @@ -17,6 +19,7 @@ public struct AdditionalPropertiesClass: Codable, Hashable { self.mapString = mapString self.mapMapString = mapMapString } + public enum CodingKeys: String, CodingKey, CaseIterable { case mapString = "map_string" case mapMapString = "map_map_string" @@ -29,7 +32,5 @@ public struct AdditionalPropertiesClass: Codable, Hashable { try container.encodeIfPresent(mapString, forKey: .mapString) try container.encodeIfPresent(mapMapString, forKey: .mapMapString) } - - - } + diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/Animal.swift b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/Animal.swift index 0f825cf24d0..cdd4f5335b9 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/Animal.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/Animal.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct Animal: Codable, Hashable { @@ -17,6 +19,7 @@ public struct Animal: Codable, Hashable { self.className = className self.color = color } + public enum CodingKeys: String, CodingKey, CaseIterable { case className case color @@ -29,7 +32,5 @@ public struct Animal: Codable, Hashable { try container.encode(className, forKey: .className) try container.encodeIfPresent(color, forKey: .color) } - - - } + diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/AnimalFarm.swift b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/AnimalFarm.swift index b20b894a1ad..a0b09cb9761 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/AnimalFarm.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/AnimalFarm.swift @@ -6,6 +6,8 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public typealias AnimalFarm = [Animal] diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift index 2b66af2dc94..c365505ab9d 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct ApiResponse: Codable, Hashable { @@ -19,6 +21,7 @@ public struct ApiResponse: Codable, Hashable { self.type = type self.message = message } + public enum CodingKeys: String, CodingKey, CaseIterable { case code case type @@ -33,7 +36,5 @@ public struct ApiResponse: Codable, Hashable { try container.encodeIfPresent(type, forKey: .type) try container.encodeIfPresent(message, forKey: .message) } - - - } + diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfArrayOfNumberOnly.swift b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfArrayOfNumberOnly.swift index 06f0640475c..226f7456181 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfArrayOfNumberOnly.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfArrayOfNumberOnly.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct ArrayOfArrayOfNumberOnly: Codable, Hashable { @@ -15,6 +17,7 @@ public struct ArrayOfArrayOfNumberOnly: Codable, Hashable { public init(arrayArrayNumber: [[Double]]? = nil) { self.arrayArrayNumber = arrayArrayNumber } + public enum CodingKeys: String, CodingKey, CaseIterable { case arrayArrayNumber = "ArrayArrayNumber" } @@ -25,7 +28,5 @@ public struct ArrayOfArrayOfNumberOnly: Codable, Hashable { var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(arrayArrayNumber, forKey: .arrayArrayNumber) } - - - } + diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfNumberOnly.swift b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfNumberOnly.swift index 8c50c7fa1e4..39831127871 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfNumberOnly.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfNumberOnly.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct ArrayOfNumberOnly: Codable, Hashable { @@ -15,6 +17,7 @@ public struct ArrayOfNumberOnly: Codable, Hashable { public init(arrayNumber: [Double]? = nil) { self.arrayNumber = arrayNumber } + public enum CodingKeys: String, CodingKey, CaseIterable { case arrayNumber = "ArrayNumber" } @@ -25,7 +28,5 @@ public struct ArrayOfNumberOnly: Codable, Hashable { var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(arrayNumber, forKey: .arrayNumber) } - - - } + diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayTest.swift b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayTest.swift index 461ec7cd9ac..8865d76bef2 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayTest.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayTest.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct ArrayTest: Codable, Hashable { @@ -19,6 +21,7 @@ public struct ArrayTest: Codable, Hashable { self.arrayArrayOfInteger = arrayArrayOfInteger self.arrayArrayOfModel = arrayArrayOfModel } + public enum CodingKeys: String, CodingKey, CaseIterable { case arrayOfString = "array_of_string" case arrayArrayOfInteger = "array_array_of_integer" @@ -33,7 +36,5 @@ public struct ArrayTest: Codable, Hashable { try container.encodeIfPresent(arrayArrayOfInteger, forKey: .arrayArrayOfInteger) try container.encodeIfPresent(arrayArrayOfModel, forKey: .arrayArrayOfModel) } - - - } + diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/Capitalization.swift b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/Capitalization.swift index fbe62983d5e..71cd93bce5f 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/Capitalization.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/Capitalization.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct Capitalization: Codable, Hashable { @@ -26,6 +28,7 @@ public struct Capitalization: Codable, Hashable { self.sCAETHFlowPoints = sCAETHFlowPoints self.ATT_NAME = ATT_NAME } + public enum CodingKeys: String, CodingKey, CaseIterable { case smallCamel case capitalCamel = "CapitalCamel" @@ -46,7 +49,5 @@ public struct Capitalization: Codable, Hashable { try container.encodeIfPresent(sCAETHFlowPoints, forKey: .sCAETHFlowPoints) try container.encodeIfPresent(ATT_NAME, forKey: .ATT_NAME) } - - - } + diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/Cat.swift b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/Cat.swift index 7f3a86932f1..457e04bd475 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/Cat.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/Cat.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct Cat: Codable, Hashable { @@ -19,6 +21,7 @@ public struct Cat: Codable, Hashable { self.color = color self.declawed = declawed } + public enum CodingKeys: String, CodingKey, CaseIterable { case className case color @@ -33,7 +36,5 @@ public struct Cat: Codable, Hashable { try container.encodeIfPresent(color, forKey: .color) try container.encodeIfPresent(declawed, forKey: .declawed) } - - - } + diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/CatAllOf.swift b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/CatAllOf.swift index 8df23954832..8caebb1c206 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/CatAllOf.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/CatAllOf.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct CatAllOf: Codable, Hashable { @@ -15,6 +17,7 @@ public struct CatAllOf: Codable, Hashable { public init(declawed: Bool? = nil) { self.declawed = declawed } + public enum CodingKeys: String, CodingKey, CaseIterable { case declawed } @@ -25,7 +28,5 @@ public struct CatAllOf: Codable, Hashable { var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(declawed, forKey: .declawed) } - - - } + diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/Category.swift b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/Category.swift index 4109db4d1ef..89016ca353d 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/Category.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/Category.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct Category: Codable, Hashable { @@ -17,6 +19,7 @@ public struct Category: Codable, Hashable { self.id = id self.name = name } + public enum CodingKeys: String, CodingKey, CaseIterable { case id case name @@ -29,7 +32,5 @@ public struct Category: Codable, Hashable { try container.encodeIfPresent(id, forKey: .id) try container.encode(name, forKey: .name) } - - - } + diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/ClassModel.swift b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/ClassModel.swift index 7269ddbef6f..16e69e560bd 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/ClassModel.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/ClassModel.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif /** Model for testing model with \"_class\" property */ public struct ClassModel: Codable, Hashable { @@ -16,6 +18,7 @@ public struct ClassModel: Codable, Hashable { public init(_class: String? = nil) { self._class = _class } + public enum CodingKeys: String, CodingKey, CaseIterable { case _class } @@ -26,7 +29,5 @@ public struct ClassModel: Codable, Hashable { var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(_class, forKey: ._class) } - - - } + diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/Client.swift b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/Client.swift index 7d6eff2ffe1..60dbc5dc5c1 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/Client.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/Client.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct Client: Codable, Hashable { @@ -15,6 +17,7 @@ public struct Client: Codable, Hashable { public init(client: String? = nil) { self.client = client } + public enum CodingKeys: String, CodingKey, CaseIterable { case client } @@ -25,7 +28,5 @@ public struct Client: Codable, Hashable { var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(client, forKey: .client) } - - - } + diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/Dog.swift b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/Dog.swift index b5f2bcea38a..658732a7f36 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/Dog.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/Dog.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct Dog: Codable, Hashable { @@ -19,6 +21,7 @@ public struct Dog: Codable, Hashable { self.color = color self.breed = breed } + public enum CodingKeys: String, CodingKey, CaseIterable { case className case color @@ -33,7 +36,5 @@ public struct Dog: Codable, Hashable { try container.encodeIfPresent(color, forKey: .color) try container.encodeIfPresent(breed, forKey: .breed) } - - - } + diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/DogAllOf.swift b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/DogAllOf.swift index 1bfa23d7bc6..82b0dedf35b 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/DogAllOf.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/DogAllOf.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct DogAllOf: Codable, Hashable { @@ -15,6 +17,7 @@ public struct DogAllOf: Codable, Hashable { public init(breed: String? = nil) { self.breed = breed } + public enum CodingKeys: String, CodingKey, CaseIterable { case breed } @@ -25,7 +28,5 @@ public struct DogAllOf: Codable, Hashable { var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(breed, forKey: .breed) } - - - } + diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumArrays.swift b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumArrays.swift index 73368c42143..1d8ce99539c 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumArrays.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumArrays.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct EnumArrays: Codable, Hashable { @@ -25,6 +27,7 @@ public struct EnumArrays: Codable, Hashable { self.justSymbol = justSymbol self.arrayEnum = arrayEnum } + public enum CodingKeys: String, CodingKey, CaseIterable { case justSymbol = "just_symbol" case arrayEnum = "array_enum" @@ -37,7 +40,5 @@ public struct EnumArrays: Codable, Hashable { try container.encodeIfPresent(justSymbol, forKey: .justSymbol) try container.encodeIfPresent(arrayEnum, forKey: .arrayEnum) } - - - } + diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumClass.swift b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumClass.swift index ab01cf297f8..6ea2895aee5 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumClass.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumClass.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public enum EnumClass: String, Codable, CaseIterable { case abc = "_abc" diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumTest.swift b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumTest.swift index 60a81bcac77..8c8bca49774 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumTest.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumTest.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct EnumTest: Codable, Hashable { @@ -41,6 +43,7 @@ public struct EnumTest: Codable, Hashable { self.enumNumber = enumNumber self.outerEnum = outerEnum } + public enum CodingKeys: String, CodingKey, CaseIterable { case enumString = "enum_string" case enumStringRequired = "enum_string_required" @@ -59,7 +62,5 @@ public struct EnumTest: Codable, Hashable { try container.encodeIfPresent(enumNumber, forKey: .enumNumber) try container.encodeIfPresent(outerEnum, forKey: .outerEnum) } - - - } + diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/File.swift b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/File.swift index 90283656d1b..05dd5b1a825 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/File.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/File.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif /** Must be named `File` for test. */ public struct File: Codable, Hashable { @@ -17,6 +19,7 @@ public struct File: Codable, Hashable { public init(sourceURI: String? = nil) { self.sourceURI = sourceURI } + public enum CodingKeys: String, CodingKey, CaseIterable { case sourceURI } @@ -27,7 +30,5 @@ public struct File: Codable, Hashable { var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(sourceURI, forKey: .sourceURI) } - - - } + diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/FileSchemaTestClass.swift b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/FileSchemaTestClass.swift index cff92673bbe..3ca66a31359 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/FileSchemaTestClass.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/FileSchemaTestClass.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct FileSchemaTestClass: Codable, Hashable { @@ -17,6 +19,7 @@ public struct FileSchemaTestClass: Codable, Hashable { self.file = file self.files = files } + public enum CodingKeys: String, CodingKey, CaseIterable { case file case files @@ -29,7 +32,5 @@ public struct FileSchemaTestClass: Codable, Hashable { try container.encodeIfPresent(file, forKey: .file) try container.encodeIfPresent(files, forKey: .files) } - - - } + diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/FormatTest.swift b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/FormatTest.swift index fc86676eec3..a7a4b39e720 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/FormatTest.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/FormatTest.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct FormatTest: Codable, Hashable { @@ -39,6 +41,7 @@ public struct FormatTest: Codable, Hashable { self.uuid = uuid self.password = password } + public enum CodingKeys: String, CodingKey, CaseIterable { case integer case int32 @@ -73,7 +76,5 @@ public struct FormatTest: Codable, Hashable { try container.encodeIfPresent(uuid, forKey: .uuid) try container.encode(password, forKey: .password) } - - - } + diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/HasOnlyReadOnly.swift b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/HasOnlyReadOnly.swift index d7960f5c800..54ed8a723c6 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/HasOnlyReadOnly.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/HasOnlyReadOnly.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct HasOnlyReadOnly: Codable, Hashable { @@ -17,6 +19,7 @@ public struct HasOnlyReadOnly: Codable, Hashable { self.bar = bar self.foo = foo } + public enum CodingKeys: String, CodingKey, CaseIterable { case bar case foo @@ -29,7 +32,5 @@ public struct HasOnlyReadOnly: Codable, Hashable { try container.encodeIfPresent(bar, forKey: .bar) try container.encodeIfPresent(foo, forKey: .foo) } - - - } + diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/List.swift b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/List.swift index c5d4f2cae56..67e3048469f 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/List.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/List.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct List: Codable, Hashable { @@ -15,6 +17,7 @@ public struct List: Codable, Hashable { public init(_123list: String? = nil) { self._123list = _123list } + public enum CodingKeys: String, CodingKey, CaseIterable { case _123list = "123-list" } @@ -25,7 +28,5 @@ public struct List: Codable, Hashable { var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(_123list, forKey: ._123list) } - - - } + diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/MapTest.swift b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/MapTest.swift index b54bd01e5dc..1e728fcdf58 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/MapTest.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/MapTest.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct MapTest: Codable, Hashable { @@ -25,6 +27,7 @@ public struct MapTest: Codable, Hashable { self.directMap = directMap self.indirectMap = indirectMap } + public enum CodingKeys: String, CodingKey, CaseIterable { case mapMapOfString = "map_map_of_string" case mapOfEnumString = "map_of_enum_string" @@ -41,7 +44,5 @@ public struct MapTest: Codable, Hashable { try container.encodeIfPresent(directMap, forKey: .directMap) try container.encodeIfPresent(indirectMap, forKey: .indirectMap) } - - - } + diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/MixedPropertiesAndAdditionalPropertiesClass.swift b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/MixedPropertiesAndAdditionalPropertiesClass.swift index c8f639ef43d..c79ca459217 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/MixedPropertiesAndAdditionalPropertiesClass.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/MixedPropertiesAndAdditionalPropertiesClass.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct MixedPropertiesAndAdditionalPropertiesClass: Codable, Hashable { @@ -19,6 +21,7 @@ public struct MixedPropertiesAndAdditionalPropertiesClass: Codable, Hashable { self.dateTime = dateTime self.map = map } + public enum CodingKeys: String, CodingKey, CaseIterable { case uuid case dateTime @@ -33,7 +36,5 @@ public struct MixedPropertiesAndAdditionalPropertiesClass: Codable, Hashable { try container.encodeIfPresent(dateTime, forKey: .dateTime) try container.encodeIfPresent(map, forKey: .map) } - - - } + diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/Model200Response.swift b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/Model200Response.swift index 5368032f09b..23402143f71 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/Model200Response.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/Model200Response.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif /** Model for testing model name starting with number */ public struct Model200Response: Codable, Hashable { @@ -18,6 +20,7 @@ public struct Model200Response: Codable, Hashable { self.name = name self._class = _class } + public enum CodingKeys: String, CodingKey, CaseIterable { case name case _class = "class" @@ -30,7 +33,5 @@ public struct Model200Response: Codable, Hashable { try container.encodeIfPresent(name, forKey: .name) try container.encodeIfPresent(_class, forKey: ._class) } - - - } + diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/Name.swift b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/Name.swift index 84a40e1c101..a28f46a33ce 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/Name.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/Name.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif /** Model for testing model name same as property name */ public struct Name: Codable, Hashable { @@ -22,6 +24,7 @@ public struct Name: Codable, Hashable { self.property = property self._123number = _123number } + public enum CodingKeys: String, CodingKey, CaseIterable { case name case snakeCase = "snake_case" @@ -38,7 +41,5 @@ public struct Name: Codable, Hashable { try container.encodeIfPresent(property, forKey: .property) try container.encodeIfPresent(_123number, forKey: ._123number) } - - - } + diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/NumberOnly.swift b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/NumberOnly.swift index 710f41648f9..87ceb64bb97 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/NumberOnly.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/NumberOnly.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct NumberOnly: Codable, Hashable { @@ -15,6 +17,7 @@ public struct NumberOnly: Codable, Hashable { public init(justNumber: Double? = nil) { self.justNumber = justNumber } + public enum CodingKeys: String, CodingKey, CaseIterable { case justNumber = "JustNumber" } @@ -25,7 +28,5 @@ public struct NumberOnly: Codable, Hashable { var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(justNumber, forKey: .justNumber) } - - - } + diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/Order.swift b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/Order.swift index 15726ab16a4..e2eeced4c57 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/Order.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/Order.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct Order: Codable, Hashable { @@ -31,6 +33,7 @@ public struct Order: Codable, Hashable { self.status = status self.complete = complete } + public enum CodingKeys: String, CodingKey, CaseIterable { case id case petId @@ -51,7 +54,5 @@ public struct Order: Codable, Hashable { try container.encodeIfPresent(status, forKey: .status) try container.encodeIfPresent(complete, forKey: .complete) } - - - } + diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/OuterComposite.swift b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/OuterComposite.swift index 36904afbd50..edeaccaeaa6 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/OuterComposite.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/OuterComposite.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct OuterComposite: Codable, Hashable { @@ -19,6 +21,7 @@ public struct OuterComposite: Codable, Hashable { self.myString = myString self.myBoolean = myBoolean } + public enum CodingKeys: String, CodingKey, CaseIterable { case myNumber = "my_number" case myString = "my_string" @@ -33,7 +36,5 @@ public struct OuterComposite: Codable, Hashable { try container.encodeIfPresent(myString, forKey: .myString) try container.encodeIfPresent(myBoolean, forKey: .myBoolean) } - - - } + diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/OuterEnum.swift b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/OuterEnum.swift index 9bd6f3bef8f..76c34b3c2ce 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/OuterEnum.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/OuterEnum.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public enum OuterEnum: String, Codable, CaseIterable { case placed = "placed" diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/Pet.swift b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/Pet.swift index 7a1c2826a19..ddd1186b891 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/Pet.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/Pet.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct Pet: Codable, Hashable { @@ -31,6 +33,7 @@ public struct Pet: Codable, Hashable { self.tags = tags self.status = status } + public enum CodingKeys: String, CodingKey, CaseIterable { case id case category @@ -51,7 +54,5 @@ public struct Pet: Codable, Hashable { try container.encodeIfPresent(tags, forKey: .tags) try container.encodeIfPresent(status, forKey: .status) } - - - } + diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/ReadOnlyFirst.swift b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/ReadOnlyFirst.swift index 38fb57af328..57ba3f577c8 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/ReadOnlyFirst.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/ReadOnlyFirst.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct ReadOnlyFirst: Codable, Hashable { @@ -17,6 +19,7 @@ public struct ReadOnlyFirst: Codable, Hashable { self.bar = bar self.baz = baz } + public enum CodingKeys: String, CodingKey, CaseIterable { case bar case baz @@ -29,7 +32,5 @@ public struct ReadOnlyFirst: Codable, Hashable { try container.encodeIfPresent(bar, forKey: .bar) try container.encodeIfPresent(baz, forKey: .baz) } - - - } + diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/Return.swift b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/Return.swift index ed7e538a06d..afc2b51f8f3 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/Return.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/Return.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif /** Model for testing reserved words */ public struct Return: Codable, Hashable { @@ -16,6 +18,7 @@ public struct Return: Codable, Hashable { public init(_return: Int? = nil) { self._return = _return } + public enum CodingKeys: String, CodingKey, CaseIterable { case _return = "return" } @@ -26,7 +29,5 @@ public struct Return: Codable, Hashable { var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(_return, forKey: ._return) } - - - } + diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/SpecialModelName.swift b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/SpecialModelName.swift index 18747e071bc..bfe9723f888 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/SpecialModelName.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/SpecialModelName.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct SpecialModelName: Codable, Hashable { @@ -15,6 +17,7 @@ public struct SpecialModelName: Codable, Hashable { public init(specialPropertyName: Int64? = nil) { self.specialPropertyName = specialPropertyName } + public enum CodingKeys: String, CodingKey, CaseIterable { case specialPropertyName = "$special[property.name]" } @@ -25,7 +28,5 @@ public struct SpecialModelName: Codable, Hashable { var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(specialPropertyName, forKey: .specialPropertyName) } - - - } + diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/StringBooleanMap.swift b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/StringBooleanMap.swift index 0699c25ff7e..126c35c85a6 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/StringBooleanMap.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/StringBooleanMap.swift @@ -6,12 +6,16 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct StringBooleanMap: Codable, Hashable { + public enum CodingKeys: CodingKey, CaseIterable { } + public var additionalProperties: [String: Bool] = [:] public subscript(key: String) -> Bool? { @@ -38,11 +42,11 @@ public struct StringBooleanMap: Codable, Hashable { // Decodable protocol methods public init(from decoder: Decoder) throws { - let container = try decoder.container(keyedBy: String.self) + let container = try decoder.container(keyedBy: CodingKeys.self) var nonAdditionalPropertyKeys = Set() - additionalProperties = try container.decodeMap(Bool.self, excludedKeys: nonAdditionalPropertyKeys) + let additionalPropertiesContainer = try decoder.container(keyedBy: String.self) + additionalProperties = try additionalPropertiesContainer.decodeMap(Bool.self, excludedKeys: nonAdditionalPropertyKeys) } - - } + diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift index 11c5f7a750b..07b826264f3 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct Tag: Codable, Hashable { @@ -17,6 +19,7 @@ public struct Tag: Codable, Hashable { self.id = id self.name = name } + public enum CodingKeys: String, CodingKey, CaseIterable { case id case name @@ -29,7 +32,5 @@ public struct Tag: Codable, Hashable { try container.encodeIfPresent(id, forKey: .id) try container.encodeIfPresent(name, forKey: .name) } - - - } + diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderDefault.swift b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderDefault.swift index 35b1a5833b9..e58eecd960f 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderDefault.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderDefault.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct TypeHolderDefault: Codable, Hashable { @@ -23,6 +25,7 @@ public struct TypeHolderDefault: Codable, Hashable { self.boolItem = boolItem self.arrayItem = arrayItem } + public enum CodingKeys: String, CodingKey, CaseIterable { case stringItem = "string_item" case numberItem = "number_item" @@ -41,7 +44,5 @@ public struct TypeHolderDefault: Codable, Hashable { try container.encode(boolItem, forKey: .boolItem) try container.encode(arrayItem, forKey: .arrayItem) } - - - } + diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderExample.swift b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderExample.swift index 37277a4ac00..6c22fdbae7a 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderExample.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderExample.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct TypeHolderExample: Codable, Hashable { @@ -23,6 +25,7 @@ public struct TypeHolderExample: Codable, Hashable { self.boolItem = boolItem self.arrayItem = arrayItem } + public enum CodingKeys: String, CodingKey, CaseIterable { case stringItem = "string_item" case numberItem = "number_item" @@ -41,7 +44,5 @@ public struct TypeHolderExample: Codable, Hashable { try container.encode(boolItem, forKey: .boolItem) try container.encode(arrayItem, forKey: .arrayItem) } - - - } + diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/User.swift b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/User.swift index 2bbc31806ff..7afe359ae40 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/User.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models/User.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct User: Codable, Hashable { @@ -30,6 +32,7 @@ public struct User: Codable, Hashable { self.phone = phone self.userStatus = userStatus } + public enum CodingKeys: String, CodingKey, CaseIterable { case id case username @@ -54,7 +57,5 @@ public struct User: Codable, Hashable { try container.encodeIfPresent(phone, forKey: .phone) try container.encodeIfPresent(userStatus, forKey: .userStatus) } - - - } + 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 52b2071ec1a..41959190a26 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift @@ -93,14 +93,14 @@ open class URLSessionRequestBuilder: RequestBuilder { return modifiedRequest } - override open func execute(_ apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, _ completion: @escaping (_ result: Swift.Result, Error>) -> Void) { + override open func execute(_ apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, _ completion: @escaping (_ result: Swift.Result, Error>) -> Void) { let urlSessionId = UUID().uuidString // Create a new manager for each request to customize its request header let urlSession = createURLSession() urlSessionStore[urlSessionId] = urlSession guard let xMethod = HTTPMethod(rawValue: method) else { - fatalError("Unsuported Http method - \(method)") + fatalError("Unsupported Http method - \(method)") } let encoding: ParameterEncoding @@ -119,7 +119,7 @@ open class URLSessionRequestBuilder: RequestBuilder { } else if contentType == "application/x-www-form-urlencoded" { encoding = FormURLEncoding() } else { - fatalError("Unsuported Media Type - \(contentType)") + fatalError("Unsupported Media Type - \(contentType)") } } @@ -205,16 +205,18 @@ open class URLSessionRequestBuilder: RequestBuilder { } let fileManager = FileManager.default - let documentsDirectory = fileManager.urls(for: .documentDirectory, in: .userDomainMask)[0] + let cachesDirectory = fileManager.urls(for: .cachesDirectory, in: .userDomainMask)[0] let requestURL = try getURL(from: urlRequest) var requestPath = try getPath(from: requestURL) if let headerFileName = getFileName(fromContentDisposition: httpResponse.allHeaderFields["Content-Disposition"] as? String) { requestPath = requestPath.appending("/\(headerFileName)") + } else { + requestPath = requestPath.appending("/tmp.PetstoreClient.\(UUID().uuidString)") } - let filePath = documentsDirectory.appendingPathComponent(requestPath) + let filePath = cachesDirectory.appendingPathComponent(requestPath) let directoryPath = filePath.deletingLastPathComponent().path try fileManager.createDirectory(atPath: directoryPath, withIntermediateDirectories: true, attributes: nil) @@ -232,6 +234,10 @@ open class URLSessionRequestBuilder: RequestBuilder { completion(.success(Response(response: httpResponse, body: nil))) + case is Data.Type: + + completion(.success(Response(response: httpResponse, body: data as? T))) + default: completion(.success(Response(response: httpResponse, body: data as? T))) @@ -244,7 +250,7 @@ open class URLSessionRequestBuilder: RequestBuilder { for (key, value) in headers { httpHeaders[key] = value } - for (key, value) in PetstoreClientAPI.customHeaders { + for (key, value) in PetstoreClient.customHeaders { httpHeaders[key] = value } return httpHeaders @@ -328,6 +334,43 @@ open class URLSessionDecodableRequestBuilder: URLSessionRequestBui completion(.success(Response(response: httpResponse, body: body as? T))) + case is URL.Type: + do { + + guard error == nil else { + throw DownloadException.responseFailed + } + + guard let data = data else { + throw DownloadException.responseDataMissing + } + + let fileManager = FileManager.default + let cachesDirectory = fileManager.urls(for: .cachesDirectory, in: .userDomainMask)[0] + let requestURL = try getURL(from: urlRequest) + + var requestPath = try getPath(from: requestURL) + + if let headerFileName = getFileName(fromContentDisposition: httpResponse.allHeaderFields["Content-Disposition"] as? String) { + requestPath = requestPath.appending("/\(headerFileName)") + } else { + requestPath = requestPath.appending("/tmp.PetstoreClient.\(UUID().uuidString)") + } + + let filePath = cachesDirectory.appendingPathComponent(requestPath) + let directoryPath = filePath.deletingLastPathComponent().path + + try fileManager.createDirectory(atPath: directoryPath, withIntermediateDirectories: true, attributes: nil) + try data.write(to: filePath, options: .atomic) + + completion(.success(Response(response: httpResponse, body: filePath as? T))) + + } catch let requestParserError as DownloadException { + completion(.failure(ErrorResponse.error(400, data, response, requestParserError))) + } catch { + completion(.failure(ErrorResponse.error(400, data, response, error))) + } + case is Void.Type: completion(.success(Response(response: httpResponse, body: nil))) diff --git a/samples/client/petstore/swift5/combineLibrary/SwaggerClientTests/.gitignore b/samples/client/petstore/swift5/combineLibrary/SwaggerClientTests/.gitignore index 0269c2f56db..22029d2f644 100644 --- a/samples/client/petstore/swift5/combineLibrary/SwaggerClientTests/.gitignore +++ b/samples/client/petstore/swift5/combineLibrary/SwaggerClientTests/.gitignore @@ -1,14 +1,22 @@ -### https://raw.github.com/github/gitignore/7792e50daeaa6c07460484704671d1dc9f0045a7/Swift.gitignore +# Created by https://www.toptal.com/developers/gitignore/api/swift,xcode +# Edit at https://www.toptal.com/developers/gitignore?templates=swift,xcode +### Swift ### # Xcode # # gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore -## Build generated +## User settings +xcuserdata/ + +## compatibility with Xcode 8 and earlier (ignoring not required starting Xcode 9) +*.xcscmblueprint +*.xccheckout + +## compatibility with Xcode 3 and earlier (ignoring not required starting Xcode 4) build/ DerivedData/ - -## Various settings +*.moved-aside *.pbxuser !default.pbxuser *.mode1v3 @@ -17,15 +25,11 @@ DerivedData/ !default.mode2v3 *.perspectivev3 !default.perspectivev3 -xcuserdata/ - -## Other -*.moved-aside -*.xccheckout -*.xcscmblueprint ## Obj-C/Swift specific *.hmap + +## App packaging *.ipa *.dSYM.zip *.dSYM @@ -35,38 +39,67 @@ timeline.xctimeline playground.xcworkspace # Swift Package Manager -# # Add this line if you want to avoid checking in source code from Swift Package Manager dependencies. # Packages/ # Package.pins # Package.resolved +# *.xcodeproj +# Xcode automatically generates this directory with a .xcworkspacedata file and xcuserdata +# hence it is not needed unless you have added a package configuration file to your project +# .swiftpm + .build/ # CocoaPods -# # We recommend against adding the Pods directory to your .gitignore. However # you should judge for yourself, the pros and cons are mentioned at: # https://guides.cocoapods.org/using/using-cocoapods.html#should-i-check-the-pods-directory-into-source-control -# -Pods/ +# Pods/ +# Add this line if you want to avoid checking in source code from the Xcode workspace +# *.xcworkspace # Carthage -# # Add this line if you want to avoid checking in source code from Carthage dependencies. -Carthage/Checkouts +# Carthage/Checkouts -Carthage/Build +Carthage/Build/ + +# Add this lines if you are using Accio dependency management (Deprecated since Xcode 12) +# Dependencies/ +# .accio/ # fastlane -# -# It is recommended to not store the screenshots in the git repo. Instead, use fastlane to re-generate the -# screenshots whenever they are needed. +# It is recommended to not store the screenshots in the git repo. +# Instead, use fastlane to re-generate the screenshots whenever they are needed. # For more information about the recommended setup visit: # https://docs.fastlane.tools/best-practices/source-control/#source-control fastlane/report.xml fastlane/Preview.html -fastlane/screenshots +fastlane/screenshots/**/*.png fastlane/test_output +# Code Injection +# After new code Injection tools there's a generated folder /iOSInjectionProject +# https://github.com/johnno1962/injectionforxcode +iOSInjectionProject/ + +### Xcode ### +# Xcode +# gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore + + + + +## Gcc Patch +/*.gcno + +### Xcode Patch ### +*.xcodeproj/* +!*.xcodeproj/project.pbxproj +!*.xcodeproj/xcshareddata/ +!*.xcworkspace/contents.xcworkspacedata +**/xcshareddata/WorkspaceSettings.xcsettings + +# End of https://www.toptal.com/developers/gitignore/api/swift,xcode \ No newline at end of file diff --git a/samples/client/petstore/swift5/combineLibrary/SwaggerClientTests/Podfile b/samples/client/petstore/swift5/combineLibrary/SwaggerClientTests/Podfile deleted file mode 100644 index 77432f9eee9..00000000000 --- a/samples/client/petstore/swift5/combineLibrary/SwaggerClientTests/Podfile +++ /dev/null @@ -1,13 +0,0 @@ -platform :ios, '9.0' - -source 'https://cdn.cocoapods.org/' - -use_frameworks! - -target 'SwaggerClient' do - pod "PetstoreClient", :path => "../" - - target 'SwaggerClientTests' do - inherit! :search_paths - end -end diff --git a/samples/client/petstore/swift5/combineLibrary/SwaggerClientTests/Podfile.lock b/samples/client/petstore/swift5/combineLibrary/SwaggerClientTests/Podfile.lock deleted file mode 100644 index a621fdeec88..00000000000 --- a/samples/client/petstore/swift5/combineLibrary/SwaggerClientTests/Podfile.lock +++ /dev/null @@ -1,16 +0,0 @@ -PODS: - - PetstoreClient (1.0.0) - -DEPENDENCIES: - - PetstoreClient (from `../`) - -EXTERNAL SOURCES: - PetstoreClient: - :path: "../" - -SPEC CHECKSUMS: - PetstoreClient: b26b235a3ece06dbf1da99dc67e48aa201659f21 - -PODFILE CHECKSUM: 509bec696cc1d8641751b52e4fe4bef04ac4542c - -COCOAPODS: 1.9.0 diff --git a/samples/client/petstore/swift5/combineLibrary/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj b/samples/client/petstore/swift5/combineLibrary/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj index 0be50e9f6f1..84e7599d4d3 100644 --- a/samples/client/petstore/swift5/combineLibrary/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj +++ b/samples/client/petstore/swift5/combineLibrary/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj @@ -3,14 +3,13 @@ archiveVersion = 1; classes = { }; - objectVersion = 46; + objectVersion = 52; objects = { /* Begin PBXBuildFile section */ + A5782C732664FABF00CAA106 /* PetstoreClient in Frameworks */ = {isa = PBXBuildFile; productRef = A5782C722664FABF00CAA106 /* PetstoreClient */; }; A5EA12582419390400E30FC3 /* FileUtils.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5EA12562419390400E30FC3 /* FileUtils.swift */; }; A5EA12592419390400E30FC3 /* UIImage+Extras.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5EA12572419390400E30FC3 /* UIImage+Extras.swift */; }; - B024164FBFF71BF644D4419A /* Pods_SwaggerClient.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 177A58DD5CF63F2989335DCC /* Pods_SwaggerClient.framework */; }; - B1D0246C8960F47A60098F37 /* Pods_SwaggerClientTests.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 6F96A0131101344CC5406CB3 /* Pods_SwaggerClientTests.framework */; }; B596E4BD205657A500B46F03 /* APIHelperTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = B596E4BC205657A500B46F03 /* APIHelperTests.swift */; }; EAEC0BC21D4E30CE00C908A3 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = EAEC0BC11D4E30CE00C908A3 /* AppDelegate.swift */; }; EAEC0BC41D4E30CE00C908A3 /* ViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = EAEC0BC31D4E30CE00C908A3 /* ViewController.swift */; }; @@ -33,11 +32,6 @@ /* End PBXContainerItemProxy section */ /* Begin PBXFileReference section */ - 177A58DD5CF63F2989335DCC /* Pods_SwaggerClient.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_SwaggerClient.framework; sourceTree = BUILT_PRODUCTS_DIR; }; - 2DEFA8828BD4E38FA5262F53 /* Pods-SwaggerClient.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-SwaggerClient.release.xcconfig"; path = "Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient.release.xcconfig"; sourceTree = ""; }; - 4EF2021609D112A6F5AE0F55 /* Pods-SwaggerClientTests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-SwaggerClientTests.debug.xcconfig"; path = "Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests.debug.xcconfig"; sourceTree = ""; }; - 6F96A0131101344CC5406CB3 /* Pods_SwaggerClientTests.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_SwaggerClientTests.framework; sourceTree = BUILT_PRODUCTS_DIR; }; - 8D99518E8E05FD856A952698 /* Pods-SwaggerClient.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-SwaggerClient.debug.xcconfig"; path = "Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient.debug.xcconfig"; sourceTree = ""; }; A5EA12562419390400E30FC3 /* FileUtils.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FileUtils.swift; sourceTree = ""; }; A5EA12572419390400E30FC3 /* UIImage+Extras.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "UIImage+Extras.swift"; sourceTree = ""; }; B596E4BC205657A500B46F03 /* APIHelperTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = APIHelperTests.swift; sourceTree = ""; }; @@ -53,7 +47,6 @@ EAEC0BE31D4E330700C908A3 /* PetAPITests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PetAPITests.swift; sourceTree = ""; }; EAEC0BE51D4E379000C908A3 /* StoreAPITests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StoreAPITests.swift; sourceTree = ""; }; EAEC0BE71D4E38CB00C908A3 /* UserAPITests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = UserAPITests.swift; sourceTree = ""; }; - EFD8AB05F53C74985527D117 /* Pods-SwaggerClientTests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-SwaggerClientTests.release.xcconfig"; path = "Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests.release.xcconfig"; sourceTree = ""; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ @@ -61,7 +54,7 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( - B024164FBFF71BF644D4419A /* Pods_SwaggerClient.framework in Frameworks */, + A5782C732664FABF00CAA106 /* PetstoreClient in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -69,41 +62,26 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( - B1D0246C8960F47A60098F37 /* Pods_SwaggerClientTests.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */ - 55DC454FF5FFEF8A9CBC1CA3 /* Frameworks */ = { + A5782C712664FABE00CAA106 /* Frameworks */ = { isa = PBXGroup; children = ( - 177A58DD5CF63F2989335DCC /* Pods_SwaggerClient.framework */, - 6F96A0131101344CC5406CB3 /* Pods_SwaggerClientTests.framework */, ); name = Frameworks; sourceTree = ""; }; - CB19142D951AB5DD885404A8 /* Pods */ = { - isa = PBXGroup; - children = ( - 8D99518E8E05FD856A952698 /* Pods-SwaggerClient.debug.xcconfig */, - 2DEFA8828BD4E38FA5262F53 /* Pods-SwaggerClient.release.xcconfig */, - 4EF2021609D112A6F5AE0F55 /* Pods-SwaggerClientTests.debug.xcconfig */, - EFD8AB05F53C74985527D117 /* Pods-SwaggerClientTests.release.xcconfig */, - ); - name = Pods; - sourceTree = ""; - }; EAEC0BB51D4E30CE00C908A3 = { isa = PBXGroup; children = ( EAEC0BC01D4E30CE00C908A3 /* SwaggerClient */, EAEC0BD51D4E30CE00C908A3 /* SwaggerClientTests */, EAEC0BBF1D4E30CE00C908A3 /* Products */, - CB19142D951AB5DD885404A8 /* Pods */, - 55DC454FF5FFEF8A9CBC1CA3 /* Frameworks */, + A5782C712664FABE00CAA106 /* Frameworks */, ); sourceTree = ""; }; @@ -150,17 +128,18 @@ isa = PBXNativeTarget; buildConfigurationList = EAEC0BDB1D4E30CE00C908A3 /* Build configuration list for PBXNativeTarget "SwaggerClient" */; buildPhases = ( - 898E536ECC2C4811DDDF67C1 /* [CP] Check Pods Manifest.lock */, EAEC0BBA1D4E30CE00C908A3 /* Sources */, EAEC0BBB1D4E30CE00C908A3 /* Frameworks */, EAEC0BBC1D4E30CE00C908A3 /* Resources */, - 8A7961360961F06AADAF17C9 /* [CP] Embed Pods Frameworks */, ); buildRules = ( ); dependencies = ( ); name = SwaggerClient; + packageProductDependencies = ( + A5782C722664FABF00CAA106 /* PetstoreClient */, + ); productName = SwaggerClient; productReference = EAEC0BBE1D4E30CE00C908A3 /* SwaggerClient.app */; productType = "com.apple.product-type.application"; @@ -169,7 +148,6 @@ isa = PBXNativeTarget; buildConfigurationList = EAEC0BDE1D4E30CE00C908A3 /* Build configuration list for PBXNativeTarget "SwaggerClientTests" */; buildPhases = ( - 82CB35D52E274C6177DAC0DD /* [CP] Check Pods Manifest.lock */, EAEC0BCE1D4E30CE00C908A3 /* Sources */, EAEC0BCF1D4E30CE00C908A3 /* Frameworks */, EAEC0BD01D4E30CE00C908A3 /* Resources */, @@ -244,63 +222,6 @@ }; /* End PBXResourcesBuildPhase section */ -/* Begin PBXShellScriptBuildPhase section */ - 82CB35D52E274C6177DAC0DD /* [CP] Check Pods Manifest.lock */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputPaths = ( - "${PODS_PODFILE_DIR_PATH}/Podfile.lock", - "${PODS_ROOT}/Manifest.lock", - ); - name = "[CP] Check Pods Manifest.lock"; - outputPaths = ( - "$(DERIVED_FILE_DIR)/Pods-SwaggerClientTests-checkManifestLockResult.txt", - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; - showEnvVarsInLog = 0; - }; - 898E536ECC2C4811DDDF67C1 /* [CP] Check Pods Manifest.lock */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputPaths = ( - "${PODS_PODFILE_DIR_PATH}/Podfile.lock", - "${PODS_ROOT}/Manifest.lock", - ); - name = "[CP] Check Pods Manifest.lock"; - outputPaths = ( - "$(DERIVED_FILE_DIR)/Pods-SwaggerClient-checkManifestLockResult.txt", - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; - showEnvVarsInLog = 0; - }; - 8A7961360961F06AADAF17C9 /* [CP] Embed Pods Frameworks */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputPaths = ( - "${PODS_ROOT}/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-frameworks.sh", - "${BUILT_PRODUCTS_DIR}/PetstoreClient/PetstoreClient.framework", - ); - name = "[CP] Embed Pods Frameworks"; - outputPaths = ( - "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/PetstoreClient.framework", - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-frameworks.sh\"\n"; - showEnvVarsInLog = 0; - }; -/* End PBXShellScriptBuildPhase section */ - /* Begin PBXSourcesBuildPhase section */ EAEC0BBA1D4E30CE00C908A3 /* Sources */ = { isa = PBXSourcesBuildPhase; @@ -456,7 +377,8 @@ IPHONEOS_DEPLOYMENT_TARGET = 9.3; MTL_ENABLE_DEBUG_INFO = NO; SDKROOT = iphoneos; - SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; SWIFT_VERSION = 4.2; VALIDATE_PRODUCT = YES; }; @@ -464,11 +386,13 @@ }; EAEC0BDC1D4E30CE00C908A3 /* Debug */ = { isa = XCBuildConfiguration; - baseConfigurationReference = 8D99518E8E05FD856A952698 /* Pods-SwaggerClient.debug.xcconfig */; buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; INFOPLIST_FILE = SwaggerClient/Info.plist; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); PRODUCT_BUNDLE_IDENTIFIER = com.swagger.SwaggerClient; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_VERSION = 5.0; @@ -478,11 +402,13 @@ }; EAEC0BDD1D4E30CE00C908A3 /* Release */ = { isa = XCBuildConfiguration; - baseConfigurationReference = 2DEFA8828BD4E38FA5262F53 /* Pods-SwaggerClient.release.xcconfig */; buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; INFOPLIST_FILE = SwaggerClient/Info.plist; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); PRODUCT_BUNDLE_IDENTIFIER = com.swagger.SwaggerClient; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_VERSION = 5.0; @@ -492,12 +418,15 @@ }; EAEC0BDF1D4E30CE00C908A3 /* Debug */ = { isa = XCBuildConfiguration; - baseConfigurationReference = 4EF2021609D112A6F5AE0F55 /* Pods-SwaggerClientTests.debug.xcconfig */; buildSettings = { BUNDLE_LOADER = "$(TEST_HOST)"; CLANG_ENABLE_MODULES = YES; INFOPLIST_FILE = SwaggerClientTests/Info.plist; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); PRODUCT_BUNDLE_IDENTIFIER = com.swagger.SwaggerClientTests; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_OPTIMIZATION_LEVEL = "-Onone"; @@ -508,12 +437,15 @@ }; EAEC0BE01D4E30CE00C908A3 /* Release */ = { isa = XCBuildConfiguration; - baseConfigurationReference = EFD8AB05F53C74985527D117 /* Pods-SwaggerClientTests.release.xcconfig */; buildSettings = { BUNDLE_LOADER = "$(TEST_HOST)"; CLANG_ENABLE_MODULES = YES; INFOPLIST_FILE = SwaggerClientTests/Info.plist; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); PRODUCT_BUNDLE_IDENTIFIER = com.swagger.SwaggerClientTests; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_VERSION = 5.0; @@ -552,6 +484,13 @@ defaultConfigurationName = Release; }; /* End XCConfigurationList section */ + +/* Begin XCSwiftPackageProductDependency section */ + A5782C722664FABF00CAA106 /* PetstoreClient */ = { + isa = XCSwiftPackageProductDependency; + productName = PetstoreClient; + }; +/* End XCSwiftPackageProductDependency section */ }; rootObject = EAEC0BB61D4E30CE00C908A3 /* Project object */; } diff --git a/samples/client/petstore/swift5/combineLibrary/SwaggerClientTests/SwaggerClient.xcworkspace/contents.xcworkspacedata b/samples/client/petstore/swift5/combineLibrary/SwaggerClientTests/SwaggerClient.xcworkspace/contents.xcworkspacedata index 9b3fa18954f..00ec9b53a7f 100644 --- a/samples/client/petstore/swift5/combineLibrary/SwaggerClientTests/SwaggerClient.xcworkspace/contents.xcworkspacedata +++ b/samples/client/petstore/swift5/combineLibrary/SwaggerClientTests/SwaggerClient.xcworkspace/contents.xcworkspacedata @@ -2,9 +2,9 @@ + location = "group:.."> + location = "group:SwaggerClient.xcodeproj"> diff --git a/samples/client/petstore/swift5/combineLibrary/SwaggerClientTests/SwaggerClient.xcworkspace/xcshareddata/swiftpm/Package.resolved b/samples/client/petstore/swift5/combineLibrary/SwaggerClientTests/SwaggerClient.xcworkspace/xcshareddata/swiftpm/Package.resolved new file mode 100644 index 00000000000..d384b276b4b --- /dev/null +++ b/samples/client/petstore/swift5/combineLibrary/SwaggerClientTests/SwaggerClient.xcworkspace/xcshareddata/swiftpm/Package.resolved @@ -0,0 +1,16 @@ +{ + "object": { + "pins": [ + { + "package": "AnyCodable", + "repositoryURL": "https://github.com/Flight-School/AnyCodable", + "state": { + "branch": null, + "revision": "876d162385e9862ae8b3c8d65dc301312b040005", + "version": "0.6.0" + } + } + ] + }, + "version": 1 +} diff --git a/samples/client/petstore/swift5/combineLibrary/docs/FakeAPI.md b/samples/client/petstore/swift5/combineLibrary/docs/FakeAPI.md index 543869c0d2e..553a46281aa 100644 --- a/samples/client/petstore/swift5/combineLibrary/docs/FakeAPI.md +++ b/samples/client/petstore/swift5/combineLibrary/docs/FakeAPI.md @@ -379,7 +379,7 @@ import PetstoreClient let number = 987 // Double | None let double = 987 // Double | None let patternWithoutDelimiter = "patternWithoutDelimiter_example" // String | None -let byte = 987 // Data | None +let byte = Data([9, 8, 7]) // Data | None let integer = 987 // Int | None (optional) let int32 = 987 // Int | None (optional) let int64 = 987 // Int64 | None (optional) diff --git a/samples/client/petstore/swift5/combineLibrary/project.yml b/samples/client/petstore/swift5/combineLibrary/project.yml index 5528eeee513..0493cf65896 100644 --- a/samples/client/petstore/swift5/combineLibrary/project.yml +++ b/samples/client/petstore/swift5/combineLibrary/project.yml @@ -11,5 +11,5 @@ targets: settings: APPLICATION_EXTENSION_API_ONLY: true scheme: {} - + dependencies: - carthage: AnyCodable diff --git a/samples/client/petstore/swift5/default/.gitignore b/samples/client/petstore/swift5/default/.gitignore index 5e5d5cebcf4..627d360a903 100644 --- a/samples/client/petstore/swift5/default/.gitignore +++ b/samples/client/petstore/swift5/default/.gitignore @@ -1,12 +1,22 @@ +# Created by https://www.toptal.com/developers/gitignore/api/swift,xcode +# Edit at https://www.toptal.com/developers/gitignore?templates=swift,xcode + +### Swift ### # Xcode # # gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore -## Build generated -build/ -DerivedData +## User settings +xcuserdata/ -## Various settings +## compatibility with Xcode 8 and earlier (ignoring not required starting Xcode 9) +*.xcscmblueprint +*.xccheckout + +## compatibility with Xcode 3 and earlier (ignoring not required starting Xcode 4) +build/ +DerivedData/ +*.moved-aside *.pbxuser !default.pbxuser *.mode1v3 @@ -15,49 +25,81 @@ DerivedData !default.mode2v3 *.perspectivev3 !default.perspectivev3 -xcuserdata - -## Other -*.xccheckout -*.moved-aside -*.xcuserstate -*.xcscmblueprint ## Obj-C/Swift specific *.hmap + +## App packaging *.ipa +*.dSYM.zip +*.dSYM ## Playgrounds timeline.xctimeline playground.xcworkspace # Swift Package Manager -# # Add this line if you want to avoid checking in source code from Swift Package Manager dependencies. # Packages/ +# Package.pins +# Package.resolved +# *.xcodeproj +# Xcode automatically generates this directory with a .xcworkspacedata file and xcuserdata +# hence it is not needed unless you have added a package configuration file to your project +# .swiftpm + .build/ # CocoaPods -# # We recommend against adding the Pods directory to your .gitignore. However # you should judge for yourself, the pros and cons are mentioned at: # https://guides.cocoapods.org/using/using-cocoapods.html#should-i-check-the-pods-directory-into-source-control -# # Pods/ +# Add this line if you want to avoid checking in source code from the Xcode workspace +# *.xcworkspace # Carthage -# # Add this line if you want to avoid checking in source code from Carthage dependencies. # Carthage/Checkouts -Carthage/Build +Carthage/Build/ + +# Add this lines if you are using Accio dependency management (Deprecated since Xcode 12) +# Dependencies/ +# .accio/ # fastlane -# -# It is recommended to not store the screenshots in the git repo. Instead, use fastlane to re-generate the -# screenshots whenever they are needed. +# It is recommended to not store the screenshots in the git repo. +# Instead, use fastlane to re-generate the screenshots whenever they are needed. # For more information about the recommended setup visit: -# https://github.com/fastlane/fastlane/blob/master/docs/Gitignore.md +# https://docs.fastlane.tools/best-practices/source-control/#source-control fastlane/report.xml -fastlane/screenshots +fastlane/Preview.html +fastlane/screenshots/**/*.png +fastlane/test_output + +# Code Injection +# After new code Injection tools there's a generated folder /iOSInjectionProject +# https://github.com/johnno1962/injectionforxcode + +iOSInjectionProject/ + +### Xcode ### +# Xcode +# gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore + + + + +## Gcc Patch +/*.gcno + +### Xcode Patch ### +*.xcodeproj/* +!*.xcodeproj/project.pbxproj +!*.xcodeproj/xcshareddata/ +!*.xcworkspace/contents.xcworkspacedata +**/xcshareddata/WorkspaceSettings.xcsettings + +# End of https://www.toptal.com/developers/gitignore/api/swift,xcode diff --git a/samples/client/petstore/swift5/default/.openapi-generator/VERSION b/samples/client/petstore/swift5/default/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/client/petstore/swift5/default/.openapi-generator/VERSION +++ b/samples/client/petstore/swift5/default/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/client/petstore/swift5/default/Cartfile b/samples/client/petstore/swift5/default/Cartfile index 84aaa61ef2d..a6a6bcacb1d 100644 --- a/samples/client/petstore/swift5/default/Cartfile +++ b/samples/client/petstore/swift5/default/Cartfile @@ -1,2 +1,2 @@ -github "Flight-School/AnyCodable" ~> 0.4.0 +github "Flight-School/AnyCodable" ~> 0.6.1 diff --git a/samples/client/petstore/swift5/default/Package.resolved b/samples/client/petstore/swift5/default/Package.resolved index 85bb93ced12..79610c3b3b3 100644 --- a/samples/client/petstore/swift5/default/Package.resolved +++ b/samples/client/petstore/swift5/default/Package.resolved @@ -6,8 +6,8 @@ "repositoryURL": "https://github.com/Flight-School/AnyCodable", "state": { "branch": null, - "revision": "38b05fc9f86501ef8018aa90cf3d83bd97f74067", - "version": "0.4.0" + "revision": "69261f239f0fffaf51495dadc4f8483fbfe97025", + "version": "0.6.1" } } ] diff --git a/samples/client/petstore/swift5/default/Package.swift b/samples/client/petstore/swift5/default/Package.swift index b724838fe8d..87bb775fb72 100644 --- a/samples/client/petstore/swift5/default/Package.swift +++ b/samples/client/petstore/swift5/default/Package.swift @@ -19,7 +19,7 @@ let package = Package( ], dependencies: [ // Dependencies declare other packages that this package depends on. - .package(url: "https://github.com/Flight-School/AnyCodable", .exact("0.4.0")), + .package(url: "https://github.com/Flight-School/AnyCodable", from: "0.6.1"), ], targets: [ // Targets are the basic building blocks of a package. A target can define a module or a test suite. diff --git a/samples/client/petstore/swift5/default/PetstoreClient.podspec b/samples/client/petstore/swift5/default/PetstoreClient.podspec index de06558efbd..0e6bf7ec024 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient.podspec +++ b/samples/client/petstore/swift5/default/PetstoreClient.podspec @@ -11,5 +11,5 @@ Pod::Spec.new do |s| s.homepage = 'https://github.com/openapitools/openapi-generator' s.summary = 'PetstoreClient' s.source_files = 'PetstoreClient/Classes/**/*.swift' - s.dependency 'AnyCodable-FlightSchool', '~> 0.4.0' + s.dependency 'AnyCodable-FlightSchool', '~> 0.6.1' end diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/APIs.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/APIs.swift index dbdab491ff7..941c61b713a 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/APIs.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/APIs.swift @@ -6,10 +6,13 @@ import Foundation -open class PetstoreClientAPI { +@available(*, deprecated, renamed: "PetstoreClient") +public typealias PetstoreClientAPI = PetstoreClient + +open class PetstoreClient { public static var basePath = "http://petstore.swagger.io:80/v2" - public static var credential: URLCredential? public static var customHeaders: [String: String] = [:] + public static var credential: URLCredential? public static var requestBuilderFactory: RequestBuilderFactory = URLSessionRequestBuilderFactory() public static var apiResponseQueue: DispatchQueue = .main } @@ -32,7 +35,7 @@ open class RequestBuilder { self.parameters = parameters self.headers = headers - addHeaders(PetstoreClientAPI.customHeaders) + addHeaders(PetstoreClient.customHeaders) } open func addHeaders(_ aHeaders: [String: String]) { @@ -41,7 +44,7 @@ open class RequestBuilder { } } - open func execute(_ apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, _ completion: @escaping (_ result: Swift.Result, Error>) -> Void) { } + open func execute(_ apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, _ completion: @escaping (_ result: Swift.Result, Error>) -> Void) { } public func addHeader(name: String, value: String) -> Self { if !value.isEmpty { @@ -51,7 +54,7 @@ open class RequestBuilder { } open func addCredential() -> Self { - credential = PetstoreClientAPI.credential + credential = PetstoreClient.credential return self } } 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 72b89640eeb..ac9dd9b74f2 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 @@ -6,8 +6,12 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif open class AnotherFakeAPI { + /** To test special tags @@ -15,7 +19,7 @@ open class AnotherFakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func call123testSpecialTags(body: Client, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Client?, _ error: Error?) -> Void)) { + open class func call123testSpecialTags(body: Client, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Client?, _ error: Error?) -> Void)) { call123testSpecialTagsWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -34,21 +38,20 @@ open class AnotherFakeAPI { - returns: RequestBuilder */ open class func call123testSpecialTagsWithRequestBuilder(body: Client) -> RequestBuilder { - let path = "/another-fake/dummy" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/another-fake/dummy" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "PATCH", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "PATCH", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } - } 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 6d02c24d05f..aaff9fe6752 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 @@ -6,8 +6,12 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif open class FakeAPI { + /** creates an XmlItem @@ -15,7 +19,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func createXmlItem(xmlItem: XmlItem, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func createXmlItem(xmlItem: XmlItem, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { createXmlItemWithRequestBuilder(xmlItem: xmlItem).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -34,21 +38,21 @@ open class FakeAPI { - returns: RequestBuilder */ open class func createXmlItemWithRequestBuilder(xmlItem: XmlItem) -> RequestBuilder { - let path = "/fake/create_xml_item" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: xmlItem) + let localVariablePath = "/fake/create_xml_item" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: xmlItem) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -57,7 +61,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func fakeOuterBooleanSerialize(body: Bool? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Bool?, _ error: Error?) -> Void)) { + open class func fakeOuterBooleanSerialize(body: Bool? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Bool?, _ error: Error?) -> Void)) { fakeOuterBooleanSerializeWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -75,21 +79,21 @@ open class FakeAPI { - returns: RequestBuilder */ open class func fakeOuterBooleanSerializeWithRequestBuilder(body: Bool? = nil) -> RequestBuilder { - let path = "/fake/outer/boolean" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/fake/outer/boolean" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -98,7 +102,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func fakeOuterCompositeSerialize(body: OuterComposite? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: OuterComposite?, _ error: Error?) -> Void)) { + open class func fakeOuterCompositeSerialize(body: OuterComposite? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: OuterComposite?, _ error: Error?) -> Void)) { fakeOuterCompositeSerializeWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -116,21 +120,21 @@ open class FakeAPI { - returns: RequestBuilder */ open class func fakeOuterCompositeSerializeWithRequestBuilder(body: OuterComposite? = nil) -> RequestBuilder { - let path = "/fake/outer/composite" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/fake/outer/composite" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -139,7 +143,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func fakeOuterNumberSerialize(body: Double? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Double?, _ error: Error?) -> Void)) { + open class func fakeOuterNumberSerialize(body: Double? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Double?, _ error: Error?) -> Void)) { fakeOuterNumberSerializeWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -157,21 +161,21 @@ open class FakeAPI { - returns: RequestBuilder */ open class func fakeOuterNumberSerializeWithRequestBuilder(body: Double? = nil) -> RequestBuilder { - let path = "/fake/outer/number" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/fake/outer/number" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -180,7 +184,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func fakeOuterStringSerialize(body: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: String?, _ error: Error?) -> Void)) { + open class func fakeOuterStringSerialize(body: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: String?, _ error: Error?) -> Void)) { fakeOuterStringSerializeWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -198,21 +202,21 @@ open class FakeAPI { - returns: RequestBuilder */ open class func fakeOuterStringSerializeWithRequestBuilder(body: String? = nil) -> RequestBuilder { - let path = "/fake/outer/string" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/fake/outer/string" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -221,7 +225,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func testBodyWithFileSchema(body: FileSchemaTestClass, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func testBodyWithFileSchema(body: FileSchemaTestClass, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { testBodyWithFileSchemaWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -239,21 +243,21 @@ open class FakeAPI { - returns: RequestBuilder */ open class func testBodyWithFileSchemaWithRequestBuilder(body: FileSchemaTestClass) -> RequestBuilder { - let path = "/fake/body-with-file-schema" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/fake/body-with-file-schema" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "PUT", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -263,7 +267,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func testBodyWithQueryParams(query: String, body: User, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func testBodyWithQueryParams(query: String, body: User, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { testBodyWithQueryParamsWithRequestBuilder(query: query, body: body).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -281,24 +285,24 @@ open class FakeAPI { - returns: RequestBuilder */ open class func testBodyWithQueryParamsWithRequestBuilder(query: String, body: User) -> RequestBuilder { - let path = "/fake/body-with-query-params" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/fake/body-with-query-params" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - var urlComponents = URLComponents(string: URLString) - urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ + var localVariableUrlComponents = URLComponents(string: localVariableURLString) + localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ "query": query.encodeToJSON(), ]) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "PUT", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -308,7 +312,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func testClientModel(body: Client, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Client?, _ error: Error?) -> Void)) { + open class func testClientModel(body: Client, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Client?, _ error: Error?) -> Void)) { testClientModelWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -327,21 +331,21 @@ open class FakeAPI { - returns: RequestBuilder */ open class func testClientModelWithRequestBuilder(body: Client) -> RequestBuilder { - let path = "/fake" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/fake" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "PATCH", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "PATCH", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -364,7 +368,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func testEndpointParameters(number: Double, double: Double, patternWithoutDelimiter: String, byte: Data, integer: Int? = nil, int32: Int? = nil, int64: Int64? = nil, float: Float? = nil, string: String? = nil, binary: URL? = nil, date: Date? = nil, dateTime: Date? = nil, password: String? = nil, callback: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func testEndpointParameters(number: Double, double: Double, patternWithoutDelimiter: String, byte: Data, integer: Int? = nil, int32: Int? = nil, int64: Int64? = nil, float: Float? = nil, string: String? = nil, binary: URL? = nil, date: Date? = nil, dateTime: Date? = nil, password: String? = nil, callback: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { testEndpointParametersWithRequestBuilder(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(apiResponseQueue) { result -> Void in switch result { case .success: @@ -399,9 +403,9 @@ open class FakeAPI { - returns: RequestBuilder */ open class func testEndpointParametersWithRequestBuilder(number: Double, double: Double, patternWithoutDelimiter: String, byte: Data, integer: Int? = nil, int32: Int? = nil, int64: Int64? = nil, float: Float? = nil, string: String? = nil, binary: URL? = nil, date: Date? = nil, dateTime: Date? = nil, password: String? = nil, callback: String? = nil) -> RequestBuilder { - let path = "/fake" - let URLString = PetstoreClientAPI.basePath + path - let formParams: [String: Any?] = [ + let localVariablePath = "/fake" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableFormParams: [String: Any?] = [ "integer": integer?.encodeToJSON(), "int32": int32?.encodeToJSON(), "int64": int64?.encodeToJSON(), @@ -418,20 +422,20 @@ open class FakeAPI { "callback": callback?.encodeToJSON(), ] - let nonNullParameters = APIHelper.rejectNil(formParams) - let parameters = APIHelper.convertBoolToString(nonNullParameters) + let localVariableNonNullParameters = APIHelper.rejectNil(localVariableFormParams) + let localVariableParameters = APIHelper.convertBoolToString(localVariableNonNullParameters) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ "Content-Type": "application/x-www-form-urlencoded", ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -515,7 +519,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func testEnumParameters(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func testEnumParameters(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { testEnumParametersWithRequestBuilder(enumHeaderStringArray: enumHeaderStringArray, enumHeaderString: enumHeaderString, enumQueryStringArray: enumQueryStringArray, enumQueryString: enumQueryString, enumQueryInteger: enumQueryInteger, enumQueryDouble: enumQueryDouble, enumFormStringArray: enumFormStringArray, enumFormString: enumFormString).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -541,35 +545,35 @@ open class FakeAPI { - returns: RequestBuilder */ open class func testEnumParametersWithRequestBuilder(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil) -> RequestBuilder { - let path = "/fake" - let URLString = PetstoreClientAPI.basePath + path - let formParams: [String: Any?] = [ + let localVariablePath = "/fake" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableFormParams: [String: Any?] = [ "enum_form_string_array": enumFormStringArray?.encodeToJSON(), "enum_form_string": enumFormString?.encodeToJSON(), ] - let nonNullParameters = APIHelper.rejectNil(formParams) - let parameters = APIHelper.convertBoolToString(nonNullParameters) + let localVariableNonNullParameters = APIHelper.rejectNil(localVariableFormParams) + let localVariableParameters = APIHelper.convertBoolToString(localVariableNonNullParameters) - var urlComponents = URLComponents(string: URLString) - urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ + var localVariableUrlComponents = URLComponents(string: localVariableURLString) + localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ "enum_query_string_array": enumQueryStringArray?.encodeToJSON(), "enum_query_string": enumQueryString?.encodeToJSON(), "enum_query_integer": enumQueryInteger?.encodeToJSON(), "enum_query_double": enumQueryDouble?.encodeToJSON(), ]) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ "Content-Type": "application/x-www-form-urlencoded", "enum_header_string_array": enumHeaderStringArray?.encodeToJSON(), "enum_header_string": enumHeaderString?.encodeToJSON(), ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -584,7 +588,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func testGroupParameters(requiredStringGroup: Int, requiredBooleanGroup: Bool, requiredInt64Group: Int64, stringGroup: Int? = nil, booleanGroup: Bool? = nil, int64Group: Int64? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func testGroupParameters(requiredStringGroup: Int, requiredBooleanGroup: Bool, requiredInt64Group: Int64, stringGroup: Int? = nil, booleanGroup: Bool? = nil, int64Group: Int64? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { testGroupParametersWithRequestBuilder(requiredStringGroup: requiredStringGroup, requiredBooleanGroup: requiredBooleanGroup, requiredInt64Group: requiredInt64Group, stringGroup: stringGroup, booleanGroup: booleanGroup, int64Group: int64Group).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -608,28 +612,28 @@ open class FakeAPI { - returns: RequestBuilder */ open class func testGroupParametersWithRequestBuilder(requiredStringGroup: Int, requiredBooleanGroup: Bool, requiredInt64Group: Int64, stringGroup: Int? = nil, booleanGroup: Bool? = nil, int64Group: Int64? = nil) -> RequestBuilder { - let path = "/fake" - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + let localVariablePath = "/fake" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - var urlComponents = URLComponents(string: URLString) - urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ + var localVariableUrlComponents = URLComponents(string: localVariableURLString) + localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ "required_string_group": requiredStringGroup.encodeToJSON(), "required_int64_group": requiredInt64Group.encodeToJSON(), "string_group": stringGroup?.encodeToJSON(), "int64_group": int64Group?.encodeToJSON(), ]) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ "required_boolean_group": requiredBooleanGroup.encodeToJSON(), "boolean_group": booleanGroup?.encodeToJSON(), ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "DELETE", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -639,7 +643,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func testInlineAdditionalProperties(param: [String: String], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func testInlineAdditionalProperties(param: [String: String], apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { testInlineAdditionalPropertiesWithRequestBuilder(param: param).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -657,21 +661,21 @@ open class FakeAPI { - returns: RequestBuilder */ open class func testInlineAdditionalPropertiesWithRequestBuilder(param: [String: String]) -> RequestBuilder { - let path = "/fake/inline-additionalProperties" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: param) + let localVariablePath = "/fake/inline-additionalProperties" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: param) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -682,7 +686,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func testJsonFormData(param: String, param2: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func testJsonFormData(param: String, param2: String, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { testJsonFormDataWithRequestBuilder(param: param, param2: param2).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -701,27 +705,27 @@ open class FakeAPI { - returns: RequestBuilder */ open class func testJsonFormDataWithRequestBuilder(param: String, param2: String) -> RequestBuilder { - let path = "/fake/jsonFormData" - let URLString = PetstoreClientAPI.basePath + path - let formParams: [String: Any?] = [ + let localVariablePath = "/fake/jsonFormData" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableFormParams: [String: Any?] = [ "param": param.encodeToJSON(), "param2": param2.encodeToJSON(), ] - let nonNullParameters = APIHelper.rejectNil(formParams) - let parameters = APIHelper.convertBoolToString(nonNullParameters) + let localVariableNonNullParameters = APIHelper.rejectNil(localVariableFormParams) + let localVariableParameters = APIHelper.convertBoolToString(localVariableNonNullParameters) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ "Content-Type": "application/x-www-form-urlencoded", ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -734,7 +738,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func testQueryParameterCollectionFormat(pipe: [String], ioutil: [String], http: [String], url: [String], context: [String], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func testQueryParameterCollectionFormat(pipe: [String], ioutil: [String], http: [String], url: [String], context: [String], apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { testQueryParameterCollectionFormatWithRequestBuilder(pipe: pipe, ioutil: ioutil, http: http, url: url, context: context).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -756,12 +760,12 @@ open class FakeAPI { - returns: RequestBuilder */ open class func testQueryParameterCollectionFormatWithRequestBuilder(pipe: [String], ioutil: [String], http: [String], url: [String], context: [String]) -> RequestBuilder { - let path = "/fake/test-query-paramters" - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + let localVariablePath = "/fake/test-query-paramters" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - var urlComponents = URLComponents(string: URLString) - urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ + var localVariableUrlComponents = URLComponents(string: localVariableURLString) + localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ "pipe": pipe.encodeToJSON(), "ioutil": ioutil.encodeToJSON(), "http": http.encodeToJSON(), @@ -769,15 +773,14 @@ open class FakeAPI { "context": context.encodeToJSON(), ]) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "PUT", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } - } 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 d4d65166496..a6ca6c66b51 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 @@ -6,8 +6,12 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif open class FakeClassnameTags123API { + /** To test class name in snake case @@ -15,7 +19,7 @@ open class FakeClassnameTags123API { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func testClassname(body: Client, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Client?, _ error: Error?) -> Void)) { + open class func testClassname(body: Client, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Client?, _ error: Error?) -> Void)) { testClassnameWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -37,21 +41,20 @@ open class FakeClassnameTags123API { - returns: RequestBuilder */ open class func testClassnameWithRequestBuilder(body: Client) -> RequestBuilder { - let path = "/fake_classname_test" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/fake_classname_test" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "PATCH", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "PATCH", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } - } 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 5c220c11bb5..9912bf9a295 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 @@ -6,8 +6,12 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif open class PetAPI { + /** Add a new pet to the store @@ -15,7 +19,7 @@ open class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func addPet(body: Pet, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func addPet(body: Pet, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { addPetWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -36,21 +40,21 @@ open class PetAPI { - returns: RequestBuilder */ open class func addPetWithRequestBuilder(body: Pet) -> RequestBuilder { - let path = "/pet" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/pet" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -61,7 +65,7 @@ open class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func deletePet(petId: Int64, apiKey: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func deletePet(petId: Int64, apiKey: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { deletePetWithRequestBuilder(petId: petId, apiKey: apiKey).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -83,24 +87,24 @@ open class PetAPI { - returns: RequestBuilder */ open class func deletePetWithRequestBuilder(petId: Int64, apiKey: String? = nil) -> RequestBuilder { - var path = "/pet/{petId}" + var localVariablePath = "/pet/{petId}" let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))" let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" - path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + localVariablePath = localVariablePath.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ "api_key": apiKey?.encodeToJSON(), ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "DELETE", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -119,7 +123,7 @@ open class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func findPetsByStatus(status: [String], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: [Pet]?, _ error: Error?) -> Void)) { + open class func findPetsByStatus(status: [String], apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: [Pet]?, _ error: Error?) -> Void)) { findPetsByStatusWithRequestBuilder(status: status).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -141,24 +145,24 @@ open class PetAPI { - returns: RequestBuilder<[Pet]> */ open class func findPetsByStatusWithRequestBuilder(status: [String]) -> RequestBuilder<[Pet]> { - let path = "/pet/findByStatus" - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + let localVariablePath = "/pet/findByStatus" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - var urlComponents = URLComponents(string: URLString) - urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ + var localVariableUrlComponents = URLComponents(string: localVariableURLString) + localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ "status": status.encodeToJSON(), ]) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -169,7 +173,7 @@ open class PetAPI { - parameter completion: completion handler to receive the data and the error objects */ @available(*, deprecated, message: "This operation is deprecated.") - open class func findPetsByTags(tags: Set, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Set?, _ error: Error?) -> Void)) { + open class func findPetsByTags(tags: Set, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Set?, _ error: Error?) -> Void)) { findPetsByTagsWithRequestBuilder(tags: tags).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -192,24 +196,24 @@ open class PetAPI { */ @available(*, deprecated, message: "This operation is deprecated.") open class func findPetsByTagsWithRequestBuilder(tags: Set) -> RequestBuilder> { - let path = "/pet/findByTags" - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + let localVariablePath = "/pet/findByTags" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - var urlComponents = URLComponents(string: URLString) - urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ + var localVariableUrlComponents = URLComponents(string: localVariableURLString) + localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ "tags": tags.encodeToJSON(), ]) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder>.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -219,7 +223,7 @@ open class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func getPetById(petId: Int64, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Pet?, _ error: Error?) -> Void)) { + open class func getPetById(petId: Int64, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Pet?, _ error: Error?) -> Void)) { getPetByIdWithRequestBuilder(petId: petId).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -241,24 +245,24 @@ open class PetAPI { - returns: RequestBuilder */ open class func getPetByIdWithRequestBuilder(petId: Int64) -> RequestBuilder { - var path = "/pet/{petId}" + var localVariablePath = "/pet/{petId}" let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))" let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" - path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + localVariablePath = localVariablePath.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -268,7 +272,7 @@ open class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func updatePet(body: Pet, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func updatePet(body: Pet, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { updatePetWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -289,21 +293,21 @@ open class PetAPI { - returns: RequestBuilder */ open class func updatePetWithRequestBuilder(body: Pet) -> RequestBuilder { - let path = "/pet" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/pet" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "PUT", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -315,7 +319,7 @@ open class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func updatePetWithForm(petId: Int64, name: String? = nil, status: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func updatePetWithForm(petId: Int64, name: String? = nil, status: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { updatePetWithFormWithRequestBuilder(petId: petId, name: name, status: status).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -338,30 +342,30 @@ open class PetAPI { - returns: RequestBuilder */ open class func updatePetWithFormWithRequestBuilder(petId: Int64, name: String? = nil, status: String? = nil) -> RequestBuilder { - var path = "/pet/{petId}" + var localVariablePath = "/pet/{petId}" let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))" let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" - path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path - let formParams: [String: Any?] = [ + localVariablePath = localVariablePath.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableFormParams: [String: Any?] = [ "name": name?.encodeToJSON(), "status": status?.encodeToJSON(), ] - let nonNullParameters = APIHelper.rejectNil(formParams) - let parameters = APIHelper.convertBoolToString(nonNullParameters) + let localVariableNonNullParameters = APIHelper.rejectNil(localVariableFormParams) + let localVariableParameters = APIHelper.convertBoolToString(localVariableNonNullParameters) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ "Content-Type": "application/x-www-form-urlencoded", ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -373,7 +377,7 @@ open class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func uploadFile(petId: Int64, additionalMetadata: String? = nil, file: URL? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: ApiResponse?, _ error: Error?) -> Void)) { + open class func uploadFile(petId: Int64, additionalMetadata: String? = nil, file: URL? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: ApiResponse?, _ error: Error?) -> Void)) { uploadFileWithRequestBuilder(petId: petId, additionalMetadata: additionalMetadata, file: file).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -396,30 +400,30 @@ open class PetAPI { - returns: RequestBuilder */ open class func uploadFileWithRequestBuilder(petId: Int64, additionalMetadata: String? = nil, file: URL? = nil) -> RequestBuilder { - var path = "/pet/{petId}/uploadImage" + var localVariablePath = "/pet/{petId}/uploadImage" let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))" let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" - path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path - let formParams: [String: Any?] = [ + localVariablePath = localVariablePath.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableFormParams: [String: Any?] = [ "additionalMetadata": additionalMetadata?.encodeToJSON(), "file": file?.encodeToJSON(), ] - let nonNullParameters = APIHelper.rejectNil(formParams) - let parameters = APIHelper.convertBoolToString(nonNullParameters) + let localVariableNonNullParameters = APIHelper.rejectNil(localVariableFormParams) + let localVariableParameters = APIHelper.convertBoolToString(localVariableNonNullParameters) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ "Content-Type": "multipart/form-data", ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -431,7 +435,7 @@ open class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func uploadFileWithRequiredFile(petId: Int64, requiredFile: URL, additionalMetadata: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: ApiResponse?, _ error: Error?) -> Void)) { + open class func uploadFileWithRequiredFile(petId: Int64, requiredFile: URL, additionalMetadata: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: ApiResponse?, _ error: Error?) -> Void)) { uploadFileWithRequiredFileWithRequestBuilder(petId: petId, requiredFile: requiredFile, additionalMetadata: additionalMetadata).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -454,30 +458,29 @@ open class PetAPI { - returns: RequestBuilder */ open class func uploadFileWithRequiredFileWithRequestBuilder(petId: Int64, requiredFile: URL, additionalMetadata: String? = nil) -> RequestBuilder { - var path = "/fake/{petId}/uploadImageWithRequiredFile" + var localVariablePath = "/fake/{petId}/uploadImageWithRequiredFile" let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))" let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" - path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path - let formParams: [String: Any?] = [ + localVariablePath = localVariablePath.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableFormParams: [String: Any?] = [ "additionalMetadata": additionalMetadata?.encodeToJSON(), "requiredFile": requiredFile.encodeToJSON(), ] - let nonNullParameters = APIHelper.rejectNil(formParams) - let parameters = APIHelper.convertBoolToString(nonNullParameters) + let localVariableNonNullParameters = APIHelper.rejectNil(localVariableFormParams) + let localVariableParameters = APIHelper.convertBoolToString(localVariableNonNullParameters) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ "Content-Type": "multipart/form-data", ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } - } diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift index 501f11f5f21..53c1fed1eb3 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift @@ -6,8 +6,12 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif open class StoreAPI { + /** Delete purchase order by ID @@ -15,7 +19,7 @@ open class StoreAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func deleteOrder(orderId: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func deleteOrder(orderId: String, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { deleteOrderWithRequestBuilder(orderId: orderId).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -34,24 +38,24 @@ open class StoreAPI { - returns: RequestBuilder */ open class func deleteOrderWithRequestBuilder(orderId: String) -> RequestBuilder { - var path = "/store/order/{order_id}" + var localVariablePath = "/store/order/{order_id}" let orderIdPreEscape = "\(APIHelper.mapValueToPathItem(orderId))" let orderIdPostEscape = orderIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" - path = path.replacingOccurrences(of: "{order_id}", with: orderIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + localVariablePath = localVariablePath.replacingOccurrences(of: "{order_id}", with: orderIdPostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "DELETE", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -60,7 +64,7 @@ open class StoreAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func getInventory(apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: [String: Int]?, _ error: Error?) -> Void)) { + open class func getInventory(apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: [String: Int]?, _ error: Error?) -> Void)) { getInventoryWithRequestBuilder().execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -81,21 +85,21 @@ open class StoreAPI { - returns: RequestBuilder<[String: Int]> */ open class func getInventoryWithRequestBuilder() -> RequestBuilder<[String: Int]> { - let path = "/store/inventory" - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + let localVariablePath = "/store/inventory" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder<[String: Int]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder<[String: Int]>.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -105,7 +109,7 @@ open class StoreAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func getOrderById(orderId: Int64, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Order?, _ error: Error?) -> Void)) { + open class func getOrderById(orderId: Int64, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Order?, _ error: Error?) -> Void)) { getOrderByIdWithRequestBuilder(orderId: orderId).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -124,24 +128,24 @@ open class StoreAPI { - returns: RequestBuilder */ open class func getOrderByIdWithRequestBuilder(orderId: Int64) -> RequestBuilder { - var path = "/store/order/{order_id}" + var localVariablePath = "/store/order/{order_id}" let orderIdPreEscape = "\(APIHelper.mapValueToPathItem(orderId))" let orderIdPostEscape = orderIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" - path = path.replacingOccurrences(of: "{order_id}", with: orderIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + localVariablePath = localVariablePath.replacingOccurrences(of: "{order_id}", with: orderIdPostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -151,7 +155,7 @@ open class StoreAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func placeOrder(body: Order, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Order?, _ error: Error?) -> Void)) { + open class func placeOrder(body: Order, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Order?, _ error: Error?) -> Void)) { placeOrderWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -169,21 +173,20 @@ open class StoreAPI { - returns: RequestBuilder */ open class func placeOrderWithRequestBuilder(body: Order) -> RequestBuilder { - let path = "/store/order" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/store/order" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } - } diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift index 254474014d3..c1e5691390e 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift @@ -6,8 +6,12 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif open class UserAPI { + /** Create user @@ -15,7 +19,7 @@ open class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func createUser(body: User, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func createUser(body: User, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { createUserWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -34,21 +38,21 @@ open class UserAPI { - returns: RequestBuilder */ open class func createUserWithRequestBuilder(body: User) -> RequestBuilder { - let path = "/user" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/user" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -58,7 +62,7 @@ open class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func createUsersWithArrayInput(body: [User], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func createUsersWithArrayInput(body: [User], apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { createUsersWithArrayInputWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -76,21 +80,21 @@ open class UserAPI { - returns: RequestBuilder */ open class func createUsersWithArrayInputWithRequestBuilder(body: [User]) -> RequestBuilder { - let path = "/user/createWithArray" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/user/createWithArray" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -100,7 +104,7 @@ open class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func createUsersWithListInput(body: [User], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func createUsersWithListInput(body: [User], apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { createUsersWithListInputWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -118,21 +122,21 @@ open class UserAPI { - returns: RequestBuilder */ open class func createUsersWithListInputWithRequestBuilder(body: [User]) -> RequestBuilder { - let path = "/user/createWithList" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/user/createWithList" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -142,7 +146,7 @@ open class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func deleteUser(username: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func deleteUser(username: String, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { deleteUserWithRequestBuilder(username: username).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -161,24 +165,24 @@ open class UserAPI { - returns: RequestBuilder */ open class func deleteUserWithRequestBuilder(username: String) -> RequestBuilder { - var path = "/user/{username}" + var localVariablePath = "/user/{username}" let usernamePreEscape = "\(APIHelper.mapValueToPathItem(username))" let usernamePostEscape = usernamePreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" - path = path.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + localVariablePath = localVariablePath.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "DELETE", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -188,7 +192,7 @@ open class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func getUserByName(username: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: User?, _ error: Error?) -> Void)) { + open class func getUserByName(username: String, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: User?, _ error: Error?) -> Void)) { getUserByNameWithRequestBuilder(username: username).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -206,24 +210,24 @@ open class UserAPI { - returns: RequestBuilder */ open class func getUserByNameWithRequestBuilder(username: String) -> RequestBuilder { - var path = "/user/{username}" + var localVariablePath = "/user/{username}" let usernamePreEscape = "\(APIHelper.mapValueToPathItem(username))" let usernamePostEscape = usernamePreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" - path = path.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + localVariablePath = localVariablePath.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -234,7 +238,7 @@ open class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func loginUser(username: String, password: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: String?, _ error: Error?) -> Void)) { + open class func loginUser(username: String, password: String, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: String?, _ error: Error?) -> Void)) { loginUserWithRequestBuilder(username: username, password: password).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -254,25 +258,25 @@ open class UserAPI { - returns: RequestBuilder */ open class func loginUserWithRequestBuilder(username: String, password: String) -> RequestBuilder { - let path = "/user/login" - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + let localVariablePath = "/user/login" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - var urlComponents = URLComponents(string: URLString) - urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ + var localVariableUrlComponents = URLComponents(string: localVariableURLString) + localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ "username": username.encodeToJSON(), "password": password.encodeToJSON(), ]) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -281,7 +285,7 @@ open class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func logoutUser(apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func logoutUser(apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { logoutUserWithRequestBuilder().execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -298,21 +302,21 @@ open class UserAPI { - returns: RequestBuilder */ open class func logoutUserWithRequestBuilder() -> RequestBuilder { - let path = "/user/logout" - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + let localVariablePath = "/user/logout" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -323,7 +327,7 @@ open class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func updateUser(username: String, body: User, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func updateUser(username: String, body: User, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { updateUserWithRequestBuilder(username: username, body: body).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -343,24 +347,23 @@ open class UserAPI { - returns: RequestBuilder */ open class func updateUserWithRequestBuilder(username: String, body: User) -> RequestBuilder { - var path = "/user/{username}" + var localVariablePath = "/user/{username}" let usernamePreEscape = "\(APIHelper.mapValueToPathItem(username))" let usernamePostEscape = usernamePreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" - path = path.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + localVariablePath = localVariablePath.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "PUT", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } - } diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Configuration.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Configuration.swift index 18edabbed78..8fb05331889 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Configuration.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Configuration.swift @@ -7,6 +7,7 @@ import Foundation open class Configuration { + // This value is used to configure the date formatter that is used to serialize dates into JSON format. // You must set it prior to encoding any dates, and it will only be read once. @available(*, unavailable, message: "To set a different date format, use CodableHelper.dateFormatter instead.") diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Extensions.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Extensions.swift index 3aef2d1d6c5..e23035dde30 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Extensions.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Extensions.swift @@ -5,7 +5,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif extension Bool: JSONEncodable { func encodeToJSON() -> Any { return self as Any } @@ -184,44 +186,3 @@ extension HTTPURLResponse { return Array(200 ..< 300).contains(statusCode) } } - -extension AnyCodable: Hashable { - public func hash(into hasher: inout Hasher) { - switch value { - case let value as Bool: - hasher.combine(value) - case let value as Int: - hasher.combine(value) - case let value as Int8: - hasher.combine(value) - case let value as Int16: - hasher.combine(value) - case let value as Int32: - hasher.combine(value) - case let value as Int64: - hasher.combine(value) - case let value as UInt: - hasher.combine(value) - case let value as UInt8: - hasher.combine(value) - case let value as UInt16: - hasher.combine(value) - case let value as UInt32: - hasher.combine(value) - case let value as UInt64: - hasher.combine(value) - case let value as Float: - hasher.combine(value) - case let value as Double: - hasher.combine(value) - case let value as String: - hasher.combine(value) - case let value as [String: AnyCodable]: - hasher.combine(value) - case let value as [AnyCodable]: - hasher.combine(value) - default: - hasher.combine(0) - } - } -} \ No newline at end of file diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesAnyType.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesAnyType.swift index dd9fdef5c97..07dd0c38a1f 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesAnyType.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesAnyType.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct AdditionalPropertiesAnyType: Codable, Hashable { @@ -15,9 +17,11 @@ public struct AdditionalPropertiesAnyType: Codable, Hashable { public init(name: String? = nil) { self.name = name } + public enum CodingKeys: String, CodingKey, CaseIterable { case name } + public var additionalProperties: [String: AnyCodable] = [:] public subscript(key: String) -> AnyCodable? { @@ -45,13 +49,13 @@ public struct AdditionalPropertiesAnyType: Codable, Hashable { // Decodable protocol methods public init(from decoder: Decoder) throws { - let container = try decoder.container(keyedBy: String.self) + let container = try decoder.container(keyedBy: CodingKeys.self) - name = try container.decodeIfPresent(String.self, forKey: "name") + name = try container.decodeIfPresent(String.self, forKey: .name) var nonAdditionalPropertyKeys = Set() nonAdditionalPropertyKeys.insert("name") - additionalProperties = try container.decodeMap(AnyCodable.self, excludedKeys: nonAdditionalPropertyKeys) + let additionalPropertiesContainer = try decoder.container(keyedBy: String.self) + additionalProperties = try additionalPropertiesContainer.decodeMap(AnyCodable.self, excludedKeys: nonAdditionalPropertyKeys) } - - } + diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesArray.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesArray.swift index 03708059804..43a6d66cb59 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesArray.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesArray.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct AdditionalPropertiesArray: Codable, Hashable { @@ -15,9 +17,11 @@ public struct AdditionalPropertiesArray: Codable, Hashable { public init(name: String? = nil) { self.name = name } + public enum CodingKeys: String, CodingKey, CaseIterable { case name } + public var additionalProperties: [String: [AnyCodable]] = [:] public subscript(key: String) -> [AnyCodable]? { @@ -45,13 +49,13 @@ public struct AdditionalPropertiesArray: Codable, Hashable { // Decodable protocol methods public init(from decoder: Decoder) throws { - let container = try decoder.container(keyedBy: String.self) + let container = try decoder.container(keyedBy: CodingKeys.self) - name = try container.decodeIfPresent(String.self, forKey: "name") + name = try container.decodeIfPresent(String.self, forKey: .name) var nonAdditionalPropertyKeys = Set() nonAdditionalPropertyKeys.insert("name") - additionalProperties = try container.decodeMap([AnyCodable].self, excludedKeys: nonAdditionalPropertyKeys) + let additionalPropertiesContainer = try decoder.container(keyedBy: String.self) + additionalProperties = try additionalPropertiesContainer.decodeMap([AnyCodable].self, excludedKeys: nonAdditionalPropertyKeys) } - - } + diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesBoolean.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesBoolean.swift index 6a8bd72e6e5..a2a20a926a1 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesBoolean.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesBoolean.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct AdditionalPropertiesBoolean: Codable, Hashable { @@ -15,9 +17,11 @@ public struct AdditionalPropertiesBoolean: Codable, Hashable { public init(name: String? = nil) { self.name = name } + public enum CodingKeys: String, CodingKey, CaseIterable { case name } + public var additionalProperties: [String: Bool] = [:] public subscript(key: String) -> Bool? { @@ -45,13 +49,13 @@ public struct AdditionalPropertiesBoolean: Codable, Hashable { // Decodable protocol methods public init(from decoder: Decoder) throws { - let container = try decoder.container(keyedBy: String.self) + let container = try decoder.container(keyedBy: CodingKeys.self) - name = try container.decodeIfPresent(String.self, forKey: "name") + name = try container.decodeIfPresent(String.self, forKey: .name) var nonAdditionalPropertyKeys = Set() nonAdditionalPropertyKeys.insert("name") - additionalProperties = try container.decodeMap(Bool.self, excludedKeys: nonAdditionalPropertyKeys) + let additionalPropertiesContainer = try decoder.container(keyedBy: String.self) + additionalProperties = try additionalPropertiesContainer.decodeMap(Bool.self, excludedKeys: nonAdditionalPropertyKeys) } - - } + diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesClass.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesClass.swift index abe4a181890..eb6669c105a 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesClass.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesClass.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct AdditionalPropertiesClass: Codable, Hashable { @@ -35,6 +37,7 @@ public struct AdditionalPropertiesClass: Codable, Hashable { self.anytype2 = anytype2 self.anytype3 = anytype3 } + public enum CodingKeys: String, CodingKey, CaseIterable { case mapString = "map_string" case mapNumber = "map_number" @@ -65,7 +68,5 @@ public struct AdditionalPropertiesClass: Codable, Hashable { try container.encodeIfPresent(anytype2, forKey: .anytype2) try container.encodeIfPresent(anytype3, forKey: .anytype3) } - - - } + diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesInteger.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesInteger.swift index 90109260d02..0ccd9115bfd 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesInteger.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesInteger.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct AdditionalPropertiesInteger: Codable, Hashable { @@ -15,9 +17,11 @@ public struct AdditionalPropertiesInteger: Codable, Hashable { public init(name: String? = nil) { self.name = name } + public enum CodingKeys: String, CodingKey, CaseIterable { case name } + public var additionalProperties: [String: Int] = [:] public subscript(key: String) -> Int? { @@ -45,13 +49,13 @@ public struct AdditionalPropertiesInteger: Codable, Hashable { // Decodable protocol methods public init(from decoder: Decoder) throws { - let container = try decoder.container(keyedBy: String.self) + let container = try decoder.container(keyedBy: CodingKeys.self) - name = try container.decodeIfPresent(String.self, forKey: "name") + name = try container.decodeIfPresent(String.self, forKey: .name) var nonAdditionalPropertyKeys = Set() nonAdditionalPropertyKeys.insert("name") - additionalProperties = try container.decodeMap(Int.self, excludedKeys: nonAdditionalPropertyKeys) + let additionalPropertiesContainer = try decoder.container(keyedBy: String.self) + additionalProperties = try additionalPropertiesContainer.decodeMap(Int.self, excludedKeys: nonAdditionalPropertyKeys) } - - } + diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesNumber.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesNumber.swift index 2cae455cf24..06987825557 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesNumber.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesNumber.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct AdditionalPropertiesNumber: Codable, Hashable { @@ -15,9 +17,11 @@ public struct AdditionalPropertiesNumber: Codable, Hashable { public init(name: String? = nil) { self.name = name } + public enum CodingKeys: String, CodingKey, CaseIterable { case name } + public var additionalProperties: [String: Double] = [:] public subscript(key: String) -> Double? { @@ -45,13 +49,13 @@ public struct AdditionalPropertiesNumber: Codable, Hashable { // Decodable protocol methods public init(from decoder: Decoder) throws { - let container = try decoder.container(keyedBy: String.self) + let container = try decoder.container(keyedBy: CodingKeys.self) - name = try container.decodeIfPresent(String.self, forKey: "name") + name = try container.decodeIfPresent(String.self, forKey: .name) var nonAdditionalPropertyKeys = Set() nonAdditionalPropertyKeys.insert("name") - additionalProperties = try container.decodeMap(Double.self, excludedKeys: nonAdditionalPropertyKeys) + let additionalPropertiesContainer = try decoder.container(keyedBy: String.self) + additionalProperties = try additionalPropertiesContainer.decodeMap(Double.self, excludedKeys: nonAdditionalPropertyKeys) } - - } + diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesObject.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesObject.swift index 6f86abd07ab..848a0983a3f 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesObject.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesObject.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct AdditionalPropertiesObject: Codable, Hashable { @@ -15,9 +17,11 @@ public struct AdditionalPropertiesObject: Codable, Hashable { public init(name: String? = nil) { self.name = name } + public enum CodingKeys: String, CodingKey, CaseIterable { case name } + public var additionalProperties: [String: [String: AnyCodable]] = [:] public subscript(key: String) -> [String: AnyCodable]? { @@ -45,13 +49,13 @@ public struct AdditionalPropertiesObject: Codable, Hashable { // Decodable protocol methods public init(from decoder: Decoder) throws { - let container = try decoder.container(keyedBy: String.self) + let container = try decoder.container(keyedBy: CodingKeys.self) - name = try container.decodeIfPresent(String.self, forKey: "name") + name = try container.decodeIfPresent(String.self, forKey: .name) var nonAdditionalPropertyKeys = Set() nonAdditionalPropertyKeys.insert("name") - additionalProperties = try container.decodeMap([String: AnyCodable].self, excludedKeys: nonAdditionalPropertyKeys) + let additionalPropertiesContainer = try decoder.container(keyedBy: String.self) + additionalProperties = try additionalPropertiesContainer.decodeMap([String: AnyCodable].self, excludedKeys: nonAdditionalPropertyKeys) } - - } + diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesString.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesString.swift index b8b54f04b1b..7b5bd40f70f 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesString.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesString.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct AdditionalPropertiesString: Codable, Hashable { @@ -15,9 +17,11 @@ public struct AdditionalPropertiesString: Codable, Hashable { public init(name: String? = nil) { self.name = name } + public enum CodingKeys: String, CodingKey, CaseIterable { case name } + public var additionalProperties: [String: String] = [:] public subscript(key: String) -> String? { @@ -45,13 +49,13 @@ public struct AdditionalPropertiesString: Codable, Hashable { // Decodable protocol methods public init(from decoder: Decoder) throws { - let container = try decoder.container(keyedBy: String.self) + let container = try decoder.container(keyedBy: CodingKeys.self) - name = try container.decodeIfPresent(String.self, forKey: "name") + name = try container.decodeIfPresent(String.self, forKey: .name) var nonAdditionalPropertyKeys = Set() nonAdditionalPropertyKeys.insert("name") - additionalProperties = try container.decodeMap(String.self, excludedKeys: nonAdditionalPropertyKeys) + let additionalPropertiesContainer = try decoder.container(keyedBy: String.self) + additionalProperties = try additionalPropertiesContainer.decodeMap(String.self, excludedKeys: nonAdditionalPropertyKeys) } - - } + diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/Animal.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/Animal.swift index 0f825cf24d0..cdd4f5335b9 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/Animal.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/Animal.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct Animal: Codable, Hashable { @@ -17,6 +19,7 @@ public struct Animal: Codable, Hashable { self.className = className self.color = color } + public enum CodingKeys: String, CodingKey, CaseIterable { case className case color @@ -29,7 +32,5 @@ public struct Animal: Codable, Hashable { try container.encode(className, forKey: .className) try container.encodeIfPresent(color, forKey: .color) } - - - } + diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/AnimalFarm.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/AnimalFarm.swift index b20b894a1ad..a0b09cb9761 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/AnimalFarm.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/AnimalFarm.swift @@ -6,6 +6,8 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public typealias AnimalFarm = [Animal] diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift index 2b66af2dc94..c365505ab9d 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct ApiResponse: Codable, Hashable { @@ -19,6 +21,7 @@ public struct ApiResponse: Codable, Hashable { self.type = type self.message = message } + public enum CodingKeys: String, CodingKey, CaseIterable { case code case type @@ -33,7 +36,5 @@ public struct ApiResponse: Codable, Hashable { try container.encodeIfPresent(type, forKey: .type) try container.encodeIfPresent(message, forKey: .message) } - - - } + diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfArrayOfNumberOnly.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfArrayOfNumberOnly.swift index 06f0640475c..226f7456181 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfArrayOfNumberOnly.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfArrayOfNumberOnly.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct ArrayOfArrayOfNumberOnly: Codable, Hashable { @@ -15,6 +17,7 @@ public struct ArrayOfArrayOfNumberOnly: Codable, Hashable { public init(arrayArrayNumber: [[Double]]? = nil) { self.arrayArrayNumber = arrayArrayNumber } + public enum CodingKeys: String, CodingKey, CaseIterable { case arrayArrayNumber = "ArrayArrayNumber" } @@ -25,7 +28,5 @@ public struct ArrayOfArrayOfNumberOnly: Codable, Hashable { var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(arrayArrayNumber, forKey: .arrayArrayNumber) } - - - } + diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfNumberOnly.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfNumberOnly.swift index 8c50c7fa1e4..39831127871 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfNumberOnly.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfNumberOnly.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct ArrayOfNumberOnly: Codable, Hashable { @@ -15,6 +17,7 @@ public struct ArrayOfNumberOnly: Codable, Hashable { public init(arrayNumber: [Double]? = nil) { self.arrayNumber = arrayNumber } + public enum CodingKeys: String, CodingKey, CaseIterable { case arrayNumber = "ArrayNumber" } @@ -25,7 +28,5 @@ public struct ArrayOfNumberOnly: Codable, Hashable { var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(arrayNumber, forKey: .arrayNumber) } - - - } + diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/ArrayTest.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/ArrayTest.swift index 461ec7cd9ac..8865d76bef2 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/ArrayTest.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/ArrayTest.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct ArrayTest: Codable, Hashable { @@ -19,6 +21,7 @@ public struct ArrayTest: Codable, Hashable { self.arrayArrayOfInteger = arrayArrayOfInteger self.arrayArrayOfModel = arrayArrayOfModel } + public enum CodingKeys: String, CodingKey, CaseIterable { case arrayOfString = "array_of_string" case arrayArrayOfInteger = "array_array_of_integer" @@ -33,7 +36,5 @@ public struct ArrayTest: Codable, Hashable { try container.encodeIfPresent(arrayArrayOfInteger, forKey: .arrayArrayOfInteger) try container.encodeIfPresent(arrayArrayOfModel, forKey: .arrayArrayOfModel) } - - - } + diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/BigCat.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/BigCat.swift index 9c3f0f237a3..4ca3454f9bd 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/BigCat.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/BigCat.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct BigCat: Codable, Hashable { @@ -21,6 +23,7 @@ public struct BigCat: Codable, Hashable { public init(kind: Kind? = nil) { self.kind = kind } + public enum CodingKeys: String, CodingKey, CaseIterable { case kind } @@ -31,7 +34,5 @@ public struct BigCat: Codable, Hashable { var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(kind, forKey: .kind) } - - - } + diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/BigCatAllOf.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/BigCatAllOf.swift index 6b78ab7b42a..8c6a92c8b48 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/BigCatAllOf.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/BigCatAllOf.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct BigCatAllOf: Codable, Hashable { @@ -21,6 +23,7 @@ public struct BigCatAllOf: Codable, Hashable { public init(kind: Kind? = nil) { self.kind = kind } + public enum CodingKeys: String, CodingKey, CaseIterable { case kind } @@ -31,7 +34,5 @@ public struct BigCatAllOf: Codable, Hashable { var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(kind, forKey: .kind) } - - - } + diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/Capitalization.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/Capitalization.swift index fbe62983d5e..71cd93bce5f 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/Capitalization.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/Capitalization.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct Capitalization: Codable, Hashable { @@ -26,6 +28,7 @@ public struct Capitalization: Codable, Hashable { self.sCAETHFlowPoints = sCAETHFlowPoints self.ATT_NAME = ATT_NAME } + public enum CodingKeys: String, CodingKey, CaseIterable { case smallCamel case capitalCamel = "CapitalCamel" @@ -46,7 +49,5 @@ public struct Capitalization: Codable, Hashable { try container.encodeIfPresent(sCAETHFlowPoints, forKey: .sCAETHFlowPoints) try container.encodeIfPresent(ATT_NAME, forKey: .ATT_NAME) } - - - } + diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/Cat.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/Cat.swift index 7f3a86932f1..457e04bd475 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/Cat.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/Cat.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct Cat: Codable, Hashable { @@ -19,6 +21,7 @@ public struct Cat: Codable, Hashable { self.color = color self.declawed = declawed } + public enum CodingKeys: String, CodingKey, CaseIterable { case className case color @@ -33,7 +36,5 @@ public struct Cat: Codable, Hashable { try container.encodeIfPresent(color, forKey: .color) try container.encodeIfPresent(declawed, forKey: .declawed) } - - - } + diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/CatAllOf.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/CatAllOf.swift index 8df23954832..8caebb1c206 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/CatAllOf.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/CatAllOf.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct CatAllOf: Codable, Hashable { @@ -15,6 +17,7 @@ public struct CatAllOf: Codable, Hashable { public init(declawed: Bool? = nil) { self.declawed = declawed } + public enum CodingKeys: String, CodingKey, CaseIterable { case declawed } @@ -25,7 +28,5 @@ public struct CatAllOf: Codable, Hashable { var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(declawed, forKey: .declawed) } - - - } + diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/Category.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/Category.swift index 611a8a32e39..e880b792bbe 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/Category.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/Category.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct Category: Codable, Hashable { @@ -17,6 +19,7 @@ public struct Category: Codable, Hashable { self.id = id self.name = name } + public enum CodingKeys: String, CodingKey, CaseIterable { case id case name @@ -29,7 +32,5 @@ public struct Category: Codable, Hashable { try container.encodeIfPresent(id, forKey: .id) try container.encode(name, forKey: .name) } - - - } + diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/ClassModel.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/ClassModel.swift index 7269ddbef6f..16e69e560bd 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/ClassModel.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/ClassModel.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif /** Model for testing model with \"_class\" property */ public struct ClassModel: Codable, Hashable { @@ -16,6 +18,7 @@ public struct ClassModel: Codable, Hashable { public init(_class: String? = nil) { self._class = _class } + public enum CodingKeys: String, CodingKey, CaseIterable { case _class } @@ -26,7 +29,5 @@ public struct ClassModel: Codable, Hashable { var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(_class, forKey: ._class) } - - - } + diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/Client.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/Client.swift index 7d6eff2ffe1..60dbc5dc5c1 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/Client.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/Client.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct Client: Codable, Hashable { @@ -15,6 +17,7 @@ public struct Client: Codable, Hashable { public init(client: String? = nil) { self.client = client } + public enum CodingKeys: String, CodingKey, CaseIterable { case client } @@ -25,7 +28,5 @@ public struct Client: Codable, Hashable { var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(client, forKey: .client) } - - - } + diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/Dog.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/Dog.swift index b5f2bcea38a..658732a7f36 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/Dog.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/Dog.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct Dog: Codable, Hashable { @@ -19,6 +21,7 @@ public struct Dog: Codable, Hashable { self.color = color self.breed = breed } + public enum CodingKeys: String, CodingKey, CaseIterable { case className case color @@ -33,7 +36,5 @@ public struct Dog: Codable, Hashable { try container.encodeIfPresent(color, forKey: .color) try container.encodeIfPresent(breed, forKey: .breed) } - - - } + diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/DogAllOf.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/DogAllOf.swift index 1bfa23d7bc6..82b0dedf35b 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/DogAllOf.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/DogAllOf.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct DogAllOf: Codable, Hashable { @@ -15,6 +17,7 @@ public struct DogAllOf: Codable, Hashable { public init(breed: String? = nil) { self.breed = breed } + public enum CodingKeys: String, CodingKey, CaseIterable { case breed } @@ -25,7 +28,5 @@ public struct DogAllOf: Codable, Hashable { var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(breed, forKey: .breed) } - - - } + diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/EnumArrays.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/EnumArrays.swift index 73368c42143..1d8ce99539c 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/EnumArrays.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/EnumArrays.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct EnumArrays: Codable, Hashable { @@ -25,6 +27,7 @@ public struct EnumArrays: Codable, Hashable { self.justSymbol = justSymbol self.arrayEnum = arrayEnum } + public enum CodingKeys: String, CodingKey, CaseIterable { case justSymbol = "just_symbol" case arrayEnum = "array_enum" @@ -37,7 +40,5 @@ public struct EnumArrays: Codable, Hashable { try container.encodeIfPresent(justSymbol, forKey: .justSymbol) try container.encodeIfPresent(arrayEnum, forKey: .arrayEnum) } - - - } + diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/EnumClass.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/EnumClass.swift index ab01cf297f8..6ea2895aee5 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/EnumClass.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/EnumClass.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public enum EnumClass: String, Codable, CaseIterable { case abc = "_abc" diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/EnumTest.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/EnumTest.swift index 60a81bcac77..8c8bca49774 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/EnumTest.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/EnumTest.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct EnumTest: Codable, Hashable { @@ -41,6 +43,7 @@ public struct EnumTest: Codable, Hashable { self.enumNumber = enumNumber self.outerEnum = outerEnum } + public enum CodingKeys: String, CodingKey, CaseIterable { case enumString = "enum_string" case enumStringRequired = "enum_string_required" @@ -59,7 +62,5 @@ public struct EnumTest: Codable, Hashable { try container.encodeIfPresent(enumNumber, forKey: .enumNumber) try container.encodeIfPresent(outerEnum, forKey: .outerEnum) } - - - } + diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/File.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/File.swift index 90283656d1b..05dd5b1a825 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/File.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/File.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif /** Must be named `File` for test. */ public struct File: Codable, Hashable { @@ -17,6 +19,7 @@ public struct File: Codable, Hashable { public init(sourceURI: String? = nil) { self.sourceURI = sourceURI } + public enum CodingKeys: String, CodingKey, CaseIterable { case sourceURI } @@ -27,7 +30,5 @@ public struct File: Codable, Hashable { var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(sourceURI, forKey: .sourceURI) } - - - } + diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/FileSchemaTestClass.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/FileSchemaTestClass.swift index cff92673bbe..3ca66a31359 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/FileSchemaTestClass.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/FileSchemaTestClass.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct FileSchemaTestClass: Codable, Hashable { @@ -17,6 +19,7 @@ public struct FileSchemaTestClass: Codable, Hashable { self.file = file self.files = files } + public enum CodingKeys: String, CodingKey, CaseIterable { case file case files @@ -29,7 +32,5 @@ public struct FileSchemaTestClass: Codable, Hashable { try container.encodeIfPresent(file, forKey: .file) try container.encodeIfPresent(files, forKey: .files) } - - - } + diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/FormatTest.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/FormatTest.swift index ea348c3581e..5dccf04e1e1 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/FormatTest.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/FormatTest.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct FormatTest: Codable, Hashable { @@ -41,6 +43,7 @@ public struct FormatTest: Codable, Hashable { self.password = password self.bigDecimal = bigDecimal } + public enum CodingKeys: String, CodingKey, CaseIterable { case integer case int32 @@ -77,7 +80,5 @@ public struct FormatTest: Codable, Hashable { try container.encode(password, forKey: .password) try container.encodeIfPresent(bigDecimal, forKey: .bigDecimal) } - - - } + diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/HasOnlyReadOnly.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/HasOnlyReadOnly.swift index d7960f5c800..54ed8a723c6 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/HasOnlyReadOnly.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/HasOnlyReadOnly.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct HasOnlyReadOnly: Codable, Hashable { @@ -17,6 +19,7 @@ public struct HasOnlyReadOnly: Codable, Hashable { self.bar = bar self.foo = foo } + public enum CodingKeys: String, CodingKey, CaseIterable { case bar case foo @@ -29,7 +32,5 @@ public struct HasOnlyReadOnly: Codable, Hashable { try container.encodeIfPresent(bar, forKey: .bar) try container.encodeIfPresent(foo, forKey: .foo) } - - - } + diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/List.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/List.swift index c5d4f2cae56..67e3048469f 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/List.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/List.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct List: Codable, Hashable { @@ -15,6 +17,7 @@ public struct List: Codable, Hashable { public init(_123list: String? = nil) { self._123list = _123list } + public enum CodingKeys: String, CodingKey, CaseIterable { case _123list = "123-list" } @@ -25,7 +28,5 @@ public struct List: Codable, Hashable { var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(_123list, forKey: ._123list) } - - - } + diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/MapTest.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/MapTest.swift index b54bd01e5dc..1e728fcdf58 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/MapTest.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/MapTest.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct MapTest: Codable, Hashable { @@ -25,6 +27,7 @@ public struct MapTest: Codable, Hashable { self.directMap = directMap self.indirectMap = indirectMap } + public enum CodingKeys: String, CodingKey, CaseIterable { case mapMapOfString = "map_map_of_string" case mapOfEnumString = "map_of_enum_string" @@ -41,7 +44,5 @@ public struct MapTest: Codable, Hashable { try container.encodeIfPresent(directMap, forKey: .directMap) try container.encodeIfPresent(indirectMap, forKey: .indirectMap) } - - - } + diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/MixedPropertiesAndAdditionalPropertiesClass.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/MixedPropertiesAndAdditionalPropertiesClass.swift index c8f639ef43d..c79ca459217 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/MixedPropertiesAndAdditionalPropertiesClass.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/MixedPropertiesAndAdditionalPropertiesClass.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct MixedPropertiesAndAdditionalPropertiesClass: Codable, Hashable { @@ -19,6 +21,7 @@ public struct MixedPropertiesAndAdditionalPropertiesClass: Codable, Hashable { self.dateTime = dateTime self.map = map } + public enum CodingKeys: String, CodingKey, CaseIterable { case uuid case dateTime @@ -33,7 +36,5 @@ public struct MixedPropertiesAndAdditionalPropertiesClass: Codable, Hashable { try container.encodeIfPresent(dateTime, forKey: .dateTime) try container.encodeIfPresent(map, forKey: .map) } - - - } + diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/Model200Response.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/Model200Response.swift index 5368032f09b..23402143f71 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/Model200Response.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/Model200Response.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif /** Model for testing model name starting with number */ public struct Model200Response: Codable, Hashable { @@ -18,6 +20,7 @@ public struct Model200Response: Codable, Hashable { self.name = name self._class = _class } + public enum CodingKeys: String, CodingKey, CaseIterable { case name case _class = "class" @@ -30,7 +33,5 @@ public struct Model200Response: Codable, Hashable { try container.encodeIfPresent(name, forKey: .name) try container.encodeIfPresent(_class, forKey: ._class) } - - - } + diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/Name.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/Name.swift index 84a40e1c101..a28f46a33ce 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/Name.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/Name.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif /** Model for testing model name same as property name */ public struct Name: Codable, Hashable { @@ -22,6 +24,7 @@ public struct Name: Codable, Hashable { self.property = property self._123number = _123number } + public enum CodingKeys: String, CodingKey, CaseIterable { case name case snakeCase = "snake_case" @@ -38,7 +41,5 @@ public struct Name: Codable, Hashable { try container.encodeIfPresent(property, forKey: .property) try container.encodeIfPresent(_123number, forKey: ._123number) } - - - } + diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/NumberOnly.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/NumberOnly.swift index 710f41648f9..87ceb64bb97 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/NumberOnly.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/NumberOnly.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct NumberOnly: Codable, Hashable { @@ -15,6 +17,7 @@ public struct NumberOnly: Codable, Hashable { public init(justNumber: Double? = nil) { self.justNumber = justNumber } + public enum CodingKeys: String, CodingKey, CaseIterable { case justNumber = "JustNumber" } @@ -25,7 +28,5 @@ public struct NumberOnly: Codable, Hashable { var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(justNumber, forKey: .justNumber) } - - - } + 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 15726ab16a4..e2eeced4c57 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 @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct Order: Codable, Hashable { @@ -31,6 +33,7 @@ public struct Order: Codable, Hashable { self.status = status self.complete = complete } + public enum CodingKeys: String, CodingKey, CaseIterable { case id case petId @@ -51,7 +54,5 @@ public struct Order: Codable, Hashable { try container.encodeIfPresent(status, forKey: .status) try container.encodeIfPresent(complete, forKey: .complete) } - - - } + diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/OuterComposite.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/OuterComposite.swift index 36904afbd50..edeaccaeaa6 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/OuterComposite.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/OuterComposite.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct OuterComposite: Codable, Hashable { @@ -19,6 +21,7 @@ public struct OuterComposite: Codable, Hashable { self.myString = myString self.myBoolean = myBoolean } + public enum CodingKeys: String, CodingKey, CaseIterable { case myNumber = "my_number" case myString = "my_string" @@ -33,7 +36,5 @@ public struct OuterComposite: Codable, Hashable { try container.encodeIfPresent(myString, forKey: .myString) try container.encodeIfPresent(myBoolean, forKey: .myBoolean) } - - - } + 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 9bd6f3bef8f..76c34b3c2ce 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 @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public enum OuterEnum: String, Codable, CaseIterable { case placed = "placed" diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/Pet.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/Pet.swift index 03e81af5d05..f3a1bc92289 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/Pet.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/Pet.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct Pet: Codable, Hashable { @@ -31,6 +33,7 @@ public struct Pet: Codable, Hashable { self.tags = tags self.status = status } + public enum CodingKeys: String, CodingKey, CaseIterable { case id case category @@ -51,7 +54,5 @@ public struct Pet: Codable, Hashable { try container.encodeIfPresent(tags, forKey: .tags) try container.encodeIfPresent(status, forKey: .status) } - - - } + diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/ReadOnlyFirst.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/ReadOnlyFirst.swift index 38fb57af328..57ba3f577c8 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/ReadOnlyFirst.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/ReadOnlyFirst.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct ReadOnlyFirst: Codable, Hashable { @@ -17,6 +19,7 @@ public struct ReadOnlyFirst: Codable, Hashable { self.bar = bar self.baz = baz } + public enum CodingKeys: String, CodingKey, CaseIterable { case bar case baz @@ -29,7 +32,5 @@ public struct ReadOnlyFirst: Codable, Hashable { try container.encodeIfPresent(bar, forKey: .bar) try container.encodeIfPresent(baz, forKey: .baz) } - - - } + diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/Return.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/Return.swift index ed7e538a06d..afc2b51f8f3 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/Return.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/Return.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif /** Model for testing reserved words */ public struct Return: Codable, Hashable { @@ -16,6 +18,7 @@ public struct Return: Codable, Hashable { public init(_return: Int? = nil) { self._return = _return } + public enum CodingKeys: String, CodingKey, CaseIterable { case _return = "return" } @@ -26,7 +29,5 @@ public struct Return: Codable, Hashable { var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(_return, forKey: ._return) } - - - } + diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/SpecialModelName.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/SpecialModelName.swift index 18747e071bc..bfe9723f888 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/SpecialModelName.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/SpecialModelName.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct SpecialModelName: Codable, Hashable { @@ -15,6 +17,7 @@ public struct SpecialModelName: Codable, Hashable { public init(specialPropertyName: Int64? = nil) { self.specialPropertyName = specialPropertyName } + public enum CodingKeys: String, CodingKey, CaseIterable { case specialPropertyName = "$special[property.name]" } @@ -25,7 +28,5 @@ public struct SpecialModelName: Codable, Hashable { var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(specialPropertyName, forKey: .specialPropertyName) } - - - } + diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/StringBooleanMap.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/StringBooleanMap.swift index 0699c25ff7e..126c35c85a6 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/StringBooleanMap.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/StringBooleanMap.swift @@ -6,12 +6,16 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct StringBooleanMap: Codable, Hashable { + public enum CodingKeys: CodingKey, CaseIterable { } + public var additionalProperties: [String: Bool] = [:] public subscript(key: String) -> Bool? { @@ -38,11 +42,11 @@ public struct StringBooleanMap: Codable, Hashable { // Decodable protocol methods public init(from decoder: Decoder) throws { - let container = try decoder.container(keyedBy: String.self) + let container = try decoder.container(keyedBy: CodingKeys.self) var nonAdditionalPropertyKeys = Set() - additionalProperties = try container.decodeMap(Bool.self, excludedKeys: nonAdditionalPropertyKeys) + let additionalPropertiesContainer = try decoder.container(keyedBy: String.self) + additionalProperties = try additionalPropertiesContainer.decodeMap(Bool.self, excludedKeys: nonAdditionalPropertyKeys) } - - } + diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift index 11c5f7a750b..07b826264f3 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct Tag: Codable, Hashable { @@ -17,6 +19,7 @@ public struct Tag: Codable, Hashable { self.id = id self.name = name } + public enum CodingKeys: String, CodingKey, CaseIterable { case id case name @@ -29,7 +32,5 @@ public struct Tag: Codable, Hashable { try container.encodeIfPresent(id, forKey: .id) try container.encodeIfPresent(name, forKey: .name) } - - - } + diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderDefault.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderDefault.swift index 35b1a5833b9..e58eecd960f 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderDefault.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderDefault.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct TypeHolderDefault: Codable, Hashable { @@ -23,6 +25,7 @@ public struct TypeHolderDefault: Codable, Hashable { self.boolItem = boolItem self.arrayItem = arrayItem } + public enum CodingKeys: String, CodingKey, CaseIterable { case stringItem = "string_item" case numberItem = "number_item" @@ -41,7 +44,5 @@ public struct TypeHolderDefault: Codable, Hashable { try container.encode(boolItem, forKey: .boolItem) try container.encode(arrayItem, forKey: .arrayItem) } - - - } + diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderExample.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderExample.swift index 66dc3819f2a..23343c3c393 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderExample.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderExample.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct TypeHolderExample: Codable, Hashable { @@ -25,6 +27,7 @@ public struct TypeHolderExample: Codable, Hashable { self.boolItem = boolItem self.arrayItem = arrayItem } + public enum CodingKeys: String, CodingKey, CaseIterable { case stringItem = "string_item" case numberItem = "number_item" @@ -45,7 +48,5 @@ public struct TypeHolderExample: Codable, Hashable { try container.encode(boolItem, forKey: .boolItem) try container.encode(arrayItem, forKey: .arrayItem) } - - - } + diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/User.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/User.swift index 2bbc31806ff..7afe359ae40 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/User.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/User.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct User: Codable, Hashable { @@ -30,6 +32,7 @@ public struct User: Codable, Hashable { self.phone = phone self.userStatus = userStatus } + public enum CodingKeys: String, CodingKey, CaseIterable { case id case username @@ -54,7 +57,5 @@ public struct User: Codable, Hashable { try container.encodeIfPresent(phone, forKey: .phone) try container.encodeIfPresent(userStatus, forKey: .userStatus) } - - - } + diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/XmlItem.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/XmlItem.swift index daa3716aeca..ae43cd28692 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/XmlItem.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/XmlItem.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct XmlItem: Codable, Hashable { @@ -71,6 +73,7 @@ public struct XmlItem: Codable, Hashable { self.prefixNsArray = prefixNsArray self.prefixNsWrappedArray = prefixNsWrappedArray } + public enum CodingKeys: String, CodingKey, CaseIterable { case attributeString = "attribute_string" case attributeNumber = "attribute_number" @@ -137,7 +140,5 @@ public struct XmlItem: Codable, Hashable { try container.encodeIfPresent(prefixNsArray, forKey: .prefixNsArray) try container.encodeIfPresent(prefixNsWrappedArray, forKey: .prefixNsWrappedArray) } - - - } + 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 52b2071ec1a..41959190a26 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift @@ -93,14 +93,14 @@ open class URLSessionRequestBuilder: RequestBuilder { return modifiedRequest } - override open func execute(_ apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, _ completion: @escaping (_ result: Swift.Result, Error>) -> Void) { + override open func execute(_ apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, _ completion: @escaping (_ result: Swift.Result, Error>) -> Void) { let urlSessionId = UUID().uuidString // Create a new manager for each request to customize its request header let urlSession = createURLSession() urlSessionStore[urlSessionId] = urlSession guard let xMethod = HTTPMethod(rawValue: method) else { - fatalError("Unsuported Http method - \(method)") + fatalError("Unsupported Http method - \(method)") } let encoding: ParameterEncoding @@ -119,7 +119,7 @@ open class URLSessionRequestBuilder: RequestBuilder { } else if contentType == "application/x-www-form-urlencoded" { encoding = FormURLEncoding() } else { - fatalError("Unsuported Media Type - \(contentType)") + fatalError("Unsupported Media Type - \(contentType)") } } @@ -205,16 +205,18 @@ open class URLSessionRequestBuilder: RequestBuilder { } let fileManager = FileManager.default - let documentsDirectory = fileManager.urls(for: .documentDirectory, in: .userDomainMask)[0] + let cachesDirectory = fileManager.urls(for: .cachesDirectory, in: .userDomainMask)[0] let requestURL = try getURL(from: urlRequest) var requestPath = try getPath(from: requestURL) if let headerFileName = getFileName(fromContentDisposition: httpResponse.allHeaderFields["Content-Disposition"] as? String) { requestPath = requestPath.appending("/\(headerFileName)") + } else { + requestPath = requestPath.appending("/tmp.PetstoreClient.\(UUID().uuidString)") } - let filePath = documentsDirectory.appendingPathComponent(requestPath) + let filePath = cachesDirectory.appendingPathComponent(requestPath) let directoryPath = filePath.deletingLastPathComponent().path try fileManager.createDirectory(atPath: directoryPath, withIntermediateDirectories: true, attributes: nil) @@ -232,6 +234,10 @@ open class URLSessionRequestBuilder: RequestBuilder { completion(.success(Response(response: httpResponse, body: nil))) + case is Data.Type: + + completion(.success(Response(response: httpResponse, body: data as? T))) + default: completion(.success(Response(response: httpResponse, body: data as? T))) @@ -244,7 +250,7 @@ open class URLSessionRequestBuilder: RequestBuilder { for (key, value) in headers { httpHeaders[key] = value } - for (key, value) in PetstoreClientAPI.customHeaders { + for (key, value) in PetstoreClient.customHeaders { httpHeaders[key] = value } return httpHeaders @@ -328,6 +334,43 @@ open class URLSessionDecodableRequestBuilder: URLSessionRequestBui completion(.success(Response(response: httpResponse, body: body as? T))) + case is URL.Type: + do { + + guard error == nil else { + throw DownloadException.responseFailed + } + + guard let data = data else { + throw DownloadException.responseDataMissing + } + + let fileManager = FileManager.default + let cachesDirectory = fileManager.urls(for: .cachesDirectory, in: .userDomainMask)[0] + let requestURL = try getURL(from: urlRequest) + + var requestPath = try getPath(from: requestURL) + + if let headerFileName = getFileName(fromContentDisposition: httpResponse.allHeaderFields["Content-Disposition"] as? String) { + requestPath = requestPath.appending("/\(headerFileName)") + } else { + requestPath = requestPath.appending("/tmp.PetstoreClient.\(UUID().uuidString)") + } + + let filePath = cachesDirectory.appendingPathComponent(requestPath) + let directoryPath = filePath.deletingLastPathComponent().path + + try fileManager.createDirectory(atPath: directoryPath, withIntermediateDirectories: true, attributes: nil) + try data.write(to: filePath, options: .atomic) + + completion(.success(Response(response: httpResponse, body: filePath as? T))) + + } catch let requestParserError as DownloadException { + completion(.failure(ErrorResponse.error(400, data, response, requestParserError))) + } catch { + completion(.failure(ErrorResponse.error(400, data, response, error))) + } + case is Void.Type: completion(.success(Response(response: httpResponse, body: nil))) diff --git a/samples/client/petstore/swift5/default/SwaggerClientTests/.gitignore b/samples/client/petstore/swift5/default/SwaggerClientTests/.gitignore index 0269c2f56db..22029d2f644 100644 --- a/samples/client/petstore/swift5/default/SwaggerClientTests/.gitignore +++ b/samples/client/petstore/swift5/default/SwaggerClientTests/.gitignore @@ -1,14 +1,22 @@ -### https://raw.github.com/github/gitignore/7792e50daeaa6c07460484704671d1dc9f0045a7/Swift.gitignore +# Created by https://www.toptal.com/developers/gitignore/api/swift,xcode +# Edit at https://www.toptal.com/developers/gitignore?templates=swift,xcode +### Swift ### # Xcode # # gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore -## Build generated +## User settings +xcuserdata/ + +## compatibility with Xcode 8 and earlier (ignoring not required starting Xcode 9) +*.xcscmblueprint +*.xccheckout + +## compatibility with Xcode 3 and earlier (ignoring not required starting Xcode 4) build/ DerivedData/ - -## Various settings +*.moved-aside *.pbxuser !default.pbxuser *.mode1v3 @@ -17,15 +25,11 @@ DerivedData/ !default.mode2v3 *.perspectivev3 !default.perspectivev3 -xcuserdata/ - -## Other -*.moved-aside -*.xccheckout -*.xcscmblueprint ## Obj-C/Swift specific *.hmap + +## App packaging *.ipa *.dSYM.zip *.dSYM @@ -35,38 +39,67 @@ timeline.xctimeline playground.xcworkspace # Swift Package Manager -# # Add this line if you want to avoid checking in source code from Swift Package Manager dependencies. # Packages/ # Package.pins # Package.resolved +# *.xcodeproj +# Xcode automatically generates this directory with a .xcworkspacedata file and xcuserdata +# hence it is not needed unless you have added a package configuration file to your project +# .swiftpm + .build/ # CocoaPods -# # We recommend against adding the Pods directory to your .gitignore. However # you should judge for yourself, the pros and cons are mentioned at: # https://guides.cocoapods.org/using/using-cocoapods.html#should-i-check-the-pods-directory-into-source-control -# -Pods/ +# Pods/ +# Add this line if you want to avoid checking in source code from the Xcode workspace +# *.xcworkspace # Carthage -# # Add this line if you want to avoid checking in source code from Carthage dependencies. -Carthage/Checkouts +# Carthage/Checkouts -Carthage/Build +Carthage/Build/ + +# Add this lines if you are using Accio dependency management (Deprecated since Xcode 12) +# Dependencies/ +# .accio/ # fastlane -# -# It is recommended to not store the screenshots in the git repo. Instead, use fastlane to re-generate the -# screenshots whenever they are needed. +# It is recommended to not store the screenshots in the git repo. +# Instead, use fastlane to re-generate the screenshots whenever they are needed. # For more information about the recommended setup visit: # https://docs.fastlane.tools/best-practices/source-control/#source-control fastlane/report.xml fastlane/Preview.html -fastlane/screenshots +fastlane/screenshots/**/*.png fastlane/test_output +# Code Injection +# After new code Injection tools there's a generated folder /iOSInjectionProject +# https://github.com/johnno1962/injectionforxcode +iOSInjectionProject/ + +### Xcode ### +# Xcode +# gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore + + + + +## Gcc Patch +/*.gcno + +### Xcode Patch ### +*.xcodeproj/* +!*.xcodeproj/project.pbxproj +!*.xcodeproj/xcshareddata/ +!*.xcworkspace/contents.xcworkspacedata +**/xcshareddata/WorkspaceSettings.xcsettings + +# End of https://www.toptal.com/developers/gitignore/api/swift,xcode \ No newline at end of file diff --git a/samples/client/petstore/swift5/default/SwaggerClientTests/Podfile b/samples/client/petstore/swift5/default/SwaggerClientTests/Podfile deleted file mode 100644 index 77432f9eee9..00000000000 --- a/samples/client/petstore/swift5/default/SwaggerClientTests/Podfile +++ /dev/null @@ -1,13 +0,0 @@ -platform :ios, '9.0' - -source 'https://cdn.cocoapods.org/' - -use_frameworks! - -target 'SwaggerClient' do - pod "PetstoreClient", :path => "../" - - target 'SwaggerClientTests' do - inherit! :search_paths - end -end diff --git a/samples/client/petstore/swift5/default/SwaggerClientTests/Podfile.lock b/samples/client/petstore/swift5/default/SwaggerClientTests/Podfile.lock deleted file mode 100644 index 11d11529e9e..00000000000 --- a/samples/client/petstore/swift5/default/SwaggerClientTests/Podfile.lock +++ /dev/null @@ -1,16 +0,0 @@ -PODS: - - PetstoreClient (1.0.0) - -DEPENDENCIES: - - PetstoreClient (from `../`) - -EXTERNAL SOURCES: - PetstoreClient: - :path: "../" - -SPEC CHECKSUMS: - PetstoreClient: b26b235a3ece06dbf1da99dc67e48aa201659f21 - -PODFILE CHECKSUM: 509bec696cc1d8641751b52e4fe4bef04ac4542c - -COCOAPODS: 1.10.0 diff --git a/samples/client/petstore/swift5/default/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj b/samples/client/petstore/swift5/default/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj index ca2ec05d5dc..7d9d50e1fff 100644 --- a/samples/client/petstore/swift5/default/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj +++ b/samples/client/petstore/swift5/default/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj @@ -3,12 +3,11 @@ archiveVersion = 1; classes = { }; - objectVersion = 46; + objectVersion = 52; objects = { /* Begin PBXBuildFile section */ 1A501F48219C3DC600F372F6 /* DateFormatTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1A501F47219C3DC600F372F6 /* DateFormatTests.swift */; }; - 23B2E76564651097BE2FE501 /* Pods_SwaggerClient.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 7F98CC8B18E5FA9213F6A68D /* Pods_SwaggerClient.framework */; }; 6D4EFB951C692C6300B96B06 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6D4EFB941C692C6300B96B06 /* AppDelegate.swift */; }; 6D4EFB971C692C6300B96B06 /* ViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6D4EFB961C692C6300B96B06 /* ViewController.swift */; }; 6D4EFB9A1C692C6300B96B06 /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 6D4EFB981C692C6300B96B06 /* Main.storyboard */; }; @@ -17,9 +16,9 @@ 6D4EFBB51C693BE200B96B06 /* PetAPITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6D4EFBB41C693BE200B96B06 /* PetAPITests.swift */; }; 6D4EFBB71C693BED00B96B06 /* StoreAPITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6D4EFBB61C693BED00B96B06 /* StoreAPITests.swift */; }; 6D4EFBB91C693BFC00B96B06 /* UserAPITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6D4EFBB81C693BFC00B96B06 /* UserAPITests.swift */; }; + A5782C752664FB6500CAA106 /* PetstoreClient in Frameworks */ = {isa = PBXBuildFile; productRef = A5782C742664FB6500CAA106 /* PetstoreClient */; }; A5EA124F241901AA00E30FC3 /* UIImage+Extras.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5EA124E241901AA00E30FC3 /* UIImage+Extras.swift */; }; A5EA1251241905F000E30FC3 /* FileUtils.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5EA1250241905F000E30FC3 /* FileUtils.swift */; }; - FB5CCC7EFA680BB2746B695B /* Pods_SwaggerClientTests.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 83FDC034BBA2A07AE9975250 /* Pods_SwaggerClientTests.framework */; }; /* End PBXBuildFile section */ /* Begin PBXContainerItemProxy section */ @@ -33,7 +32,6 @@ /* End PBXContainerItemProxy section */ /* Begin PBXFileReference section */ - 081E9B893DEB1589CB807EA7 /* Pods-SwaggerClient.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-SwaggerClient.debug.xcconfig"; path = "Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient.debug.xcconfig"; sourceTree = ""; }; 1A501F47219C3DC600F372F6 /* DateFormatTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DateFormatTests.swift; sourceTree = ""; }; 6D4EFB911C692C6300B96B06 /* SwaggerClient.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = SwaggerClient.app; sourceTree = BUILT_PRODUCTS_DIR; }; 6D4EFB941C692C6300B96B06 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; @@ -47,14 +45,8 @@ 6D4EFBB41C693BE200B96B06 /* PetAPITests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PetAPITests.swift; sourceTree = ""; }; 6D4EFBB61C693BED00B96B06 /* StoreAPITests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StoreAPITests.swift; sourceTree = ""; }; 6D4EFBB81C693BFC00B96B06 /* UserAPITests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = UserAPITests.swift; sourceTree = ""; }; - 7F98CC8B18E5FA9213F6A68D /* Pods_SwaggerClient.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_SwaggerClient.framework; sourceTree = BUILT_PRODUCTS_DIR; }; - 83FDC034BBA2A07AE9975250 /* Pods_SwaggerClientTests.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_SwaggerClientTests.framework; sourceTree = BUILT_PRODUCTS_DIR; }; A5EA124E241901AA00E30FC3 /* UIImage+Extras.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "UIImage+Extras.swift"; sourceTree = ""; }; A5EA1250241905F000E30FC3 /* FileUtils.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FileUtils.swift; sourceTree = ""; }; - ACB80AC61FA8D8916D4559AA /* Pods-SwaggerClient.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-SwaggerClient.release.xcconfig"; path = "Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient.release.xcconfig"; sourceTree = ""; }; - C07EC0A94AA0F86D60668B32 /* Pods.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods.framework; sourceTree = BUILT_PRODUCTS_DIR; }; - E43FC34A9681D65ED44EE914 /* Pods-SwaggerClientTests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-SwaggerClientTests.debug.xcconfig"; path = "Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests.debug.xcconfig"; sourceTree = ""; }; - ED8576754DBB828CAE63EA87 /* Pods-SwaggerClientTests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-SwaggerClientTests.release.xcconfig"; path = "Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests.release.xcconfig"; sourceTree = ""; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ @@ -62,7 +54,7 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( - 23B2E76564651097BE2FE501 /* Pods_SwaggerClient.framework in Frameworks */, + A5782C752664FB6500CAA106 /* PetstoreClient in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -70,30 +62,15 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( - FB5CCC7EFA680BB2746B695B /* Pods_SwaggerClientTests.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */ - 203D4495376E4EB72474B091 /* Pods */ = { - isa = PBXGroup; - children = ( - 081E9B893DEB1589CB807EA7 /* Pods-SwaggerClient.debug.xcconfig */, - ACB80AC61FA8D8916D4559AA /* Pods-SwaggerClient.release.xcconfig */, - E43FC34A9681D65ED44EE914 /* Pods-SwaggerClientTests.debug.xcconfig */, - ED8576754DBB828CAE63EA87 /* Pods-SwaggerClientTests.release.xcconfig */, - ); - name = Pods; - sourceTree = ""; - }; 3FABC56EC0BA84CBF4F99564 /* Frameworks */ = { isa = PBXGroup; children = ( - C07EC0A94AA0F86D60668B32 /* Pods.framework */, - 7F98CC8B18E5FA9213F6A68D /* Pods_SwaggerClient.framework */, - 83FDC034BBA2A07AE9975250 /* Pods_SwaggerClientTests.framework */, ); name = Frameworks; sourceTree = ""; @@ -105,7 +82,6 @@ 6D4EFBA81C692C6300B96B06 /* SwaggerClientTests */, 6D4EFB921C692C6300B96B06 /* Products */, 3FABC56EC0BA84CBF4F99564 /* Frameworks */, - 203D4495376E4EB72474B091 /* Pods */, ); sourceTree = ""; }; @@ -152,17 +128,18 @@ isa = PBXNativeTarget; buildConfigurationList = 6D4EFBAE1C692C6300B96B06 /* Build configuration list for PBXNativeTarget "SwaggerClient" */; buildPhases = ( - 5BC9214E8D9BA5A427A3775B /* [CP] Check Pods Manifest.lock */, 6D4EFB8D1C692C6300B96B06 /* Sources */, 6D4EFB8E1C692C6300B96B06 /* Frameworks */, 6D4EFB8F1C692C6300B96B06 /* Resources */, - FDCA0F14611FE114BFEBA8BB /* [CP] Embed Pods Frameworks */, ); buildRules = ( ); dependencies = ( ); name = SwaggerClient; + packageProductDependencies = ( + A5782C742664FB6500CAA106 /* PetstoreClient */, + ); productName = SwaggerClient; productReference = 6D4EFB911C692C6300B96B06 /* SwaggerClient.app */; productType = "com.apple.product-type.application"; @@ -171,7 +148,6 @@ isa = PBXNativeTarget; buildConfigurationList = 6D4EFBB11C692C6300B96B06 /* Build configuration list for PBXNativeTarget "SwaggerClientTests" */; buildPhases = ( - EEDC5E683F9569976B7C1192 /* [CP] Check Pods Manifest.lock */, 6D4EFBA11C692C6300B96B06 /* Sources */, 6D4EFBA21C692C6300B96B06 /* Frameworks */, 6D4EFBA31C692C6300B96B06 /* Resources */, @@ -246,71 +222,6 @@ }; /* End PBXResourcesBuildPhase section */ -/* Begin PBXShellScriptBuildPhase section */ - 5BC9214E8D9BA5A427A3775B /* [CP] Check Pods Manifest.lock */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputFileListPaths = ( - ); - inputPaths = ( - "${PODS_PODFILE_DIR_PATH}/Podfile.lock", - "${PODS_ROOT}/Manifest.lock", - ); - name = "[CP] Check Pods Manifest.lock"; - outputFileListPaths = ( - ); - outputPaths = ( - "$(DERIVED_FILE_DIR)/Pods-SwaggerClient-checkManifestLockResult.txt", - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; - showEnvVarsInLog = 0; - }; - EEDC5E683F9569976B7C1192 /* [CP] Check Pods Manifest.lock */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputFileListPaths = ( - ); - inputPaths = ( - "${PODS_PODFILE_DIR_PATH}/Podfile.lock", - "${PODS_ROOT}/Manifest.lock", - ); - name = "[CP] Check Pods Manifest.lock"; - outputFileListPaths = ( - ); - outputPaths = ( - "$(DERIVED_FILE_DIR)/Pods-SwaggerClientTests-checkManifestLockResult.txt", - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; - showEnvVarsInLog = 0; - }; - FDCA0F14611FE114BFEBA8BB /* [CP] Embed Pods Frameworks */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputPaths = ( - "${PODS_ROOT}/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-frameworks.sh", - "${BUILT_PRODUCTS_DIR}/PetstoreClient/PetstoreClient.framework", - ); - name = "[CP] Embed Pods Frameworks"; - outputPaths = ( - "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/PetstoreClient.framework", - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-frameworks.sh\"\n"; - showEnvVarsInLog = 0; - }; -/* End PBXShellScriptBuildPhase section */ - /* Begin PBXSourcesBuildPhase section */ 6D4EFB8D1C692C6300B96B06 /* Sources */ = { isa = PBXSourcesBuildPhase; @@ -474,11 +385,13 @@ }; 6D4EFBAF1C692C6300B96B06 /* Debug */ = { isa = XCBuildConfiguration; - baseConfigurationReference = 081E9B893DEB1589CB807EA7 /* Pods-SwaggerClient.debug.xcconfig */; buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; INFOPLIST_FILE = SwaggerClient/Info.plist; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); PRODUCT_BUNDLE_IDENTIFIER = com.swagger.SwaggerClient; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_VERSION = 5.0; @@ -487,11 +400,13 @@ }; 6D4EFBB01C692C6300B96B06 /* Release */ = { isa = XCBuildConfiguration; - baseConfigurationReference = ACB80AC61FA8D8916D4559AA /* Pods-SwaggerClient.release.xcconfig */; buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; INFOPLIST_FILE = SwaggerClient/Info.plist; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); PRODUCT_BUNDLE_IDENTIFIER = com.swagger.SwaggerClient; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_VERSION = 5.0; @@ -500,11 +415,14 @@ }; 6D4EFBB21C692C6300B96B06 /* Debug */ = { isa = XCBuildConfiguration; - baseConfigurationReference = E43FC34A9681D65ED44EE914 /* Pods-SwaggerClientTests.debug.xcconfig */; buildSettings = { BUNDLE_LOADER = "$(TEST_HOST)"; INFOPLIST_FILE = SwaggerClientTests/Info.plist; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); PRODUCT_BUNDLE_IDENTIFIER = com.swagger.SwaggerClientTests; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_VERSION = 5.0; @@ -514,11 +432,14 @@ }; 6D4EFBB31C692C6300B96B06 /* Release */ = { isa = XCBuildConfiguration; - baseConfigurationReference = ED8576754DBB828CAE63EA87 /* Pods-SwaggerClientTests.release.xcconfig */; buildSettings = { BUNDLE_LOADER = "$(TEST_HOST)"; INFOPLIST_FILE = SwaggerClientTests/Info.plist; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); PRODUCT_BUNDLE_IDENTIFIER = com.swagger.SwaggerClientTests; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_VERSION = 5.0; @@ -557,6 +478,13 @@ defaultConfigurationName = Release; }; /* End XCConfigurationList section */ + +/* Begin XCSwiftPackageProductDependency section */ + A5782C742664FB6500CAA106 /* PetstoreClient */ = { + isa = XCSwiftPackageProductDependency; + productName = PetstoreClient; + }; +/* End XCSwiftPackageProductDependency section */ }; rootObject = 6D4EFB891C692C6300B96B06 /* Project object */; } diff --git a/samples/client/petstore/swift5/default/SwaggerClientTests/SwaggerClient.xcworkspace/contents.xcworkspacedata b/samples/client/petstore/swift5/default/SwaggerClientTests/SwaggerClient.xcworkspace/contents.xcworkspacedata index 9b3fa18954f..00ec9b53a7f 100644 --- a/samples/client/petstore/swift5/default/SwaggerClientTests/SwaggerClient.xcworkspace/contents.xcworkspacedata +++ b/samples/client/petstore/swift5/default/SwaggerClientTests/SwaggerClient.xcworkspace/contents.xcworkspacedata @@ -2,9 +2,9 @@ + location = "group:.."> + location = "group:SwaggerClient.xcodeproj"> diff --git a/samples/client/petstore/swift5/default/SwaggerClientTests/SwaggerClient.xcworkspace/xcshareddata/swiftpm/Package.resolved b/samples/client/petstore/swift5/default/SwaggerClientTests/SwaggerClient.xcworkspace/xcshareddata/swiftpm/Package.resolved new file mode 100644 index 00000000000..d384b276b4b --- /dev/null +++ b/samples/client/petstore/swift5/default/SwaggerClientTests/SwaggerClient.xcworkspace/xcshareddata/swiftpm/Package.resolved @@ -0,0 +1,16 @@ +{ + "object": { + "pins": [ + { + "package": "AnyCodable", + "repositoryURL": "https://github.com/Flight-School/AnyCodable", + "state": { + "branch": null, + "revision": "876d162385e9862ae8b3c8d65dc301312b040005", + "version": "0.6.0" + } + } + ] + }, + "version": 1 +} diff --git a/samples/client/petstore/swift5/default/docs/FakeAPI.md b/samples/client/petstore/swift5/default/docs/FakeAPI.md index 46599ecd3b1..01d7c662e3c 100644 --- a/samples/client/petstore/swift5/default/docs/FakeAPI.md +++ b/samples/client/petstore/swift5/default/docs/FakeAPI.md @@ -431,7 +431,7 @@ import PetstoreClient let number = 987 // Double | None let double = 987 // Double | None let patternWithoutDelimiter = "patternWithoutDelimiter_example" // String | None -let byte = 987 // Data | None +let byte = Data([9, 8, 7]) // Data | None let integer = 987 // Int | None (optional) let int32 = 987 // Int | None (optional) let int64 = 987 // Int64 | None (optional) diff --git a/samples/client/petstore/swift5/default/project.yml b/samples/client/petstore/swift5/default/project.yml index 5528eeee513..0493cf65896 100644 --- a/samples/client/petstore/swift5/default/project.yml +++ b/samples/client/petstore/swift5/default/project.yml @@ -11,5 +11,5 @@ targets: settings: APPLICATION_EXTENSION_API_ONLY: true scheme: {} - + dependencies: - carthage: AnyCodable diff --git a/samples/client/petstore/swift5/deprecated/.gitignore b/samples/client/petstore/swift5/deprecated/.gitignore index 5e5d5cebcf4..627d360a903 100644 --- a/samples/client/petstore/swift5/deprecated/.gitignore +++ b/samples/client/petstore/swift5/deprecated/.gitignore @@ -1,12 +1,22 @@ +# Created by https://www.toptal.com/developers/gitignore/api/swift,xcode +# Edit at https://www.toptal.com/developers/gitignore?templates=swift,xcode + +### Swift ### # Xcode # # gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore -## Build generated -build/ -DerivedData +## User settings +xcuserdata/ -## Various settings +## compatibility with Xcode 8 and earlier (ignoring not required starting Xcode 9) +*.xcscmblueprint +*.xccheckout + +## compatibility with Xcode 3 and earlier (ignoring not required starting Xcode 4) +build/ +DerivedData/ +*.moved-aside *.pbxuser !default.pbxuser *.mode1v3 @@ -15,49 +25,81 @@ DerivedData !default.mode2v3 *.perspectivev3 !default.perspectivev3 -xcuserdata - -## Other -*.xccheckout -*.moved-aside -*.xcuserstate -*.xcscmblueprint ## Obj-C/Swift specific *.hmap + +## App packaging *.ipa +*.dSYM.zip +*.dSYM ## Playgrounds timeline.xctimeline playground.xcworkspace # Swift Package Manager -# # Add this line if you want to avoid checking in source code from Swift Package Manager dependencies. # Packages/ +# Package.pins +# Package.resolved +# *.xcodeproj +# Xcode automatically generates this directory with a .xcworkspacedata file and xcuserdata +# hence it is not needed unless you have added a package configuration file to your project +# .swiftpm + .build/ # CocoaPods -# # We recommend against adding the Pods directory to your .gitignore. However # you should judge for yourself, the pros and cons are mentioned at: # https://guides.cocoapods.org/using/using-cocoapods.html#should-i-check-the-pods-directory-into-source-control -# # Pods/ +# Add this line if you want to avoid checking in source code from the Xcode workspace +# *.xcworkspace # Carthage -# # Add this line if you want to avoid checking in source code from Carthage dependencies. # Carthage/Checkouts -Carthage/Build +Carthage/Build/ + +# Add this lines if you are using Accio dependency management (Deprecated since Xcode 12) +# Dependencies/ +# .accio/ # fastlane -# -# It is recommended to not store the screenshots in the git repo. Instead, use fastlane to re-generate the -# screenshots whenever they are needed. +# It is recommended to not store the screenshots in the git repo. +# Instead, use fastlane to re-generate the screenshots whenever they are needed. # For more information about the recommended setup visit: -# https://github.com/fastlane/fastlane/blob/master/docs/Gitignore.md +# https://docs.fastlane.tools/best-practices/source-control/#source-control fastlane/report.xml -fastlane/screenshots +fastlane/Preview.html +fastlane/screenshots/**/*.png +fastlane/test_output + +# Code Injection +# After new code Injection tools there's a generated folder /iOSInjectionProject +# https://github.com/johnno1962/injectionforxcode + +iOSInjectionProject/ + +### Xcode ### +# Xcode +# gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore + + + + +## Gcc Patch +/*.gcno + +### Xcode Patch ### +*.xcodeproj/* +!*.xcodeproj/project.pbxproj +!*.xcodeproj/xcshareddata/ +!*.xcworkspace/contents.xcworkspacedata +**/xcshareddata/WorkspaceSettings.xcsettings + +# End of https://www.toptal.com/developers/gitignore/api/swift,xcode diff --git a/samples/client/petstore/swift5/deprecated/.openapi-generator/VERSION b/samples/client/petstore/swift5/deprecated/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/client/petstore/swift5/deprecated/.openapi-generator/VERSION +++ b/samples/client/petstore/swift5/deprecated/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/client/petstore/swift5/deprecated/Cartfile b/samples/client/petstore/swift5/deprecated/Cartfile index 84aaa61ef2d..a6a6bcacb1d 100644 --- a/samples/client/petstore/swift5/deprecated/Cartfile +++ b/samples/client/petstore/swift5/deprecated/Cartfile @@ -1,2 +1,2 @@ -github "Flight-School/AnyCodable" ~> 0.4.0 +github "Flight-School/AnyCodable" ~> 0.6.1 diff --git a/samples/client/petstore/swift5/deprecated/Package.resolved b/samples/client/petstore/swift5/deprecated/Package.resolved new file mode 100644 index 00000000000..79610c3b3b3 --- /dev/null +++ b/samples/client/petstore/swift5/deprecated/Package.resolved @@ -0,0 +1,16 @@ +{ + "object": { + "pins": [ + { + "package": "AnyCodable", + "repositoryURL": "https://github.com/Flight-School/AnyCodable", + "state": { + "branch": null, + "revision": "69261f239f0fffaf51495dadc4f8483fbfe97025", + "version": "0.6.1" + } + } + ] + }, + "version": 1 +} diff --git a/samples/client/petstore/swift5/deprecated/Package.swift b/samples/client/petstore/swift5/deprecated/Package.swift index b724838fe8d..87bb775fb72 100644 --- a/samples/client/petstore/swift5/deprecated/Package.swift +++ b/samples/client/petstore/swift5/deprecated/Package.swift @@ -19,7 +19,7 @@ let package = Package( ], dependencies: [ // Dependencies declare other packages that this package depends on. - .package(url: "https://github.com/Flight-School/AnyCodable", .exact("0.4.0")), + .package(url: "https://github.com/Flight-School/AnyCodable", from: "0.6.1"), ], targets: [ // Targets are the basic building blocks of a package. A target can define a module or a test suite. diff --git a/samples/client/petstore/swift5/deprecated/PetstoreClient.podspec b/samples/client/petstore/swift5/deprecated/PetstoreClient.podspec index de06558efbd..0e6bf7ec024 100644 --- a/samples/client/petstore/swift5/deprecated/PetstoreClient.podspec +++ b/samples/client/petstore/swift5/deprecated/PetstoreClient.podspec @@ -11,5 +11,5 @@ Pod::Spec.new do |s| s.homepage = 'https://github.com/openapitools/openapi-generator' s.summary = 'PetstoreClient' s.source_files = 'PetstoreClient/Classes/**/*.swift' - s.dependency 'AnyCodable-FlightSchool', '~> 0.4.0' + s.dependency 'AnyCodable-FlightSchool', '~> 0.6.1' end diff --git a/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/APIs.swift b/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/APIs.swift index 57308c82f8e..bbc07371c77 100644 --- a/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/APIs.swift +++ b/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/APIs.swift @@ -6,10 +6,13 @@ import Foundation -open class PetstoreClientAPI { +@available(*, deprecated, renamed: "PetstoreClient") +public typealias PetstoreClientAPI = PetstoreClient + +open class PetstoreClient { public static var basePath = "http://petstore.swagger.io/v2" - public static var credential: URLCredential? public static var customHeaders: [String: String] = [:] + public static var credential: URLCredential? public static var requestBuilderFactory: RequestBuilderFactory = URLSessionRequestBuilderFactory() public static var apiResponseQueue: DispatchQueue = .main } @@ -32,7 +35,7 @@ open class RequestBuilder { self.parameters = parameters self.headers = headers - addHeaders(PetstoreClientAPI.customHeaders) + addHeaders(PetstoreClient.customHeaders) } open func addHeaders(_ aHeaders: [String: String]) { @@ -41,7 +44,7 @@ open class RequestBuilder { } } - open func execute(_ apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, _ completion: @escaping (_ result: Swift.Result, Error>) -> Void) { } + open func execute(_ apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, _ completion: @escaping (_ result: Swift.Result, Error>) -> Void) { } public func addHeader(name: String, value: String) -> Self { if !value.isEmpty { @@ -51,7 +54,7 @@ open class RequestBuilder { } open func addCredential() -> Self { - credential = PetstoreClientAPI.credential + credential = PetstoreClient.credential return self } } 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 10fd471343e..acc589a6af8 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 @@ -6,8 +6,12 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif open class PetAPI { + /** Add a new pet to the store @@ -15,7 +19,7 @@ open class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func addPet(pet: Pet, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func addPet(pet: Pet, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { addPetWithRequestBuilder(pet: pet).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -36,21 +40,21 @@ open class PetAPI { - returns: RequestBuilder */ open class func addPetWithRequestBuilder(pet: Pet) -> RequestBuilder { - let path = "/pet" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: pet) + let localVariablePath = "/pet" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: pet) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -61,7 +65,7 @@ open class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func deletePet(petId: Int64, apiKey: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func deletePet(petId: Int64, apiKey: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { deletePetWithRequestBuilder(petId: petId, apiKey: apiKey).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -83,24 +87,24 @@ open class PetAPI { - returns: RequestBuilder */ open class func deletePetWithRequestBuilder(petId: Int64, apiKey: String? = nil) -> RequestBuilder { - var path = "/pet/{petId}" + var localVariablePath = "/pet/{petId}" let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))" let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" - path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + localVariablePath = localVariablePath.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ "api_key": apiKey?.encodeToJSON(), ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "DELETE", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -119,7 +123,7 @@ open class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func findPetsByStatus(status: [String], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: [Pet]?, _ error: Error?) -> Void)) { + open class func findPetsByStatus(status: [String], apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: [Pet]?, _ error: Error?) -> Void)) { findPetsByStatusWithRequestBuilder(status: status).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -141,24 +145,24 @@ open class PetAPI { - returns: RequestBuilder<[Pet]> */ open class func findPetsByStatusWithRequestBuilder(status: [String]) -> RequestBuilder<[Pet]> { - let path = "/pet/findByStatus" - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + let localVariablePath = "/pet/findByStatus" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - var urlComponents = URLComponents(string: URLString) - urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ + var localVariableUrlComponents = URLComponents(string: localVariableURLString) + localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ "status": status.encodeToJSON(), ]) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -169,7 +173,7 @@ open class PetAPI { - parameter completion: completion handler to receive the data and the error objects */ @available(*, deprecated, message: "This operation is deprecated.") - open class func findPetsByTags(tags: [String], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: [Pet]?, _ error: Error?) -> Void)) { + open class func findPetsByTags(tags: [String], apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: [Pet]?, _ error: Error?) -> Void)) { findPetsByTagsWithRequestBuilder(tags: tags).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -192,24 +196,24 @@ open class PetAPI { */ @available(*, deprecated, message: "This operation is deprecated.") open class func findPetsByTagsWithRequestBuilder(tags: [String]) -> RequestBuilder<[Pet]> { - let path = "/pet/findByTags" - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + let localVariablePath = "/pet/findByTags" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - var urlComponents = URLComponents(string: URLString) - urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ + var localVariableUrlComponents = URLComponents(string: localVariableURLString) + localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ "tags": tags.encodeToJSON(), ]) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -219,7 +223,7 @@ open class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func getPetById(petId: Int64, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Pet?, _ error: Error?) -> Void)) { + open class func getPetById(petId: Int64, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Pet?, _ error: Error?) -> Void)) { getPetByIdWithRequestBuilder(petId: petId).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -241,24 +245,24 @@ open class PetAPI { - returns: RequestBuilder */ open class func getPetByIdWithRequestBuilder(petId: Int64) -> RequestBuilder { - var path = "/pet/{petId}" + var localVariablePath = "/pet/{petId}" let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))" let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" - path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + localVariablePath = localVariablePath.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -268,7 +272,7 @@ open class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func updatePet(pet: Pet, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func updatePet(pet: Pet, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { updatePetWithRequestBuilder(pet: pet).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -289,21 +293,21 @@ open class PetAPI { - returns: RequestBuilder */ open class func updatePetWithRequestBuilder(pet: Pet) -> RequestBuilder { - let path = "/pet" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: pet) + let localVariablePath = "/pet" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: pet) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "PUT", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -315,7 +319,7 @@ open class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func updatePetWithForm(petId: Int64, name: String? = nil, status: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func updatePetWithForm(petId: Int64, name: String? = nil, status: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { updatePetWithFormWithRequestBuilder(petId: petId, name: name, status: status).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -338,30 +342,30 @@ open class PetAPI { - returns: RequestBuilder */ open class func updatePetWithFormWithRequestBuilder(petId: Int64, name: String? = nil, status: String? = nil) -> RequestBuilder { - var path = "/pet/{petId}" + var localVariablePath = "/pet/{petId}" let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))" let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" - path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path - let formParams: [String: Any?] = [ + localVariablePath = localVariablePath.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableFormParams: [String: Any?] = [ "name": name?.encodeToJSON(), "status": status?.encodeToJSON(), ] - let nonNullParameters = APIHelper.rejectNil(formParams) - let parameters = APIHelper.convertBoolToString(nonNullParameters) + let localVariableNonNullParameters = APIHelper.rejectNil(localVariableFormParams) + let localVariableParameters = APIHelper.convertBoolToString(localVariableNonNullParameters) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ "Content-Type": "application/x-www-form-urlencoded", ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -373,7 +377,7 @@ open class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func uploadFile(petId: Int64, additionalMetadata: String? = nil, file: URL? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: ApiResponse?, _ error: Error?) -> Void)) { + open class func uploadFile(petId: Int64, additionalMetadata: String? = nil, file: URL? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: ApiResponse?, _ error: Error?) -> Void)) { uploadFileWithRequestBuilder(petId: petId, additionalMetadata: additionalMetadata, file: file).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -396,30 +400,29 @@ open class PetAPI { - returns: RequestBuilder */ open class func uploadFileWithRequestBuilder(petId: Int64, additionalMetadata: String? = nil, file: URL? = nil) -> RequestBuilder { - var path = "/pet/{petId}/uploadImage" + var localVariablePath = "/pet/{petId}/uploadImage" let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))" let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" - path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path - let formParams: [String: Any?] = [ + localVariablePath = localVariablePath.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableFormParams: [String: Any?] = [ "additionalMetadata": additionalMetadata?.encodeToJSON(), "file": file?.encodeToJSON(), ] - let nonNullParameters = APIHelper.rejectNil(formParams) - let parameters = APIHelper.convertBoolToString(nonNullParameters) + let localVariableNonNullParameters = APIHelper.rejectNil(localVariableFormParams) + let localVariableParameters = APIHelper.convertBoolToString(localVariableNonNullParameters) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ "Content-Type": "multipart/form-data", ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } - } 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 48b32223334..1be8e579d3d 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 @@ -6,8 +6,12 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif open class StoreAPI { + /** Delete purchase order by ID @@ -15,7 +19,7 @@ open class StoreAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func deleteOrder(orderId: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func deleteOrder(orderId: String, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { deleteOrderWithRequestBuilder(orderId: orderId).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -34,24 +38,24 @@ open class StoreAPI { - returns: RequestBuilder */ open class func deleteOrderWithRequestBuilder(orderId: String) -> RequestBuilder { - var path = "/store/order/{orderId}" + var localVariablePath = "/store/order/{orderId}" let orderIdPreEscape = "\(APIHelper.mapValueToPathItem(orderId))" let orderIdPostEscape = orderIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" - path = path.replacingOccurrences(of: "{orderId}", with: orderIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + localVariablePath = localVariablePath.replacingOccurrences(of: "{orderId}", with: orderIdPostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "DELETE", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -60,7 +64,7 @@ open class StoreAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func getInventory(apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: [String: Int]?, _ error: Error?) -> Void)) { + open class func getInventory(apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: [String: Int]?, _ error: Error?) -> Void)) { getInventoryWithRequestBuilder().execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -81,21 +85,21 @@ open class StoreAPI { - returns: RequestBuilder<[String: Int]> */ open class func getInventoryWithRequestBuilder() -> RequestBuilder<[String: Int]> { - let path = "/store/inventory" - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + let localVariablePath = "/store/inventory" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder<[String: Int]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder<[String: Int]>.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -105,7 +109,7 @@ open class StoreAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func getOrderById(orderId: Int64, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Order?, _ error: Error?) -> Void)) { + open class func getOrderById(orderId: Int64, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Order?, _ error: Error?) -> Void)) { getOrderByIdWithRequestBuilder(orderId: orderId).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -124,24 +128,24 @@ open class StoreAPI { - returns: RequestBuilder */ open class func getOrderByIdWithRequestBuilder(orderId: Int64) -> RequestBuilder { - var path = "/store/order/{orderId}" + var localVariablePath = "/store/order/{orderId}" let orderIdPreEscape = "\(APIHelper.mapValueToPathItem(orderId))" let orderIdPostEscape = orderIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" - path = path.replacingOccurrences(of: "{orderId}", with: orderIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + localVariablePath = localVariablePath.replacingOccurrences(of: "{orderId}", with: orderIdPostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -151,7 +155,7 @@ open class StoreAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func placeOrder(order: Order, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Order?, _ error: Error?) -> Void)) { + open class func placeOrder(order: Order, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Order?, _ error: Error?) -> Void)) { placeOrderWithRequestBuilder(order: order).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -169,21 +173,20 @@ open class StoreAPI { - returns: RequestBuilder */ open class func placeOrderWithRequestBuilder(order: Order) -> RequestBuilder { - let path = "/store/order" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: order) + let localVariablePath = "/store/order" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: order) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } - } 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 b35fc94ae58..ad96b3a6341 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 @@ -6,8 +6,12 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif open class UserAPI { + /** Create user @@ -15,7 +19,7 @@ open class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func createUser(user: User, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func createUser(user: User, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { createUserWithRequestBuilder(user: user).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -37,21 +41,21 @@ open class UserAPI { - returns: RequestBuilder */ open class func createUserWithRequestBuilder(user: User) -> RequestBuilder { - let path = "/user" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: user) + let localVariablePath = "/user" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: user) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -61,7 +65,7 @@ open class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func createUsersWithArrayInput(user: [User], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func createUsersWithArrayInput(user: [User], apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { createUsersWithArrayInputWithRequestBuilder(user: user).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -82,21 +86,21 @@ open class UserAPI { - returns: RequestBuilder */ open class func createUsersWithArrayInputWithRequestBuilder(user: [User]) -> RequestBuilder { - let path = "/user/createWithArray" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: user) + let localVariablePath = "/user/createWithArray" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: user) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -106,7 +110,7 @@ open class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func createUsersWithListInput(user: [User], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func createUsersWithListInput(user: [User], apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { createUsersWithListInputWithRequestBuilder(user: user).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -127,21 +131,21 @@ open class UserAPI { - returns: RequestBuilder */ open class func createUsersWithListInputWithRequestBuilder(user: [User]) -> RequestBuilder { - let path = "/user/createWithList" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: user) + let localVariablePath = "/user/createWithList" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: user) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -151,7 +155,7 @@ open class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func deleteUser(username: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func deleteUser(username: String, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { deleteUserWithRequestBuilder(username: username).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -173,24 +177,24 @@ open class UserAPI { - returns: RequestBuilder */ open class func deleteUserWithRequestBuilder(username: String) -> RequestBuilder { - var path = "/user/{username}" + var localVariablePath = "/user/{username}" let usernamePreEscape = "\(APIHelper.mapValueToPathItem(username))" let usernamePostEscape = usernamePreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" - path = path.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + localVariablePath = localVariablePath.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "DELETE", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -200,7 +204,7 @@ open class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func getUserByName(username: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: User?, _ error: Error?) -> Void)) { + open class func getUserByName(username: String, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: User?, _ error: Error?) -> Void)) { getUserByNameWithRequestBuilder(username: username).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -218,24 +222,24 @@ open class UserAPI { - returns: RequestBuilder */ open class func getUserByNameWithRequestBuilder(username: String) -> RequestBuilder { - var path = "/user/{username}" + var localVariablePath = "/user/{username}" let usernamePreEscape = "\(APIHelper.mapValueToPathItem(username))" let usernamePostEscape = usernamePreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" - path = path.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + localVariablePath = localVariablePath.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -246,7 +250,7 @@ open class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func loginUser(username: String, password: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: String?, _ error: Error?) -> Void)) { + open class func loginUser(username: String, password: String, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: String?, _ error: Error?) -> Void)) { loginUserWithRequestBuilder(username: username, password: password).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -266,25 +270,25 @@ open class UserAPI { - returns: RequestBuilder */ open class func loginUserWithRequestBuilder(username: String, password: String) -> RequestBuilder { - let path = "/user/login" - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + let localVariablePath = "/user/login" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - var urlComponents = URLComponents(string: URLString) - urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ + var localVariableUrlComponents = URLComponents(string: localVariableURLString) + localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ "username": username.encodeToJSON(), "password": password.encodeToJSON(), ]) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -293,7 +297,7 @@ open class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func logoutUser(apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func logoutUser(apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { logoutUserWithRequestBuilder().execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -313,21 +317,21 @@ open class UserAPI { - returns: RequestBuilder */ open class func logoutUserWithRequestBuilder() -> RequestBuilder { - let path = "/user/logout" - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + let localVariablePath = "/user/logout" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -338,7 +342,7 @@ open class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func updateUser(username: String, user: User, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func updateUser(username: String, user: User, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { updateUserWithRequestBuilder(username: username, user: user).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -361,24 +365,23 @@ open class UserAPI { - returns: RequestBuilder */ open class func updateUserWithRequestBuilder(username: String, user: User) -> RequestBuilder { - var path = "/user/{username}" + var localVariablePath = "/user/{username}" let usernamePreEscape = "\(APIHelper.mapValueToPathItem(username))" let usernamePostEscape = usernamePreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" - path = path.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: user) + localVariablePath = localVariablePath.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: user) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "PUT", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } - } diff --git a/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/Configuration.swift b/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/Configuration.swift index 18edabbed78..8fb05331889 100644 --- a/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/Configuration.swift +++ b/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/Configuration.swift @@ -7,6 +7,7 @@ import Foundation open class Configuration { + // This value is used to configure the date formatter that is used to serialize dates into JSON format. // You must set it prior to encoding any dates, and it will only be read once. @available(*, unavailable, message: "To set a different date format, use CodableHelper.dateFormatter instead.") diff --git a/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/Extensions.swift b/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/Extensions.swift index 3aef2d1d6c5..e23035dde30 100644 --- a/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/Extensions.swift +++ b/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/Extensions.swift @@ -5,7 +5,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif extension Bool: JSONEncodable { func encodeToJSON() -> Any { return self as Any } @@ -184,44 +186,3 @@ extension HTTPURLResponse { return Array(200 ..< 300).contains(statusCode) } } - -extension AnyCodable: Hashable { - public func hash(into hasher: inout Hasher) { - switch value { - case let value as Bool: - hasher.combine(value) - case let value as Int: - hasher.combine(value) - case let value as Int8: - hasher.combine(value) - case let value as Int16: - hasher.combine(value) - case let value as Int32: - hasher.combine(value) - case let value as Int64: - hasher.combine(value) - case let value as UInt: - hasher.combine(value) - case let value as UInt8: - hasher.combine(value) - case let value as UInt16: - hasher.combine(value) - case let value as UInt32: - hasher.combine(value) - case let value as UInt64: - hasher.combine(value) - case let value as Float: - hasher.combine(value) - case let value as Double: - hasher.combine(value) - case let value as String: - hasher.combine(value) - case let value as [String: AnyCodable]: - hasher.combine(value) - case let value as [AnyCodable]: - hasher.combine(value) - default: - hasher.combine(0) - } - } -} \ No newline at end of file diff --git a/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift b/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift index 8ed4cc03185..ff77211ec29 100644 --- a/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift +++ b/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif /** Describes the result of uploading an image resource */ public struct ApiResponse: Codable, Hashable { @@ -20,6 +22,7 @@ public struct ApiResponse: Codable, Hashable { self.type = type self.message = message } + public enum CodingKeys: String, CodingKey, CaseIterable { case code case type @@ -34,7 +37,5 @@ public struct ApiResponse: Codable, Hashable { try container.encodeIfPresent(type, forKey: .type) try container.encodeIfPresent(message, forKey: .message) } - - - } + diff --git a/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/Models/Category.swift b/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/Models/Category.swift index 508c796f626..0036cc7a857 100644 --- a/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/Models/Category.swift +++ b/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/Models/Category.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif /** A category for a pet */ public struct Category: Codable, Hashable { @@ -18,6 +20,7 @@ public struct Category: Codable, Hashable { self.id = id self.name = name } + public enum CodingKeys: String, CodingKey, CaseIterable { case id case name @@ -30,7 +33,5 @@ public struct Category: Codable, Hashable { try container.encodeIfPresent(id, forKey: .id) try container.encodeIfPresent(name, forKey: .name) } - - - } + diff --git a/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/Models/Order.swift b/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/Models/Order.swift index 11ee45fef69..ccd3bea0249 100644 --- a/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/Models/Order.swift +++ b/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/Models/Order.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif /** An order for a pets from the pet store */ @available(*, deprecated, message: "This schema is deprecated.") @@ -33,6 +35,7 @@ public struct Order: Codable, Hashable { self.status = status self.complete = complete } + public enum CodingKeys: String, CodingKey, CaseIterable { case id case petId @@ -53,7 +56,5 @@ public struct Order: Codable, Hashable { try container.encodeIfPresent(status, forKey: .status) try container.encodeIfPresent(complete, forKey: .complete) } - - - } + diff --git a/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/Models/Pet.swift b/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/Models/Pet.swift index c1bac661e1f..047967197a7 100644 --- a/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/Models/Pet.swift +++ b/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/Models/Pet.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif /** A pet for sale in the pet store */ public struct Pet: Codable, Hashable { @@ -33,6 +35,7 @@ public struct Pet: Codable, Hashable { self.tags = tags self.status = status } + public enum CodingKeys: String, CodingKey, CaseIterable { case id case category @@ -53,7 +56,5 @@ public struct Pet: Codable, Hashable { try container.encodeIfPresent(tags, forKey: .tags) try container.encodeIfPresent(status, forKey: .status) } - - - } + diff --git a/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift b/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift index 5a275f11b25..555a33e6a18 100644 --- a/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift +++ b/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif /** A tag for a pet */ public struct Tag: Codable, Hashable { @@ -18,6 +20,7 @@ public struct Tag: Codable, Hashable { self.id = id self.name = name } + public enum CodingKeys: String, CodingKey, CaseIterable { case id case name @@ -30,7 +33,5 @@ public struct Tag: Codable, Hashable { try container.encodeIfPresent(id, forKey: .id) try container.encodeIfPresent(name, forKey: .name) } - - - } + diff --git a/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/Models/User.swift b/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/Models/User.swift index 058360d1249..4d8eeffdbf8 100644 --- a/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/Models/User.swift +++ b/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/Models/User.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif /** A User who is purchasing from the pet store */ public struct User: Codable, Hashable { @@ -31,6 +33,7 @@ public struct User: Codable, Hashable { self.phone = phone self.userStatus = userStatus } + public enum CodingKeys: String, CodingKey, CaseIterable { case id case username @@ -55,7 +58,5 @@ public struct User: Codable, Hashable { try container.encodeIfPresent(phone, forKey: .phone) try container.encodeIfPresent(userStatus, forKey: .userStatus) } - - - } + 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 52b2071ec1a..41959190a26 100644 --- a/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift +++ b/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift @@ -93,14 +93,14 @@ open class URLSessionRequestBuilder: RequestBuilder { return modifiedRequest } - override open func execute(_ apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, _ completion: @escaping (_ result: Swift.Result, Error>) -> Void) { + override open func execute(_ apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, _ completion: @escaping (_ result: Swift.Result, Error>) -> Void) { let urlSessionId = UUID().uuidString // Create a new manager for each request to customize its request header let urlSession = createURLSession() urlSessionStore[urlSessionId] = urlSession guard let xMethod = HTTPMethod(rawValue: method) else { - fatalError("Unsuported Http method - \(method)") + fatalError("Unsupported Http method - \(method)") } let encoding: ParameterEncoding @@ -119,7 +119,7 @@ open class URLSessionRequestBuilder: RequestBuilder { } else if contentType == "application/x-www-form-urlencoded" { encoding = FormURLEncoding() } else { - fatalError("Unsuported Media Type - \(contentType)") + fatalError("Unsupported Media Type - \(contentType)") } } @@ -205,16 +205,18 @@ open class URLSessionRequestBuilder: RequestBuilder { } let fileManager = FileManager.default - let documentsDirectory = fileManager.urls(for: .documentDirectory, in: .userDomainMask)[0] + let cachesDirectory = fileManager.urls(for: .cachesDirectory, in: .userDomainMask)[0] let requestURL = try getURL(from: urlRequest) var requestPath = try getPath(from: requestURL) if let headerFileName = getFileName(fromContentDisposition: httpResponse.allHeaderFields["Content-Disposition"] as? String) { requestPath = requestPath.appending("/\(headerFileName)") + } else { + requestPath = requestPath.appending("/tmp.PetstoreClient.\(UUID().uuidString)") } - let filePath = documentsDirectory.appendingPathComponent(requestPath) + let filePath = cachesDirectory.appendingPathComponent(requestPath) let directoryPath = filePath.deletingLastPathComponent().path try fileManager.createDirectory(atPath: directoryPath, withIntermediateDirectories: true, attributes: nil) @@ -232,6 +234,10 @@ open class URLSessionRequestBuilder: RequestBuilder { completion(.success(Response(response: httpResponse, body: nil))) + case is Data.Type: + + completion(.success(Response(response: httpResponse, body: data as? T))) + default: completion(.success(Response(response: httpResponse, body: data as? T))) @@ -244,7 +250,7 @@ open class URLSessionRequestBuilder: RequestBuilder { for (key, value) in headers { httpHeaders[key] = value } - for (key, value) in PetstoreClientAPI.customHeaders { + for (key, value) in PetstoreClient.customHeaders { httpHeaders[key] = value } return httpHeaders @@ -328,6 +334,43 @@ open class URLSessionDecodableRequestBuilder: URLSessionRequestBui completion(.success(Response(response: httpResponse, body: body as? T))) + case is URL.Type: + do { + + guard error == nil else { + throw DownloadException.responseFailed + } + + guard let data = data else { + throw DownloadException.responseDataMissing + } + + let fileManager = FileManager.default + let cachesDirectory = fileManager.urls(for: .cachesDirectory, in: .userDomainMask)[0] + let requestURL = try getURL(from: urlRequest) + + var requestPath = try getPath(from: requestURL) + + if let headerFileName = getFileName(fromContentDisposition: httpResponse.allHeaderFields["Content-Disposition"] as? String) { + requestPath = requestPath.appending("/\(headerFileName)") + } else { + requestPath = requestPath.appending("/tmp.PetstoreClient.\(UUID().uuidString)") + } + + let filePath = cachesDirectory.appendingPathComponent(requestPath) + let directoryPath = filePath.deletingLastPathComponent().path + + try fileManager.createDirectory(atPath: directoryPath, withIntermediateDirectories: true, attributes: nil) + try data.write(to: filePath, options: .atomic) + + completion(.success(Response(response: httpResponse, body: filePath as? T))) + + } catch let requestParserError as DownloadException { + completion(.failure(ErrorResponse.error(400, data, response, requestParserError))) + } catch { + completion(.failure(ErrorResponse.error(400, data, response, error))) + } + case is Void.Type: completion(.success(Response(response: httpResponse, body: nil))) diff --git a/samples/client/petstore/swift5/deprecated/project.yml b/samples/client/petstore/swift5/deprecated/project.yml index 5528eeee513..0493cf65896 100644 --- a/samples/client/petstore/swift5/deprecated/project.yml +++ b/samples/client/petstore/swift5/deprecated/project.yml @@ -11,5 +11,5 @@ targets: settings: APPLICATION_EXTENSION_API_ONLY: true scheme: {} - + dependencies: - carthage: AnyCodable diff --git a/samples/client/petstore/swift5/nonPublicApi/.gitignore b/samples/client/petstore/swift5/nonPublicApi/.gitignore index 5e5d5cebcf4..627d360a903 100644 --- a/samples/client/petstore/swift5/nonPublicApi/.gitignore +++ b/samples/client/petstore/swift5/nonPublicApi/.gitignore @@ -1,12 +1,22 @@ +# Created by https://www.toptal.com/developers/gitignore/api/swift,xcode +# Edit at https://www.toptal.com/developers/gitignore?templates=swift,xcode + +### Swift ### # Xcode # # gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore -## Build generated -build/ -DerivedData +## User settings +xcuserdata/ -## Various settings +## compatibility with Xcode 8 and earlier (ignoring not required starting Xcode 9) +*.xcscmblueprint +*.xccheckout + +## compatibility with Xcode 3 and earlier (ignoring not required starting Xcode 4) +build/ +DerivedData/ +*.moved-aside *.pbxuser !default.pbxuser *.mode1v3 @@ -15,49 +25,81 @@ DerivedData !default.mode2v3 *.perspectivev3 !default.perspectivev3 -xcuserdata - -## Other -*.xccheckout -*.moved-aside -*.xcuserstate -*.xcscmblueprint ## Obj-C/Swift specific *.hmap + +## App packaging *.ipa +*.dSYM.zip +*.dSYM ## Playgrounds timeline.xctimeline playground.xcworkspace # Swift Package Manager -# # Add this line if you want to avoid checking in source code from Swift Package Manager dependencies. # Packages/ +# Package.pins +# Package.resolved +# *.xcodeproj +# Xcode automatically generates this directory with a .xcworkspacedata file and xcuserdata +# hence it is not needed unless you have added a package configuration file to your project +# .swiftpm + .build/ # CocoaPods -# # We recommend against adding the Pods directory to your .gitignore. However # you should judge for yourself, the pros and cons are mentioned at: # https://guides.cocoapods.org/using/using-cocoapods.html#should-i-check-the-pods-directory-into-source-control -# # Pods/ +# Add this line if you want to avoid checking in source code from the Xcode workspace +# *.xcworkspace # Carthage -# # Add this line if you want to avoid checking in source code from Carthage dependencies. # Carthage/Checkouts -Carthage/Build +Carthage/Build/ + +# Add this lines if you are using Accio dependency management (Deprecated since Xcode 12) +# Dependencies/ +# .accio/ # fastlane -# -# It is recommended to not store the screenshots in the git repo. Instead, use fastlane to re-generate the -# screenshots whenever they are needed. +# It is recommended to not store the screenshots in the git repo. +# Instead, use fastlane to re-generate the screenshots whenever they are needed. # For more information about the recommended setup visit: -# https://github.com/fastlane/fastlane/blob/master/docs/Gitignore.md +# https://docs.fastlane.tools/best-practices/source-control/#source-control fastlane/report.xml -fastlane/screenshots +fastlane/Preview.html +fastlane/screenshots/**/*.png +fastlane/test_output + +# Code Injection +# After new code Injection tools there's a generated folder /iOSInjectionProject +# https://github.com/johnno1962/injectionforxcode + +iOSInjectionProject/ + +### Xcode ### +# Xcode +# gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore + + + + +## Gcc Patch +/*.gcno + +### Xcode Patch ### +*.xcodeproj/* +!*.xcodeproj/project.pbxproj +!*.xcodeproj/xcshareddata/ +!*.xcworkspace/contents.xcworkspacedata +**/xcshareddata/WorkspaceSettings.xcsettings + +# End of https://www.toptal.com/developers/gitignore/api/swift,xcode diff --git a/samples/client/petstore/swift5/nonPublicApi/.openapi-generator/VERSION b/samples/client/petstore/swift5/nonPublicApi/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/client/petstore/swift5/nonPublicApi/.openapi-generator/VERSION +++ b/samples/client/petstore/swift5/nonPublicApi/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/client/petstore/swift5/nonPublicApi/Cartfile b/samples/client/petstore/swift5/nonPublicApi/Cartfile index 84aaa61ef2d..a6a6bcacb1d 100644 --- a/samples/client/petstore/swift5/nonPublicApi/Cartfile +++ b/samples/client/petstore/swift5/nonPublicApi/Cartfile @@ -1,2 +1,2 @@ -github "Flight-School/AnyCodable" ~> 0.4.0 +github "Flight-School/AnyCodable" ~> 0.6.1 diff --git a/samples/client/petstore/swift5/nonPublicApi/Package.resolved b/samples/client/petstore/swift5/nonPublicApi/Package.resolved new file mode 100644 index 00000000000..79610c3b3b3 --- /dev/null +++ b/samples/client/petstore/swift5/nonPublicApi/Package.resolved @@ -0,0 +1,16 @@ +{ + "object": { + "pins": [ + { + "package": "AnyCodable", + "repositoryURL": "https://github.com/Flight-School/AnyCodable", + "state": { + "branch": null, + "revision": "69261f239f0fffaf51495dadc4f8483fbfe97025", + "version": "0.6.1" + } + } + ] + }, + "version": 1 +} diff --git a/samples/client/petstore/swift5/nonPublicApi/Package.swift b/samples/client/petstore/swift5/nonPublicApi/Package.swift index b724838fe8d..87bb775fb72 100644 --- a/samples/client/petstore/swift5/nonPublicApi/Package.swift +++ b/samples/client/petstore/swift5/nonPublicApi/Package.swift @@ -19,7 +19,7 @@ let package = Package( ], dependencies: [ // Dependencies declare other packages that this package depends on. - .package(url: "https://github.com/Flight-School/AnyCodable", .exact("0.4.0")), + .package(url: "https://github.com/Flight-School/AnyCodable", from: "0.6.1"), ], targets: [ // Targets are the basic building blocks of a package. A target can define a module or a test suite. diff --git a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient.podspec b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient.podspec index de06558efbd..0e6bf7ec024 100644 --- a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient.podspec +++ b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient.podspec @@ -11,5 +11,5 @@ Pod::Spec.new do |s| s.homepage = 'https://github.com/openapitools/openapi-generator' s.summary = 'PetstoreClient' s.source_files = 'PetstoreClient/Classes/**/*.swift' - s.dependency 'AnyCodable-FlightSchool', '~> 0.4.0' + s.dependency 'AnyCodable-FlightSchool', '~> 0.6.1' end diff --git a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs.swift b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs.swift index 026f2295d31..a4d2c1877f1 100644 --- a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs.swift +++ b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs.swift @@ -6,10 +6,13 @@ import Foundation -internal class PetstoreClientAPI { +@available(*, deprecated, renamed: "PetstoreClient") +internal typealias PetstoreClientAPI = PetstoreClient + +internal class PetstoreClient { internal static var basePath = "http://petstore.swagger.io:80/v2" - internal static var credential: URLCredential? internal static var customHeaders: [String: String] = [:] + internal static var credential: URLCredential? internal static var requestBuilderFactory: RequestBuilderFactory = URLSessionRequestBuilderFactory() internal static var apiResponseQueue: DispatchQueue = .main } @@ -32,7 +35,7 @@ internal class RequestBuilder { self.parameters = parameters self.headers = headers - addHeaders(PetstoreClientAPI.customHeaders) + addHeaders(PetstoreClient.customHeaders) } internal func addHeaders(_ aHeaders: [String: String]) { @@ -41,7 +44,7 @@ internal class RequestBuilder { } } - internal func execute(_ apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, _ completion: @escaping (_ result: Swift.Result, Error>) -> Void) { } + internal func execute(_ apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, _ completion: @escaping (_ result: Swift.Result, Error>) -> Void) { } internal func addHeader(name: String, value: String) -> Self { if !value.isEmpty { @@ -51,7 +54,7 @@ internal class RequestBuilder { } internal func addCredential() -> Self { - credential = PetstoreClientAPI.credential + credential = PetstoreClient.credential return self } } 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 18a502d453b..34779f80996 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 @@ -6,8 +6,12 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif internal class AnotherFakeAPI { + /** To test special tags @@ -15,7 +19,7 @@ internal class AnotherFakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - internal class func call123testSpecialTags(body: Client, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Client?, _ error: Error?) -> Void)) { + internal class func call123testSpecialTags(body: Client, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Client?, _ error: Error?) -> Void)) { call123testSpecialTagsWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -34,21 +38,20 @@ internal class AnotherFakeAPI { - returns: RequestBuilder */ internal class func call123testSpecialTagsWithRequestBuilder(body: Client) -> RequestBuilder { - let path = "/another-fake/dummy" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/another-fake/dummy" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "PATCH", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "PATCH", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } - } 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 99317dab507..227724b50cb 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 @@ -6,15 +6,19 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif internal class FakeAPI { + /** - parameter body: (body) Input boolean as post body (optional) - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - internal class func fakeOuterBooleanSerialize(body: Bool? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Bool?, _ error: Error?) -> Void)) { + internal class func fakeOuterBooleanSerialize(body: Bool? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Bool?, _ error: Error?) -> Void)) { fakeOuterBooleanSerializeWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -32,21 +36,21 @@ internal class FakeAPI { - returns: RequestBuilder */ internal class func fakeOuterBooleanSerializeWithRequestBuilder(body: Bool? = nil) -> RequestBuilder { - let path = "/fake/outer/boolean" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/fake/outer/boolean" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -55,7 +59,7 @@ internal class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - internal class func fakeOuterCompositeSerialize(body: OuterComposite? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: OuterComposite?, _ error: Error?) -> Void)) { + internal class func fakeOuterCompositeSerialize(body: OuterComposite? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: OuterComposite?, _ error: Error?) -> Void)) { fakeOuterCompositeSerializeWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -73,21 +77,21 @@ internal class FakeAPI { - returns: RequestBuilder */ internal class func fakeOuterCompositeSerializeWithRequestBuilder(body: OuterComposite? = nil) -> RequestBuilder { - let path = "/fake/outer/composite" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/fake/outer/composite" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -96,7 +100,7 @@ internal class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - internal class func fakeOuterNumberSerialize(body: Double? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Double?, _ error: Error?) -> Void)) { + internal class func fakeOuterNumberSerialize(body: Double? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Double?, _ error: Error?) -> Void)) { fakeOuterNumberSerializeWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -114,21 +118,21 @@ internal class FakeAPI { - returns: RequestBuilder */ internal class func fakeOuterNumberSerializeWithRequestBuilder(body: Double? = nil) -> RequestBuilder { - let path = "/fake/outer/number" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/fake/outer/number" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -137,7 +141,7 @@ internal class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - internal class func fakeOuterStringSerialize(body: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: String?, _ error: Error?) -> Void)) { + internal class func fakeOuterStringSerialize(body: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: String?, _ error: Error?) -> Void)) { fakeOuterStringSerializeWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -155,21 +159,21 @@ internal class FakeAPI { - returns: RequestBuilder */ internal class func fakeOuterStringSerializeWithRequestBuilder(body: String? = nil) -> RequestBuilder { - let path = "/fake/outer/string" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/fake/outer/string" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -178,7 +182,7 @@ internal class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - internal class func testBodyWithFileSchema(body: FileSchemaTestClass, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + internal class func testBodyWithFileSchema(body: FileSchemaTestClass, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { testBodyWithFileSchemaWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -196,21 +200,21 @@ internal class FakeAPI { - returns: RequestBuilder */ internal class func testBodyWithFileSchemaWithRequestBuilder(body: FileSchemaTestClass) -> RequestBuilder { - let path = "/fake/body-with-file-schema" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/fake/body-with-file-schema" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "PUT", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -220,7 +224,7 @@ internal class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - internal class func testBodyWithQueryParams(query: String, body: User, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + internal class func testBodyWithQueryParams(query: String, body: User, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { testBodyWithQueryParamsWithRequestBuilder(query: query, body: body).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -238,24 +242,24 @@ internal class FakeAPI { - returns: RequestBuilder */ internal class func testBodyWithQueryParamsWithRequestBuilder(query: String, body: User) -> RequestBuilder { - let path = "/fake/body-with-query-params" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/fake/body-with-query-params" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - var urlComponents = URLComponents(string: URLString) - urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ + var localVariableUrlComponents = URLComponents(string: localVariableURLString) + localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ "query": query.encodeToJSON(), ]) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "PUT", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -265,7 +269,7 @@ internal class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - internal class func testClientModel(body: Client, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Client?, _ error: Error?) -> Void)) { + internal class func testClientModel(body: Client, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Client?, _ error: Error?) -> Void)) { testClientModelWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -284,21 +288,21 @@ internal class FakeAPI { - returns: RequestBuilder */ internal class func testClientModelWithRequestBuilder(body: Client) -> RequestBuilder { - let path = "/fake" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/fake" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "PATCH", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "PATCH", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -321,7 +325,7 @@ internal class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - internal class func testEndpointParameters(integer: Int? = nil, int32: Int? = nil, int64: Int64? = nil, number: Double, float: Float? = nil, double: Double, string: String? = nil, patternWithoutDelimiter: String, byte: Data, binary: URL? = nil, date: Date? = nil, dateTime: Date? = nil, password: String? = nil, callback: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + internal class func testEndpointParameters(integer: Int? = nil, int32: Int? = nil, int64: Int64? = nil, number: Double, float: Float? = nil, double: Double, string: String? = nil, patternWithoutDelimiter: String, byte: Data, binary: URL? = nil, date: Date? = nil, dateTime: Date? = nil, password: String? = nil, callback: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { testEndpointParametersWithRequestBuilder(integer: integer, int32: int32, int64: int64, number: number, float: float, double: double, string: string, patternWithoutDelimiter: patternWithoutDelimiter, byte: byte, binary: binary, date: date, dateTime: dateTime, password: password, callback: callback).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -356,9 +360,9 @@ internal class FakeAPI { - returns: RequestBuilder */ internal class func testEndpointParametersWithRequestBuilder(integer: Int? = nil, int32: Int? = nil, int64: Int64? = nil, number: Double, float: Float? = nil, double: Double, string: String? = nil, patternWithoutDelimiter: String, byte: Data, binary: URL? = nil, date: Date? = nil, dateTime: Date? = nil, password: String? = nil, callback: String? = nil) -> RequestBuilder { - let path = "/fake" - let URLString = PetstoreClientAPI.basePath + path - let formParams: [String: Any?] = [ + let localVariablePath = "/fake" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableFormParams: [String: Any?] = [ "integer": integer?.encodeToJSON(), "int32": int32?.encodeToJSON(), "int64": int64?.encodeToJSON(), @@ -375,20 +379,20 @@ internal class FakeAPI { "callback": callback?.encodeToJSON(), ] - let nonNullParameters = APIHelper.rejectNil(formParams) - let parameters = APIHelper.convertBoolToString(nonNullParameters) + let localVariableNonNullParameters = APIHelper.rejectNil(localVariableFormParams) + let localVariableParameters = APIHelper.convertBoolToString(localVariableNonNullParameters) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ "Content-Type": "application/x-www-form-urlencoded", ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -472,7 +476,7 @@ internal class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - internal class func testEnumParameters(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + internal class func testEnumParameters(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { testEnumParametersWithRequestBuilder(enumHeaderStringArray: enumHeaderStringArray, enumHeaderString: enumHeaderString, enumQueryStringArray: enumQueryStringArray, enumQueryString: enumQueryString, enumQueryInteger: enumQueryInteger, enumQueryDouble: enumQueryDouble, enumFormStringArray: enumFormStringArray, enumFormString: enumFormString).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -498,35 +502,35 @@ internal class FakeAPI { - returns: RequestBuilder */ internal class func testEnumParametersWithRequestBuilder(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil) -> RequestBuilder { - let path = "/fake" - let URLString = PetstoreClientAPI.basePath + path - let formParams: [String: Any?] = [ + let localVariablePath = "/fake" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableFormParams: [String: Any?] = [ "enum_form_string_array": enumFormStringArray?.encodeToJSON(), "enum_form_string": enumFormString?.encodeToJSON(), ] - let nonNullParameters = APIHelper.rejectNil(formParams) - let parameters = APIHelper.convertBoolToString(nonNullParameters) + let localVariableNonNullParameters = APIHelper.rejectNil(localVariableFormParams) + let localVariableParameters = APIHelper.convertBoolToString(localVariableNonNullParameters) - var urlComponents = URLComponents(string: URLString) - urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ + var localVariableUrlComponents = URLComponents(string: localVariableURLString) + localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ "enum_query_string_array": enumQueryStringArray?.encodeToJSON(), "enum_query_string": enumQueryString?.encodeToJSON(), "enum_query_integer": enumQueryInteger?.encodeToJSON(), "enum_query_double": enumQueryDouble?.encodeToJSON(), ]) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ "Content-Type": "application/x-www-form-urlencoded", "enum_header_string_array": enumHeaderStringArray?.encodeToJSON(), "enum_header_string": enumHeaderString?.encodeToJSON(), ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -541,7 +545,7 @@ internal class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - internal class func testGroupParameters(requiredStringGroup: Int, requiredBooleanGroup: Bool, requiredInt64Group: Int64, stringGroup: Int? = nil, booleanGroup: Bool? = nil, int64Group: Int64? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + internal class func testGroupParameters(requiredStringGroup: Int, requiredBooleanGroup: Bool, requiredInt64Group: Int64, stringGroup: Int? = nil, booleanGroup: Bool? = nil, int64Group: Int64? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { testGroupParametersWithRequestBuilder(requiredStringGroup: requiredStringGroup, requiredBooleanGroup: requiredBooleanGroup, requiredInt64Group: requiredInt64Group, stringGroup: stringGroup, booleanGroup: booleanGroup, int64Group: int64Group).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -565,28 +569,28 @@ internal class FakeAPI { - returns: RequestBuilder */ internal class func testGroupParametersWithRequestBuilder(requiredStringGroup: Int, requiredBooleanGroup: Bool, requiredInt64Group: Int64, stringGroup: Int? = nil, booleanGroup: Bool? = nil, int64Group: Int64? = nil) -> RequestBuilder { - let path = "/fake" - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + let localVariablePath = "/fake" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - var urlComponents = URLComponents(string: URLString) - urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ + var localVariableUrlComponents = URLComponents(string: localVariableURLString) + localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ "required_string_group": requiredStringGroup.encodeToJSON(), "required_int64_group": requiredInt64Group.encodeToJSON(), "string_group": stringGroup?.encodeToJSON(), "int64_group": int64Group?.encodeToJSON(), ]) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ "required_boolean_group": requiredBooleanGroup.encodeToJSON(), "boolean_group": booleanGroup?.encodeToJSON(), ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "DELETE", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -596,7 +600,7 @@ internal class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - internal class func testInlineAdditionalProperties(param: [String: String], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + internal class func testInlineAdditionalProperties(param: [String: String], apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { testInlineAdditionalPropertiesWithRequestBuilder(param: param).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -614,21 +618,21 @@ internal class FakeAPI { - returns: RequestBuilder */ internal class func testInlineAdditionalPropertiesWithRequestBuilder(param: [String: String]) -> RequestBuilder { - let path = "/fake/inline-additionalProperties" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: param) + let localVariablePath = "/fake/inline-additionalProperties" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: param) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -639,7 +643,7 @@ internal class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - internal class func testJsonFormData(param: String, param2: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + internal class func testJsonFormData(param: String, param2: String, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { testJsonFormDataWithRequestBuilder(param: param, param2: param2).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -658,27 +662,26 @@ internal class FakeAPI { - returns: RequestBuilder */ internal class func testJsonFormDataWithRequestBuilder(param: String, param2: String) -> RequestBuilder { - let path = "/fake/jsonFormData" - let URLString = PetstoreClientAPI.basePath + path - let formParams: [String: Any?] = [ + let localVariablePath = "/fake/jsonFormData" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableFormParams: [String: Any?] = [ "param": param.encodeToJSON(), "param2": param2.encodeToJSON(), ] - let nonNullParameters = APIHelper.rejectNil(formParams) - let parameters = APIHelper.convertBoolToString(nonNullParameters) + let localVariableNonNullParameters = APIHelper.rejectNil(localVariableFormParams) + let localVariableParameters = APIHelper.convertBoolToString(localVariableNonNullParameters) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ "Content-Type": "application/x-www-form-urlencoded", ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } - } 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 5a85c1b2929..61e190bec70 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 @@ -6,8 +6,12 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif internal class FakeClassnameTags123API { + /** To test class name in snake case @@ -15,7 +19,7 @@ internal class FakeClassnameTags123API { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - internal class func testClassname(body: Client, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Client?, _ error: Error?) -> Void)) { + internal class func testClassname(body: Client, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Client?, _ error: Error?) -> Void)) { testClassnameWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -37,21 +41,20 @@ internal class FakeClassnameTags123API { - returns: RequestBuilder */ internal class func testClassnameWithRequestBuilder(body: Client) -> RequestBuilder { - let path = "/fake_classname_test" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/fake_classname_test" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "PATCH", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "PATCH", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } - } 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 ab2066aa50c..0d583238fda 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 @@ -6,8 +6,12 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif internal class PetAPI { + /** Add a new pet to the store @@ -15,7 +19,7 @@ internal class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - internal class func addPet(body: Pet, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + internal class func addPet(body: Pet, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { addPetWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -36,21 +40,21 @@ internal class PetAPI { - returns: RequestBuilder */ internal class func addPetWithRequestBuilder(body: Pet) -> RequestBuilder { - let path = "/pet" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/pet" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -61,7 +65,7 @@ internal class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - internal class func deletePet(apiKey: String? = nil, petId: Int64, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + internal class func deletePet(apiKey: String? = nil, petId: Int64, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { deletePetWithRequestBuilder(apiKey: apiKey, petId: petId).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -83,24 +87,24 @@ internal class PetAPI { - returns: RequestBuilder */ internal class func deletePetWithRequestBuilder(apiKey: String? = nil, petId: Int64) -> RequestBuilder { - var path = "/pet/{petId}" + var localVariablePath = "/pet/{petId}" let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))" let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" - path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + localVariablePath = localVariablePath.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ "api_key": apiKey?.encodeToJSON(), ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "DELETE", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -119,7 +123,7 @@ internal class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - internal class func findPetsByStatus(status: [String], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: [Pet]?, _ error: Error?) -> Void)) { + internal class func findPetsByStatus(status: [String], apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: [Pet]?, _ error: Error?) -> Void)) { findPetsByStatusWithRequestBuilder(status: status).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -141,24 +145,24 @@ internal class PetAPI { - returns: RequestBuilder<[Pet]> */ internal class func findPetsByStatusWithRequestBuilder(status: [String]) -> RequestBuilder<[Pet]> { - let path = "/pet/findByStatus" - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + let localVariablePath = "/pet/findByStatus" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - var urlComponents = URLComponents(string: URLString) - urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ + var localVariableUrlComponents = URLComponents(string: localVariableURLString) + localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ "status": status.encodeToJSON(), ]) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -169,7 +173,7 @@ internal class PetAPI { - parameter completion: completion handler to receive the data and the error objects */ @available(*, deprecated, message: "This operation is deprecated.") - internal class func findPetsByTags(tags: [String], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: [Pet]?, _ error: Error?) -> Void)) { + internal class func findPetsByTags(tags: [String], apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: [Pet]?, _ error: Error?) -> Void)) { findPetsByTagsWithRequestBuilder(tags: tags).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -192,24 +196,24 @@ internal class PetAPI { */ @available(*, deprecated, message: "This operation is deprecated.") internal class func findPetsByTagsWithRequestBuilder(tags: [String]) -> RequestBuilder<[Pet]> { - let path = "/pet/findByTags" - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + let localVariablePath = "/pet/findByTags" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - var urlComponents = URLComponents(string: URLString) - urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ + var localVariableUrlComponents = URLComponents(string: localVariableURLString) + localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ "tags": tags.encodeToJSON(), ]) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -219,7 +223,7 @@ internal class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - internal class func getPetById(petId: Int64, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Pet?, _ error: Error?) -> Void)) { + internal class func getPetById(petId: Int64, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Pet?, _ error: Error?) -> Void)) { getPetByIdWithRequestBuilder(petId: petId).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -241,24 +245,24 @@ internal class PetAPI { - returns: RequestBuilder */ internal class func getPetByIdWithRequestBuilder(petId: Int64) -> RequestBuilder { - var path = "/pet/{petId}" + var localVariablePath = "/pet/{petId}" let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))" let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" - path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + localVariablePath = localVariablePath.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -268,7 +272,7 @@ internal class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - internal class func updatePet(body: Pet, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + internal class func updatePet(body: Pet, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { updatePetWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -289,21 +293,21 @@ internal class PetAPI { - returns: RequestBuilder */ internal class func updatePetWithRequestBuilder(body: Pet) -> RequestBuilder { - let path = "/pet" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/pet" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "PUT", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -315,7 +319,7 @@ internal class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - internal class func updatePetWithForm(petId: Int64, name: String? = nil, status: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + internal class func updatePetWithForm(petId: Int64, name: String? = nil, status: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { updatePetWithFormWithRequestBuilder(petId: petId, name: name, status: status).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -338,30 +342,30 @@ internal class PetAPI { - returns: RequestBuilder */ internal class func updatePetWithFormWithRequestBuilder(petId: Int64, name: String? = nil, status: String? = nil) -> RequestBuilder { - var path = "/pet/{petId}" + var localVariablePath = "/pet/{petId}" let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))" let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" - path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path - let formParams: [String: Any?] = [ + localVariablePath = localVariablePath.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableFormParams: [String: Any?] = [ "name": name?.encodeToJSON(), "status": status?.encodeToJSON(), ] - let nonNullParameters = APIHelper.rejectNil(formParams) - let parameters = APIHelper.convertBoolToString(nonNullParameters) + let localVariableNonNullParameters = APIHelper.rejectNil(localVariableFormParams) + let localVariableParameters = APIHelper.convertBoolToString(localVariableNonNullParameters) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ "Content-Type": "application/x-www-form-urlencoded", ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -373,7 +377,7 @@ internal class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - internal class func uploadFile(petId: Int64, additionalMetadata: String? = nil, file: URL? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: ApiResponse?, _ error: Error?) -> Void)) { + internal class func uploadFile(petId: Int64, additionalMetadata: String? = nil, file: URL? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: ApiResponse?, _ error: Error?) -> Void)) { uploadFileWithRequestBuilder(petId: petId, additionalMetadata: additionalMetadata, file: file).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -396,30 +400,30 @@ internal class PetAPI { - returns: RequestBuilder */ internal class func uploadFileWithRequestBuilder(petId: Int64, additionalMetadata: String? = nil, file: URL? = nil) -> RequestBuilder { - var path = "/pet/{petId}/uploadImage" + var localVariablePath = "/pet/{petId}/uploadImage" let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))" let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" - path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path - let formParams: [String: Any?] = [ + localVariablePath = localVariablePath.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableFormParams: [String: Any?] = [ "additionalMetadata": additionalMetadata?.encodeToJSON(), "file": file?.encodeToJSON(), ] - let nonNullParameters = APIHelper.rejectNil(formParams) - let parameters = APIHelper.convertBoolToString(nonNullParameters) + let localVariableNonNullParameters = APIHelper.rejectNil(localVariableFormParams) + let localVariableParameters = APIHelper.convertBoolToString(localVariableNonNullParameters) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ "Content-Type": "multipart/form-data", ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -431,7 +435,7 @@ internal class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - internal class func uploadFileWithRequiredFile(petId: Int64, additionalMetadata: String? = nil, requiredFile: URL, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: ApiResponse?, _ error: Error?) -> Void)) { + internal class func uploadFileWithRequiredFile(petId: Int64, additionalMetadata: String? = nil, requiredFile: URL, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: ApiResponse?, _ error: Error?) -> Void)) { uploadFileWithRequiredFileWithRequestBuilder(petId: petId, additionalMetadata: additionalMetadata, requiredFile: requiredFile).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -454,30 +458,29 @@ internal class PetAPI { - returns: RequestBuilder */ internal class func uploadFileWithRequiredFileWithRequestBuilder(petId: Int64, additionalMetadata: String? = nil, requiredFile: URL) -> RequestBuilder { - var path = "/fake/{petId}/uploadImageWithRequiredFile" + var localVariablePath = "/fake/{petId}/uploadImageWithRequiredFile" let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))" let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" - path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path - let formParams: [String: Any?] = [ + localVariablePath = localVariablePath.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableFormParams: [String: Any?] = [ "additionalMetadata": additionalMetadata?.encodeToJSON(), "requiredFile": requiredFile.encodeToJSON(), ] - let nonNullParameters = APIHelper.rejectNil(formParams) - let parameters = APIHelper.convertBoolToString(nonNullParameters) + let localVariableNonNullParameters = APIHelper.rejectNil(localVariableFormParams) + let localVariableParameters = APIHelper.convertBoolToString(localVariableNonNullParameters) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ "Content-Type": "multipart/form-data", ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } - } diff --git a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift index 49812742b01..e29c10d4161 100644 --- a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift +++ b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift @@ -6,8 +6,12 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif internal class StoreAPI { + /** Delete purchase order by ID @@ -15,7 +19,7 @@ internal class StoreAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - internal class func deleteOrder(orderId: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + internal class func deleteOrder(orderId: String, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { deleteOrderWithRequestBuilder(orderId: orderId).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -34,24 +38,24 @@ internal class StoreAPI { - returns: RequestBuilder */ internal class func deleteOrderWithRequestBuilder(orderId: String) -> RequestBuilder { - var path = "/store/order/{order_id}" + var localVariablePath = "/store/order/{order_id}" let orderIdPreEscape = "\(APIHelper.mapValueToPathItem(orderId))" let orderIdPostEscape = orderIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" - path = path.replacingOccurrences(of: "{order_id}", with: orderIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + localVariablePath = localVariablePath.replacingOccurrences(of: "{order_id}", with: orderIdPostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "DELETE", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -60,7 +64,7 @@ internal class StoreAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - internal class func getInventory(apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: [String: Int]?, _ error: Error?) -> Void)) { + internal class func getInventory(apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: [String: Int]?, _ error: Error?) -> Void)) { getInventoryWithRequestBuilder().execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -81,21 +85,21 @@ internal class StoreAPI { - returns: RequestBuilder<[String: Int]> */ internal class func getInventoryWithRequestBuilder() -> RequestBuilder<[String: Int]> { - let path = "/store/inventory" - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + let localVariablePath = "/store/inventory" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder<[String: Int]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder<[String: Int]>.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -105,7 +109,7 @@ internal class StoreAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - internal class func getOrderById(orderId: Int64, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Order?, _ error: Error?) -> Void)) { + internal class func getOrderById(orderId: Int64, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Order?, _ error: Error?) -> Void)) { getOrderByIdWithRequestBuilder(orderId: orderId).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -124,24 +128,24 @@ internal class StoreAPI { - returns: RequestBuilder */ internal class func getOrderByIdWithRequestBuilder(orderId: Int64) -> RequestBuilder { - var path = "/store/order/{order_id}" + var localVariablePath = "/store/order/{order_id}" let orderIdPreEscape = "\(APIHelper.mapValueToPathItem(orderId))" let orderIdPostEscape = orderIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" - path = path.replacingOccurrences(of: "{order_id}", with: orderIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + localVariablePath = localVariablePath.replacingOccurrences(of: "{order_id}", with: orderIdPostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -151,7 +155,7 @@ internal class StoreAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - internal class func placeOrder(body: Order, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Order?, _ error: Error?) -> Void)) { + internal class func placeOrder(body: Order, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Order?, _ error: Error?) -> Void)) { placeOrderWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -169,21 +173,20 @@ internal class StoreAPI { - returns: RequestBuilder */ internal class func placeOrderWithRequestBuilder(body: Order) -> RequestBuilder { - let path = "/store/order" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/store/order" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } - } diff --git a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift index 2a1babfaa48..9d8fcd3324c 100644 --- a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift +++ b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift @@ -6,8 +6,12 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif internal class UserAPI { + /** Create user @@ -15,7 +19,7 @@ internal class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - internal class func createUser(body: User, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + internal class func createUser(body: User, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { createUserWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -34,21 +38,21 @@ internal class UserAPI { - returns: RequestBuilder */ internal class func createUserWithRequestBuilder(body: User) -> RequestBuilder { - let path = "/user" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/user" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -58,7 +62,7 @@ internal class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - internal class func createUsersWithArrayInput(body: [User], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + internal class func createUsersWithArrayInput(body: [User], apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { createUsersWithArrayInputWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -76,21 +80,21 @@ internal class UserAPI { - returns: RequestBuilder */ internal class func createUsersWithArrayInputWithRequestBuilder(body: [User]) -> RequestBuilder { - let path = "/user/createWithArray" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/user/createWithArray" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -100,7 +104,7 @@ internal class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - internal class func createUsersWithListInput(body: [User], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + internal class func createUsersWithListInput(body: [User], apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { createUsersWithListInputWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -118,21 +122,21 @@ internal class UserAPI { - returns: RequestBuilder */ internal class func createUsersWithListInputWithRequestBuilder(body: [User]) -> RequestBuilder { - let path = "/user/createWithList" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/user/createWithList" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -142,7 +146,7 @@ internal class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - internal class func deleteUser(username: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + internal class func deleteUser(username: String, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { deleteUserWithRequestBuilder(username: username).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -161,24 +165,24 @@ internal class UserAPI { - returns: RequestBuilder */ internal class func deleteUserWithRequestBuilder(username: String) -> RequestBuilder { - var path = "/user/{username}" + var localVariablePath = "/user/{username}" let usernamePreEscape = "\(APIHelper.mapValueToPathItem(username))" let usernamePostEscape = usernamePreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" - path = path.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + localVariablePath = localVariablePath.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "DELETE", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -188,7 +192,7 @@ internal class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - internal class func getUserByName(username: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: User?, _ error: Error?) -> Void)) { + internal class func getUserByName(username: String, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: User?, _ error: Error?) -> Void)) { getUserByNameWithRequestBuilder(username: username).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -206,24 +210,24 @@ internal class UserAPI { - returns: RequestBuilder */ internal class func getUserByNameWithRequestBuilder(username: String) -> RequestBuilder { - var path = "/user/{username}" + var localVariablePath = "/user/{username}" let usernamePreEscape = "\(APIHelper.mapValueToPathItem(username))" let usernamePostEscape = usernamePreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" - path = path.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + localVariablePath = localVariablePath.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -234,7 +238,7 @@ internal class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - internal class func loginUser(username: String, password: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: String?, _ error: Error?) -> Void)) { + internal class func loginUser(username: String, password: String, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: String?, _ error: Error?) -> Void)) { loginUserWithRequestBuilder(username: username, password: password).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -254,25 +258,25 @@ internal class UserAPI { - returns: RequestBuilder */ internal class func loginUserWithRequestBuilder(username: String, password: String) -> RequestBuilder { - let path = "/user/login" - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + let localVariablePath = "/user/login" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - var urlComponents = URLComponents(string: URLString) - urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ + var localVariableUrlComponents = URLComponents(string: localVariableURLString) + localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ "username": username.encodeToJSON(), "password": password.encodeToJSON(), ]) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -281,7 +285,7 @@ internal class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - internal class func logoutUser(apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + internal class func logoutUser(apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { logoutUserWithRequestBuilder().execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -298,21 +302,21 @@ internal class UserAPI { - returns: RequestBuilder */ internal class func logoutUserWithRequestBuilder() -> RequestBuilder { - let path = "/user/logout" - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + let localVariablePath = "/user/logout" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -323,7 +327,7 @@ internal class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - internal class func updateUser(username: String, body: User, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + internal class func updateUser(username: String, body: User, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { updateUserWithRequestBuilder(username: username, body: body).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -343,24 +347,23 @@ internal class UserAPI { - returns: RequestBuilder */ internal class func updateUserWithRequestBuilder(username: String, body: User) -> RequestBuilder { - var path = "/user/{username}" + var localVariablePath = "/user/{username}" let usernamePreEscape = "\(APIHelper.mapValueToPathItem(username))" let usernamePostEscape = usernamePreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" - path = path.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + localVariablePath = localVariablePath.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "PUT", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } - } diff --git a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Configuration.swift b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Configuration.swift index 3b39a978be4..5be96e4e203 100644 --- a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Configuration.swift +++ b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Configuration.swift @@ -7,6 +7,7 @@ import Foundation internal class Configuration { + // This value is used to configure the date formatter that is used to serialize dates into JSON format. // You must set it prior to encoding any dates, and it will only be read once. @available(*, unavailable, message: "To set a different date format, use CodableHelper.dateFormatter instead.") diff --git a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Extensions.swift b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Extensions.swift index 729a612f7e6..65ae1c6c642 100644 --- a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Extensions.swift +++ b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Extensions.swift @@ -5,7 +5,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif extension Bool: JSONEncodable { func encodeToJSON() -> Any { return self as Any } @@ -184,44 +186,3 @@ extension HTTPURLResponse { return Array(200 ..< 300).contains(statusCode) } } - -extension AnyCodable: Hashable { - public func hash(into hasher: inout Hasher) { - switch value { - case let value as Bool: - hasher.combine(value) - case let value as Int: - hasher.combine(value) - case let value as Int8: - hasher.combine(value) - case let value as Int16: - hasher.combine(value) - case let value as Int32: - hasher.combine(value) - case let value as Int64: - hasher.combine(value) - case let value as UInt: - hasher.combine(value) - case let value as UInt8: - hasher.combine(value) - case let value as UInt16: - hasher.combine(value) - case let value as UInt32: - hasher.combine(value) - case let value as UInt64: - hasher.combine(value) - case let value as Float: - hasher.combine(value) - case let value as Double: - hasher.combine(value) - case let value as String: - hasher.combine(value) - case let value as [String: AnyCodable]: - hasher.combine(value) - case let value as [AnyCodable]: - hasher.combine(value) - default: - hasher.combine(0) - } - } -} \ No newline at end of file diff --git a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesClass.swift b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesClass.swift index 675937c90fa..731b7b76eb6 100644 --- a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesClass.swift +++ b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesClass.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif internal struct AdditionalPropertiesClass: Codable, Hashable { @@ -17,6 +19,7 @@ internal struct AdditionalPropertiesClass: Codable, Hashable { self.mapString = mapString self.mapMapString = mapMapString } + internal enum CodingKeys: String, CodingKey, CaseIterable { case mapString = "map_string" case mapMapString = "map_map_string" @@ -29,7 +32,5 @@ internal struct AdditionalPropertiesClass: Codable, Hashable { try container.encodeIfPresent(mapString, forKey: .mapString) try container.encodeIfPresent(mapMapString, forKey: .mapMapString) } - - - } + diff --git a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Animal.swift b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Animal.swift index 8c8ffe45faa..b160f8c835d 100644 --- a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Animal.swift +++ b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Animal.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif internal struct Animal: Codable, Hashable { @@ -17,6 +19,7 @@ internal struct Animal: Codable, Hashable { self.className = className self.color = color } + internal enum CodingKeys: String, CodingKey, CaseIterable { case className case color @@ -29,7 +32,5 @@ internal struct Animal: Codable, Hashable { try container.encode(className, forKey: .className) try container.encodeIfPresent(color, forKey: .color) } - - - } + diff --git a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/AnimalFarm.swift b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/AnimalFarm.swift index 49ec4b6ac6e..58d2309771e 100644 --- a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/AnimalFarm.swift +++ b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/AnimalFarm.swift @@ -6,6 +6,8 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif internal typealias AnimalFarm = [Animal] diff --git a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift index 25f5c34054b..c62ce400c81 100644 --- a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift +++ b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif internal struct ApiResponse: Codable, Hashable { @@ -19,6 +21,7 @@ internal struct ApiResponse: Codable, Hashable { self.type = type self.message = message } + internal enum CodingKeys: String, CodingKey, CaseIterable { case code case type @@ -33,7 +36,5 @@ internal struct ApiResponse: Codable, Hashable { try container.encodeIfPresent(type, forKey: .type) try container.encodeIfPresent(message, forKey: .message) } - - - } + diff --git a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfArrayOfNumberOnly.swift b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfArrayOfNumberOnly.swift index 48daaaffa2f..2fa5da894c4 100644 --- a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfArrayOfNumberOnly.swift +++ b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfArrayOfNumberOnly.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif internal struct ArrayOfArrayOfNumberOnly: Codable, Hashable { @@ -15,6 +17,7 @@ internal struct ArrayOfArrayOfNumberOnly: Codable, Hashable { internal init(arrayArrayNumber: [[Double]]? = nil) { self.arrayArrayNumber = arrayArrayNumber } + internal enum CodingKeys: String, CodingKey, CaseIterable { case arrayArrayNumber = "ArrayArrayNumber" } @@ -25,7 +28,5 @@ internal struct ArrayOfArrayOfNumberOnly: Codable, Hashable { var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(arrayArrayNumber, forKey: .arrayArrayNumber) } - - - } + diff --git a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfNumberOnly.swift b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfNumberOnly.swift index b38ece08cc8..4ad2ff35d21 100644 --- a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfNumberOnly.swift +++ b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfNumberOnly.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif internal struct ArrayOfNumberOnly: Codable, Hashable { @@ -15,6 +17,7 @@ internal struct ArrayOfNumberOnly: Codable, Hashable { internal init(arrayNumber: [Double]? = nil) { self.arrayNumber = arrayNumber } + internal enum CodingKeys: String, CodingKey, CaseIterable { case arrayNumber = "ArrayNumber" } @@ -25,7 +28,5 @@ internal struct ArrayOfNumberOnly: Codable, Hashable { var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(arrayNumber, forKey: .arrayNumber) } - - - } + diff --git a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/ArrayTest.swift b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/ArrayTest.swift index 60f642f72a9..e3464b693ec 100644 --- a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/ArrayTest.swift +++ b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/ArrayTest.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif internal struct ArrayTest: Codable, Hashable { @@ -19,6 +21,7 @@ internal struct ArrayTest: Codable, Hashable { self.arrayArrayOfInteger = arrayArrayOfInteger self.arrayArrayOfModel = arrayArrayOfModel } + internal enum CodingKeys: String, CodingKey, CaseIterable { case arrayOfString = "array_of_string" case arrayArrayOfInteger = "array_array_of_integer" @@ -33,7 +36,5 @@ internal struct ArrayTest: Codable, Hashable { try container.encodeIfPresent(arrayArrayOfInteger, forKey: .arrayArrayOfInteger) try container.encodeIfPresent(arrayArrayOfModel, forKey: .arrayArrayOfModel) } - - - } + diff --git a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Capitalization.swift b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Capitalization.swift index 1184a9c9c78..042f77b8ab8 100644 --- a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Capitalization.swift +++ b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Capitalization.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif internal struct Capitalization: Codable, Hashable { @@ -26,6 +28,7 @@ internal struct Capitalization: Codable, Hashable { self.sCAETHFlowPoints = sCAETHFlowPoints self.ATT_NAME = ATT_NAME } + internal enum CodingKeys: String, CodingKey, CaseIterable { case smallCamel case capitalCamel = "CapitalCamel" @@ -46,7 +49,5 @@ internal struct Capitalization: Codable, Hashable { try container.encodeIfPresent(sCAETHFlowPoints, forKey: .sCAETHFlowPoints) try container.encodeIfPresent(ATT_NAME, forKey: .ATT_NAME) } - - - } + diff --git a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Cat.swift b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Cat.swift index 47016f63e3b..4828c445c1b 100644 --- a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Cat.swift +++ b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Cat.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif internal struct Cat: Codable, Hashable { @@ -19,6 +21,7 @@ internal struct Cat: Codable, Hashable { self.color = color self.declawed = declawed } + internal enum CodingKeys: String, CodingKey, CaseIterable { case className case color @@ -33,7 +36,5 @@ internal struct Cat: Codable, Hashable { try container.encodeIfPresent(color, forKey: .color) try container.encodeIfPresent(declawed, forKey: .declawed) } - - - } + diff --git a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/CatAllOf.swift b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/CatAllOf.swift index 9d01dbd6391..343d71d6873 100644 --- a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/CatAllOf.swift +++ b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/CatAllOf.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif internal struct CatAllOf: Codable, Hashable { @@ -15,6 +17,7 @@ internal struct CatAllOf: Codable, Hashable { internal init(declawed: Bool? = nil) { self.declawed = declawed } + internal enum CodingKeys: String, CodingKey, CaseIterable { case declawed } @@ -25,7 +28,5 @@ internal struct CatAllOf: Codable, Hashable { var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(declawed, forKey: .declawed) } - - - } + diff --git a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Category.swift b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Category.swift index b99e1f159fc..df67d9bd6f1 100644 --- a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Category.swift +++ b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Category.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif internal struct Category: Codable, Hashable { @@ -17,6 +19,7 @@ internal struct Category: Codable, Hashable { self.id = id self.name = name } + internal enum CodingKeys: String, CodingKey, CaseIterable { case id case name @@ -29,7 +32,5 @@ internal struct Category: Codable, Hashable { try container.encodeIfPresent(id, forKey: .id) try container.encode(name, forKey: .name) } - - - } + diff --git a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/ClassModel.swift b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/ClassModel.swift index efb0200fe33..d679cfe582a 100644 --- a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/ClassModel.swift +++ b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/ClassModel.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif /** Model for testing model with \"_class\" property */ internal struct ClassModel: Codable, Hashable { @@ -16,6 +18,7 @@ internal struct ClassModel: Codable, Hashable { internal init(_class: String? = nil) { self._class = _class } + internal enum CodingKeys: String, CodingKey, CaseIterable { case _class } @@ -26,7 +29,5 @@ internal struct ClassModel: Codable, Hashable { var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(_class, forKey: ._class) } - - - } + diff --git a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Client.swift b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Client.swift index 84457478611..2e50c580b65 100644 --- a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Client.swift +++ b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Client.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif internal struct Client: Codable, Hashable { @@ -15,6 +17,7 @@ internal struct Client: Codable, Hashable { internal init(client: String? = nil) { self.client = client } + internal enum CodingKeys: String, CodingKey, CaseIterable { case client } @@ -25,7 +28,5 @@ internal struct Client: Codable, Hashable { var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(client, forKey: .client) } - - - } + diff --git a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Dog.swift b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Dog.swift index 580fc9003c7..cdf48f3a786 100644 --- a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Dog.swift +++ b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Dog.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif internal struct Dog: Codable, Hashable { @@ -19,6 +21,7 @@ internal struct Dog: Codable, Hashable { self.color = color self.breed = breed } + internal enum CodingKeys: String, CodingKey, CaseIterable { case className case color @@ -33,7 +36,5 @@ internal struct Dog: Codable, Hashable { try container.encodeIfPresent(color, forKey: .color) try container.encodeIfPresent(breed, forKey: .breed) } - - - } + diff --git a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/DogAllOf.swift b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/DogAllOf.swift index 33f2e3a8c1e..f2e801a399e 100644 --- a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/DogAllOf.swift +++ b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/DogAllOf.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif internal struct DogAllOf: Codable, Hashable { @@ -15,6 +17,7 @@ internal struct DogAllOf: Codable, Hashable { internal init(breed: String? = nil) { self.breed = breed } + internal enum CodingKeys: String, CodingKey, CaseIterable { case breed } @@ -25,7 +28,5 @@ internal struct DogAllOf: Codable, Hashable { var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(breed, forKey: .breed) } - - - } + diff --git a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/EnumArrays.swift b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/EnumArrays.swift index 33a4472b1a7..950a66d752a 100644 --- a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/EnumArrays.swift +++ b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/EnumArrays.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif internal struct EnumArrays: Codable, Hashable { @@ -25,6 +27,7 @@ internal struct EnumArrays: Codable, Hashable { self.justSymbol = justSymbol self.arrayEnum = arrayEnum } + internal enum CodingKeys: String, CodingKey, CaseIterable { case justSymbol = "just_symbol" case arrayEnum = "array_enum" @@ -37,7 +40,5 @@ internal struct EnumArrays: Codable, Hashable { try container.encodeIfPresent(justSymbol, forKey: .justSymbol) try container.encodeIfPresent(arrayEnum, forKey: .arrayEnum) } - - - } + diff --git a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/EnumClass.swift b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/EnumClass.swift index 0c35bd818e0..7b5fa846ca1 100644 --- a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/EnumClass.swift +++ b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/EnumClass.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif internal enum EnumClass: String, Codable, CaseIterable { case abc = "_abc" diff --git a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/EnumTest.swift b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/EnumTest.swift index 476bf2dbbaa..77419816570 100644 --- a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/EnumTest.swift +++ b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/EnumTest.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif internal struct EnumTest: Codable, Hashable { @@ -41,6 +43,7 @@ internal struct EnumTest: Codable, Hashable { self.enumNumber = enumNumber self.outerEnum = outerEnum } + internal enum CodingKeys: String, CodingKey, CaseIterable { case enumString = "enum_string" case enumStringRequired = "enum_string_required" @@ -59,7 +62,5 @@ internal struct EnumTest: Codable, Hashable { try container.encodeIfPresent(enumNumber, forKey: .enumNumber) try container.encodeIfPresent(outerEnum, forKey: .outerEnum) } - - - } + diff --git a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/File.swift b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/File.swift index 668a27c089f..14b22772e3f 100644 --- a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/File.swift +++ b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/File.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif /** Must be named `File` for test. */ internal struct File: Codable, Hashable { @@ -17,6 +19,7 @@ internal struct File: Codable, Hashable { internal init(sourceURI: String? = nil) { self.sourceURI = sourceURI } + internal enum CodingKeys: String, CodingKey, CaseIterable { case sourceURI } @@ -27,7 +30,5 @@ internal struct File: Codable, Hashable { var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(sourceURI, forKey: .sourceURI) } - - - } + diff --git a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/FileSchemaTestClass.swift b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/FileSchemaTestClass.swift index 29e7ce62f3b..e0f8e9990a5 100644 --- a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/FileSchemaTestClass.swift +++ b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/FileSchemaTestClass.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif internal struct FileSchemaTestClass: Codable, Hashable { @@ -17,6 +19,7 @@ internal struct FileSchemaTestClass: Codable, Hashable { self.file = file self.files = files } + internal enum CodingKeys: String, CodingKey, CaseIterable { case file case files @@ -29,7 +32,5 @@ internal struct FileSchemaTestClass: Codable, Hashable { try container.encodeIfPresent(file, forKey: .file) try container.encodeIfPresent(files, forKey: .files) } - - - } + diff --git a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/FormatTest.swift b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/FormatTest.swift index e42c76fb1b5..6f8b00eddf8 100644 --- a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/FormatTest.swift +++ b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/FormatTest.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif internal struct FormatTest: Codable, Hashable { @@ -39,6 +41,7 @@ internal struct FormatTest: Codable, Hashable { self.uuid = uuid self.password = password } + internal enum CodingKeys: String, CodingKey, CaseIterable { case integer case int32 @@ -73,7 +76,5 @@ internal struct FormatTest: Codable, Hashable { try container.encodeIfPresent(uuid, forKey: .uuid) try container.encode(password, forKey: .password) } - - - } + diff --git a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/HasOnlyReadOnly.swift b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/HasOnlyReadOnly.swift index fff4dc5bef6..0ddedc17958 100644 --- a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/HasOnlyReadOnly.swift +++ b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/HasOnlyReadOnly.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif internal struct HasOnlyReadOnly: Codable, Hashable { @@ -17,6 +19,7 @@ internal struct HasOnlyReadOnly: Codable, Hashable { self.bar = bar self.foo = foo } + internal enum CodingKeys: String, CodingKey, CaseIterable { case bar case foo @@ -29,7 +32,5 @@ internal struct HasOnlyReadOnly: Codable, Hashable { try container.encodeIfPresent(bar, forKey: .bar) try container.encodeIfPresent(foo, forKey: .foo) } - - - } + diff --git a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/List.swift b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/List.swift index 71249ab1f5c..0e7903fd06a 100644 --- a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/List.swift +++ b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/List.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif internal struct List: Codable, Hashable { @@ -15,6 +17,7 @@ internal struct List: Codable, Hashable { internal init(_123list: String? = nil) { self._123list = _123list } + internal enum CodingKeys: String, CodingKey, CaseIterable { case _123list = "123-list" } @@ -25,7 +28,5 @@ internal struct List: Codable, Hashable { var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(_123list, forKey: ._123list) } - - - } + diff --git a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/MapTest.swift b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/MapTest.swift index c1057f3ebf5..748bc6781a5 100644 --- a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/MapTest.swift +++ b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/MapTest.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif internal struct MapTest: Codable, Hashable { @@ -25,6 +27,7 @@ internal struct MapTest: Codable, Hashable { self.directMap = directMap self.indirectMap = indirectMap } + internal enum CodingKeys: String, CodingKey, CaseIterable { case mapMapOfString = "map_map_of_string" case mapOfEnumString = "map_of_enum_string" @@ -41,7 +44,5 @@ internal struct MapTest: Codable, Hashable { try container.encodeIfPresent(directMap, forKey: .directMap) try container.encodeIfPresent(indirectMap, forKey: .indirectMap) } - - - } + diff --git a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/MixedPropertiesAndAdditionalPropertiesClass.swift b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/MixedPropertiesAndAdditionalPropertiesClass.swift index ebf6ae145dd..68ef87daf00 100644 --- a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/MixedPropertiesAndAdditionalPropertiesClass.swift +++ b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/MixedPropertiesAndAdditionalPropertiesClass.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif internal struct MixedPropertiesAndAdditionalPropertiesClass: Codable, Hashable { @@ -19,6 +21,7 @@ internal struct MixedPropertiesAndAdditionalPropertiesClass: Codable, Hashable { self.dateTime = dateTime self.map = map } + internal enum CodingKeys: String, CodingKey, CaseIterable { case uuid case dateTime @@ -33,7 +36,5 @@ internal struct MixedPropertiesAndAdditionalPropertiesClass: Codable, Hashable { try container.encodeIfPresent(dateTime, forKey: .dateTime) try container.encodeIfPresent(map, forKey: .map) } - - - } + diff --git a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Model200Response.swift b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Model200Response.swift index 1efae876cbf..dad6079ddb2 100644 --- a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Model200Response.swift +++ b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Model200Response.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif /** Model for testing model name starting with number */ internal struct Model200Response: Codable, Hashable { @@ -18,6 +20,7 @@ internal struct Model200Response: Codable, Hashable { self.name = name self._class = _class } + internal enum CodingKeys: String, CodingKey, CaseIterable { case name case _class = "class" @@ -30,7 +33,5 @@ internal struct Model200Response: Codable, Hashable { try container.encodeIfPresent(name, forKey: .name) try container.encodeIfPresent(_class, forKey: ._class) } - - - } + diff --git a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Name.swift b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Name.swift index aa9337dedc4..2a842bf54aa 100644 --- a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Name.swift +++ b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Name.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif /** Model for testing model name same as property name */ internal struct Name: Codable, Hashable { @@ -22,6 +24,7 @@ internal struct Name: Codable, Hashable { self.property = property self._123number = _123number } + internal enum CodingKeys: String, CodingKey, CaseIterable { case name case snakeCase = "snake_case" @@ -38,7 +41,5 @@ internal struct Name: Codable, Hashable { try container.encodeIfPresent(property, forKey: .property) try container.encodeIfPresent(_123number, forKey: ._123number) } - - - } + diff --git a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/NumberOnly.swift b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/NumberOnly.swift index 0748cf0a096..36cf8d164bd 100644 --- a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/NumberOnly.swift +++ b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/NumberOnly.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif internal struct NumberOnly: Codable, Hashable { @@ -15,6 +17,7 @@ internal struct NumberOnly: Codable, Hashable { internal init(justNumber: Double? = nil) { self.justNumber = justNumber } + internal enum CodingKeys: String, CodingKey, CaseIterable { case justNumber = "JustNumber" } @@ -25,7 +28,5 @@ internal struct NumberOnly: Codable, Hashable { var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(justNumber, forKey: .justNumber) } - - - } + diff --git a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Order.swift b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Order.swift index 378e41056a8..45046f9a00f 100644 --- a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Order.swift +++ b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Order.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif internal struct Order: Codable, Hashable { @@ -31,6 +33,7 @@ internal struct Order: Codable, Hashable { self.status = status self.complete = complete } + internal enum CodingKeys: String, CodingKey, CaseIterable { case id case petId @@ -51,7 +54,5 @@ internal struct Order: Codable, Hashable { try container.encodeIfPresent(status, forKey: .status) try container.encodeIfPresent(complete, forKey: .complete) } - - - } + diff --git a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/OuterComposite.swift b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/OuterComposite.swift index 76508a79a26..082cdebd26c 100644 --- a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/OuterComposite.swift +++ b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/OuterComposite.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif internal struct OuterComposite: Codable, Hashable { @@ -19,6 +21,7 @@ internal struct OuterComposite: Codable, Hashable { self.myString = myString self.myBoolean = myBoolean } + internal enum CodingKeys: String, CodingKey, CaseIterable { case myNumber = "my_number" case myString = "my_string" @@ -33,7 +36,5 @@ internal struct OuterComposite: Codable, Hashable { try container.encodeIfPresent(myString, forKey: .myString) try container.encodeIfPresent(myBoolean, forKey: .myBoolean) } - - - } + diff --git a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/OuterEnum.swift b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/OuterEnum.swift index cb0a71c180c..e947654ad72 100644 --- a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/OuterEnum.swift +++ b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/OuterEnum.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif internal enum OuterEnum: String, Codable, CaseIterable { case placed = "placed" diff --git a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Pet.swift b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Pet.swift index c28c280608f..8c77a382e8f 100644 --- a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Pet.swift +++ b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Pet.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif internal struct Pet: Codable, Hashable { @@ -31,6 +33,7 @@ internal struct Pet: Codable, Hashable { self.tags = tags self.status = status } + internal enum CodingKeys: String, CodingKey, CaseIterable { case id case category @@ -51,7 +54,5 @@ internal struct Pet: Codable, Hashable { try container.encodeIfPresent(tags, forKey: .tags) try container.encodeIfPresent(status, forKey: .status) } - - - } + diff --git a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/ReadOnlyFirst.swift b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/ReadOnlyFirst.swift index 7f9cf4abd2e..e8961d9d8a8 100644 --- a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/ReadOnlyFirst.swift +++ b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/ReadOnlyFirst.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif internal struct ReadOnlyFirst: Codable, Hashable { @@ -17,6 +19,7 @@ internal struct ReadOnlyFirst: Codable, Hashable { self.bar = bar self.baz = baz } + internal enum CodingKeys: String, CodingKey, CaseIterable { case bar case baz @@ -29,7 +32,5 @@ internal struct ReadOnlyFirst: Codable, Hashable { try container.encodeIfPresent(bar, forKey: .bar) try container.encodeIfPresent(baz, forKey: .baz) } - - - } + diff --git a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Return.swift b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Return.swift index bd512e38ac3..7a2e2da47f8 100644 --- a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Return.swift +++ b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Return.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif /** Model for testing reserved words */ internal struct Return: Codable, Hashable { @@ -16,6 +18,7 @@ internal struct Return: Codable, Hashable { internal init(_return: Int? = nil) { self._return = _return } + internal enum CodingKeys: String, CodingKey, CaseIterable { case _return = "return" } @@ -26,7 +29,5 @@ internal struct Return: Codable, Hashable { var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(_return, forKey: ._return) } - - - } + diff --git a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/SpecialModelName.swift b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/SpecialModelName.swift index 848bbe6f384..2c3d25c5bbb 100644 --- a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/SpecialModelName.swift +++ b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/SpecialModelName.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif internal struct SpecialModelName: Codable, Hashable { @@ -15,6 +17,7 @@ internal struct SpecialModelName: Codable, Hashable { internal init(specialPropertyName: Int64? = nil) { self.specialPropertyName = specialPropertyName } + internal enum CodingKeys: String, CodingKey, CaseIterable { case specialPropertyName = "$special[property.name]" } @@ -25,7 +28,5 @@ internal struct SpecialModelName: Codable, Hashable { var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(specialPropertyName, forKey: .specialPropertyName) } - - - } + diff --git a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/StringBooleanMap.swift b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/StringBooleanMap.swift index 50ff6bedf9b..4b76e50cece 100644 --- a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/StringBooleanMap.swift +++ b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/StringBooleanMap.swift @@ -6,12 +6,16 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif internal struct StringBooleanMap: Codable, Hashable { + internal enum CodingKeys: CodingKey, CaseIterable { } + internal var additionalProperties: [String: Bool] = [:] internal subscript(key: String) -> Bool? { @@ -38,11 +42,11 @@ internal struct StringBooleanMap: Codable, Hashable { // Decodable protocol methods internal init(from decoder: Decoder) throws { - let container = try decoder.container(keyedBy: String.self) + let container = try decoder.container(keyedBy: CodingKeys.self) var nonAdditionalPropertyKeys = Set() - additionalProperties = try container.decodeMap(Bool.self, excludedKeys: nonAdditionalPropertyKeys) + let additionalPropertiesContainer = try decoder.container(keyedBy: String.self) + additionalProperties = try additionalPropertiesContainer.decodeMap(Bool.self, excludedKeys: nonAdditionalPropertyKeys) } - - } + diff --git a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift index 2acf7c82cd4..810603ff0b5 100644 --- a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift +++ b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif internal struct Tag: Codable, Hashable { @@ -17,6 +19,7 @@ internal struct Tag: Codable, Hashable { self.id = id self.name = name } + internal enum CodingKeys: String, CodingKey, CaseIterable { case id case name @@ -29,7 +32,5 @@ internal struct Tag: Codable, Hashable { try container.encodeIfPresent(id, forKey: .id) try container.encodeIfPresent(name, forKey: .name) } - - - } + diff --git a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderDefault.swift b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderDefault.swift index 1e306e35699..4a71a601e1b 100644 --- a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderDefault.swift +++ b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderDefault.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif internal struct TypeHolderDefault: Codable, Hashable { @@ -23,6 +25,7 @@ internal struct TypeHolderDefault: Codable, Hashable { self.boolItem = boolItem self.arrayItem = arrayItem } + internal enum CodingKeys: String, CodingKey, CaseIterable { case stringItem = "string_item" case numberItem = "number_item" @@ -41,7 +44,5 @@ internal struct TypeHolderDefault: Codable, Hashable { try container.encode(boolItem, forKey: .boolItem) try container.encode(arrayItem, forKey: .arrayItem) } - - - } + diff --git a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderExample.swift b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderExample.swift index 386054d5ca9..71cdf9ee1ea 100644 --- a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderExample.swift +++ b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderExample.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif internal struct TypeHolderExample: Codable, Hashable { @@ -23,6 +25,7 @@ internal struct TypeHolderExample: Codable, Hashable { self.boolItem = boolItem self.arrayItem = arrayItem } + internal enum CodingKeys: String, CodingKey, CaseIterable { case stringItem = "string_item" case numberItem = "number_item" @@ -41,7 +44,5 @@ internal struct TypeHolderExample: Codable, Hashable { try container.encode(boolItem, forKey: .boolItem) try container.encode(arrayItem, forKey: .arrayItem) } - - - } + diff --git a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/User.swift b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/User.swift index a3e131ac3d9..57017c341e7 100644 --- a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/User.swift +++ b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models/User.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif internal struct User: Codable, Hashable { @@ -30,6 +32,7 @@ internal struct User: Codable, Hashable { self.phone = phone self.userStatus = userStatus } + internal enum CodingKeys: String, CodingKey, CaseIterable { case id case username @@ -54,7 +57,5 @@ internal struct User: Codable, Hashable { try container.encodeIfPresent(phone, forKey: .phone) try container.encodeIfPresent(userStatus, forKey: .userStatus) } - - - } + 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 c8ac98f2026..71361b388bb 100644 --- a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift +++ b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift @@ -93,14 +93,14 @@ internal class URLSessionRequestBuilder: RequestBuilder { return modifiedRequest } - override internal func execute(_ apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, _ completion: @escaping (_ result: Swift.Result, Error>) -> Void) { + override internal func execute(_ apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, _ completion: @escaping (_ result: Swift.Result, Error>) -> Void) { let urlSessionId = UUID().uuidString // Create a new manager for each request to customize its request header let urlSession = createURLSession() urlSessionStore[urlSessionId] = urlSession guard let xMethod = HTTPMethod(rawValue: method) else { - fatalError("Unsuported Http method - \(method)") + fatalError("Unsupported Http method - \(method)") } let encoding: ParameterEncoding @@ -119,7 +119,7 @@ internal class URLSessionRequestBuilder: RequestBuilder { } else if contentType == "application/x-www-form-urlencoded" { encoding = FormURLEncoding() } else { - fatalError("Unsuported Media Type - \(contentType)") + fatalError("Unsupported Media Type - \(contentType)") } } @@ -205,16 +205,18 @@ internal class URLSessionRequestBuilder: RequestBuilder { } let fileManager = FileManager.default - let documentsDirectory = fileManager.urls(for: .documentDirectory, in: .userDomainMask)[0] + let cachesDirectory = fileManager.urls(for: .cachesDirectory, in: .userDomainMask)[0] let requestURL = try getURL(from: urlRequest) var requestPath = try getPath(from: requestURL) if let headerFileName = getFileName(fromContentDisposition: httpResponse.allHeaderFields["Content-Disposition"] as? String) { requestPath = requestPath.appending("/\(headerFileName)") + } else { + requestPath = requestPath.appending("/tmp.PetstoreClient.\(UUID().uuidString)") } - let filePath = documentsDirectory.appendingPathComponent(requestPath) + let filePath = cachesDirectory.appendingPathComponent(requestPath) let directoryPath = filePath.deletingLastPathComponent().path try fileManager.createDirectory(atPath: directoryPath, withIntermediateDirectories: true, attributes: nil) @@ -232,6 +234,10 @@ internal class URLSessionRequestBuilder: RequestBuilder { completion(.success(Response(response: httpResponse, body: nil))) + case is Data.Type: + + completion(.success(Response(response: httpResponse, body: data as? T))) + default: completion(.success(Response(response: httpResponse, body: data as? T))) @@ -244,7 +250,7 @@ internal class URLSessionRequestBuilder: RequestBuilder { for (key, value) in headers { httpHeaders[key] = value } - for (key, value) in PetstoreClientAPI.customHeaders { + for (key, value) in PetstoreClient.customHeaders { httpHeaders[key] = value } return httpHeaders @@ -328,6 +334,43 @@ internal class URLSessionDecodableRequestBuilder: URLSessionReques completion(.success(Response(response: httpResponse, body: body as? T))) + case is URL.Type: + do { + + guard error == nil else { + throw DownloadException.responseFailed + } + + guard let data = data else { + throw DownloadException.responseDataMissing + } + + let fileManager = FileManager.default + let cachesDirectory = fileManager.urls(for: .cachesDirectory, in: .userDomainMask)[0] + let requestURL = try getURL(from: urlRequest) + + var requestPath = try getPath(from: requestURL) + + if let headerFileName = getFileName(fromContentDisposition: httpResponse.allHeaderFields["Content-Disposition"] as? String) { + requestPath = requestPath.appending("/\(headerFileName)") + } else { + requestPath = requestPath.appending("/tmp.PetstoreClient.\(UUID().uuidString)") + } + + let filePath = cachesDirectory.appendingPathComponent(requestPath) + let directoryPath = filePath.deletingLastPathComponent().path + + try fileManager.createDirectory(atPath: directoryPath, withIntermediateDirectories: true, attributes: nil) + try data.write(to: filePath, options: .atomic) + + completion(.success(Response(response: httpResponse, body: filePath as? T))) + + } catch let requestParserError as DownloadException { + completion(.failure(ErrorResponse.error(400, data, response, requestParserError))) + } catch { + completion(.failure(ErrorResponse.error(400, data, response, error))) + } + case is Void.Type: completion(.success(Response(response: httpResponse, body: nil))) diff --git a/samples/client/petstore/swift5/nonPublicApi/docs/FakeAPI.md b/samples/client/petstore/swift5/nonPublicApi/docs/FakeAPI.md index 3b14781480f..b922f6ff706 100644 --- a/samples/client/petstore/swift5/nonPublicApi/docs/FakeAPI.md +++ b/samples/client/petstore/swift5/nonPublicApi/docs/FakeAPI.md @@ -384,7 +384,7 @@ let float = 987 // Float | None (optional) let double = 987 // Double | None let string = "string_example" // String | None (optional) let patternWithoutDelimiter = "patternWithoutDelimiter_example" // String | None -let byte = 987 // Data | None +let byte = Data([9, 8, 7]) // Data | None let binary = URL(string: "https://example.com")! // URL | None (optional) let date = Date() // Date | None (optional) let dateTime = Date() // Date | None (optional) diff --git a/samples/client/petstore/swift5/nonPublicApi/project.yml b/samples/client/petstore/swift5/nonPublicApi/project.yml index 5528eeee513..0493cf65896 100644 --- a/samples/client/petstore/swift5/nonPublicApi/project.yml +++ b/samples/client/petstore/swift5/nonPublicApi/project.yml @@ -11,5 +11,5 @@ targets: settings: APPLICATION_EXTENSION_API_ONLY: true scheme: {} - + dependencies: - carthage: AnyCodable diff --git a/samples/client/petstore/swift5/objcCompatible/.gitignore b/samples/client/petstore/swift5/objcCompatible/.gitignore index 5e5d5cebcf4..627d360a903 100644 --- a/samples/client/petstore/swift5/objcCompatible/.gitignore +++ b/samples/client/petstore/swift5/objcCompatible/.gitignore @@ -1,12 +1,22 @@ +# Created by https://www.toptal.com/developers/gitignore/api/swift,xcode +# Edit at https://www.toptal.com/developers/gitignore?templates=swift,xcode + +### Swift ### # Xcode # # gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore -## Build generated -build/ -DerivedData +## User settings +xcuserdata/ -## Various settings +## compatibility with Xcode 8 and earlier (ignoring not required starting Xcode 9) +*.xcscmblueprint +*.xccheckout + +## compatibility with Xcode 3 and earlier (ignoring not required starting Xcode 4) +build/ +DerivedData/ +*.moved-aside *.pbxuser !default.pbxuser *.mode1v3 @@ -15,49 +25,81 @@ DerivedData !default.mode2v3 *.perspectivev3 !default.perspectivev3 -xcuserdata - -## Other -*.xccheckout -*.moved-aside -*.xcuserstate -*.xcscmblueprint ## Obj-C/Swift specific *.hmap + +## App packaging *.ipa +*.dSYM.zip +*.dSYM ## Playgrounds timeline.xctimeline playground.xcworkspace # Swift Package Manager -# # Add this line if you want to avoid checking in source code from Swift Package Manager dependencies. # Packages/ +# Package.pins +# Package.resolved +# *.xcodeproj +# Xcode automatically generates this directory with a .xcworkspacedata file and xcuserdata +# hence it is not needed unless you have added a package configuration file to your project +# .swiftpm + .build/ # CocoaPods -# # We recommend against adding the Pods directory to your .gitignore. However # you should judge for yourself, the pros and cons are mentioned at: # https://guides.cocoapods.org/using/using-cocoapods.html#should-i-check-the-pods-directory-into-source-control -# # Pods/ +# Add this line if you want to avoid checking in source code from the Xcode workspace +# *.xcworkspace # Carthage -# # Add this line if you want to avoid checking in source code from Carthage dependencies. # Carthage/Checkouts -Carthage/Build +Carthage/Build/ + +# Add this lines if you are using Accio dependency management (Deprecated since Xcode 12) +# Dependencies/ +# .accio/ # fastlane -# -# It is recommended to not store the screenshots in the git repo. Instead, use fastlane to re-generate the -# screenshots whenever they are needed. +# It is recommended to not store the screenshots in the git repo. +# Instead, use fastlane to re-generate the screenshots whenever they are needed. # For more information about the recommended setup visit: -# https://github.com/fastlane/fastlane/blob/master/docs/Gitignore.md +# https://docs.fastlane.tools/best-practices/source-control/#source-control fastlane/report.xml -fastlane/screenshots +fastlane/Preview.html +fastlane/screenshots/**/*.png +fastlane/test_output + +# Code Injection +# After new code Injection tools there's a generated folder /iOSInjectionProject +# https://github.com/johnno1962/injectionforxcode + +iOSInjectionProject/ + +### Xcode ### +# Xcode +# gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore + + + + +## Gcc Patch +/*.gcno + +### Xcode Patch ### +*.xcodeproj/* +!*.xcodeproj/project.pbxproj +!*.xcodeproj/xcshareddata/ +!*.xcworkspace/contents.xcworkspacedata +**/xcshareddata/WorkspaceSettings.xcsettings + +# End of https://www.toptal.com/developers/gitignore/api/swift,xcode diff --git a/samples/client/petstore/swift5/objcCompatible/.openapi-generator/VERSION b/samples/client/petstore/swift5/objcCompatible/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/client/petstore/swift5/objcCompatible/.openapi-generator/VERSION +++ b/samples/client/petstore/swift5/objcCompatible/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/client/petstore/swift5/objcCompatible/Cartfile b/samples/client/petstore/swift5/objcCompatible/Cartfile index 84aaa61ef2d..a6a6bcacb1d 100644 --- a/samples/client/petstore/swift5/objcCompatible/Cartfile +++ b/samples/client/petstore/swift5/objcCompatible/Cartfile @@ -1,2 +1,2 @@ -github "Flight-School/AnyCodable" ~> 0.4.0 +github "Flight-School/AnyCodable" ~> 0.6.1 diff --git a/samples/client/petstore/swift5/objcCompatible/Package.resolved b/samples/client/petstore/swift5/objcCompatible/Package.resolved new file mode 100644 index 00000000000..79610c3b3b3 --- /dev/null +++ b/samples/client/petstore/swift5/objcCompatible/Package.resolved @@ -0,0 +1,16 @@ +{ + "object": { + "pins": [ + { + "package": "AnyCodable", + "repositoryURL": "https://github.com/Flight-School/AnyCodable", + "state": { + "branch": null, + "revision": "69261f239f0fffaf51495dadc4f8483fbfe97025", + "version": "0.6.1" + } + } + ] + }, + "version": 1 +} diff --git a/samples/client/petstore/swift5/objcCompatible/Package.swift b/samples/client/petstore/swift5/objcCompatible/Package.swift index b724838fe8d..87bb775fb72 100644 --- a/samples/client/petstore/swift5/objcCompatible/Package.swift +++ b/samples/client/petstore/swift5/objcCompatible/Package.swift @@ -19,7 +19,7 @@ let package = Package( ], dependencies: [ // Dependencies declare other packages that this package depends on. - .package(url: "https://github.com/Flight-School/AnyCodable", .exact("0.4.0")), + .package(url: "https://github.com/Flight-School/AnyCodable", from: "0.6.1"), ], targets: [ // Targets are the basic building blocks of a package. A target can define a module or a test suite. diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient.podspec b/samples/client/petstore/swift5/objcCompatible/PetstoreClient.podspec index de06558efbd..0e6bf7ec024 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient.podspec +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient.podspec @@ -11,5 +11,5 @@ Pod::Spec.new do |s| s.homepage = 'https://github.com/openapitools/openapi-generator' s.summary = 'PetstoreClient' s.source_files = 'PetstoreClient/Classes/**/*.swift' - s.dependency 'AnyCodable-FlightSchool', '~> 0.4.0' + s.dependency 'AnyCodable-FlightSchool', '~> 0.6.1' end diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs.swift index dbdab491ff7..941c61b713a 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs.swift @@ -6,10 +6,13 @@ import Foundation -open class PetstoreClientAPI { +@available(*, deprecated, renamed: "PetstoreClient") +public typealias PetstoreClientAPI = PetstoreClient + +open class PetstoreClient { public static var basePath = "http://petstore.swagger.io:80/v2" - public static var credential: URLCredential? public static var customHeaders: [String: String] = [:] + public static var credential: URLCredential? public static var requestBuilderFactory: RequestBuilderFactory = URLSessionRequestBuilderFactory() public static var apiResponseQueue: DispatchQueue = .main } @@ -32,7 +35,7 @@ open class RequestBuilder { self.parameters = parameters self.headers = headers - addHeaders(PetstoreClientAPI.customHeaders) + addHeaders(PetstoreClient.customHeaders) } open func addHeaders(_ aHeaders: [String: String]) { @@ -41,7 +44,7 @@ open class RequestBuilder { } } - open func execute(_ apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, _ completion: @escaping (_ result: Swift.Result, Error>) -> Void) { } + open func execute(_ apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, _ completion: @escaping (_ result: Swift.Result, Error>) -> Void) { } public func addHeader(name: String, value: String) -> Self { if !value.isEmpty { @@ -51,7 +54,7 @@ open class RequestBuilder { } open func addCredential() -> Self { - credential = PetstoreClientAPI.credential + credential = PetstoreClient.credential return self } } 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 c0b90bf2f94..a14eef304fe 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 @@ -6,8 +6,12 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif @objc open class AnotherFakeAPI : NSObject { + /** To test special tags @@ -15,7 +19,7 @@ import Foundation - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func call123testSpecialTags(body: Client, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Client?, _ error: Error?) -> Void)) { + open class func call123testSpecialTags(body: Client, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Client?, _ error: Error?) -> Void)) { call123testSpecialTagsWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -34,21 +38,20 @@ import Foundation - returns: RequestBuilder */ open class func call123testSpecialTagsWithRequestBuilder(body: Client) -> RequestBuilder { - let path = "/another-fake/dummy" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/another-fake/dummy" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "PATCH", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "PATCH", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } - } 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 f37371daf50..b8c26ff6fce 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 @@ -6,15 +6,19 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif @objc open class FakeAPI : NSObject { + /** - parameter body: (body) Input boolean as post body (optional) - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func fakeOuterBooleanSerialize(body: Bool? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Bool?, _ error: Error?) -> Void)) { + open class func fakeOuterBooleanSerialize(body: Bool? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Bool?, _ error: Error?) -> Void)) { fakeOuterBooleanSerializeWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -32,21 +36,21 @@ import Foundation - returns: RequestBuilder */ open class func fakeOuterBooleanSerializeWithRequestBuilder(body: Bool? = nil) -> RequestBuilder { - let path = "/fake/outer/boolean" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/fake/outer/boolean" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -55,7 +59,7 @@ import Foundation - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func fakeOuterCompositeSerialize(body: OuterComposite? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: OuterComposite?, _ error: Error?) -> Void)) { + open class func fakeOuterCompositeSerialize(body: OuterComposite? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: OuterComposite?, _ error: Error?) -> Void)) { fakeOuterCompositeSerializeWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -73,21 +77,21 @@ import Foundation - returns: RequestBuilder */ open class func fakeOuterCompositeSerializeWithRequestBuilder(body: OuterComposite? = nil) -> RequestBuilder { - let path = "/fake/outer/composite" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/fake/outer/composite" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -96,7 +100,7 @@ import Foundation - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func fakeOuterNumberSerialize(body: Double? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Double?, _ error: Error?) -> Void)) { + open class func fakeOuterNumberSerialize(body: Double? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Double?, _ error: Error?) -> Void)) { fakeOuterNumberSerializeWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -114,21 +118,21 @@ import Foundation - returns: RequestBuilder */ open class func fakeOuterNumberSerializeWithRequestBuilder(body: Double? = nil) -> RequestBuilder { - let path = "/fake/outer/number" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/fake/outer/number" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -137,7 +141,7 @@ import Foundation - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func fakeOuterStringSerialize(body: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: String?, _ error: Error?) -> Void)) { + open class func fakeOuterStringSerialize(body: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: String?, _ error: Error?) -> Void)) { fakeOuterStringSerializeWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -155,21 +159,21 @@ import Foundation - returns: RequestBuilder */ open class func fakeOuterStringSerializeWithRequestBuilder(body: String? = nil) -> RequestBuilder { - let path = "/fake/outer/string" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/fake/outer/string" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -178,7 +182,7 @@ import Foundation - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func testBodyWithFileSchema(body: FileSchemaTestClass, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func testBodyWithFileSchema(body: FileSchemaTestClass, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { testBodyWithFileSchemaWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -196,21 +200,21 @@ import Foundation - returns: RequestBuilder */ open class func testBodyWithFileSchemaWithRequestBuilder(body: FileSchemaTestClass) -> RequestBuilder { - let path = "/fake/body-with-file-schema" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/fake/body-with-file-schema" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "PUT", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -220,7 +224,7 @@ import Foundation - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func testBodyWithQueryParams(query: String, body: User, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func testBodyWithQueryParams(query: String, body: User, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { testBodyWithQueryParamsWithRequestBuilder(query: query, body: body).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -238,24 +242,24 @@ import Foundation - returns: RequestBuilder */ open class func testBodyWithQueryParamsWithRequestBuilder(query: String, body: User) -> RequestBuilder { - let path = "/fake/body-with-query-params" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/fake/body-with-query-params" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - var urlComponents = URLComponents(string: URLString) - urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ + var localVariableUrlComponents = URLComponents(string: localVariableURLString) + localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ "query": query.encodeToJSON(), ]) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "PUT", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -265,7 +269,7 @@ import Foundation - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func testClientModel(body: Client, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Client?, _ error: Error?) -> Void)) { + open class func testClientModel(body: Client, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Client?, _ error: Error?) -> Void)) { testClientModelWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -284,21 +288,21 @@ import Foundation - returns: RequestBuilder */ open class func testClientModelWithRequestBuilder(body: Client) -> RequestBuilder { - let path = "/fake" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/fake" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "PATCH", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "PATCH", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -321,7 +325,7 @@ import Foundation - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func testEndpointParameters(number: Double, double: Double, patternWithoutDelimiter: String, byte: Data, integer: Int? = nil, int32: Int? = nil, int64: Int64? = nil, float: Float? = nil, string: String? = nil, binary: URL? = nil, date: Date? = nil, dateTime: Date? = nil, password: String? = nil, callback: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func testEndpointParameters(number: Double, double: Double, patternWithoutDelimiter: String, byte: Data, integer: Int? = nil, int32: Int? = nil, int64: Int64? = nil, float: Float? = nil, string: String? = nil, binary: URL? = nil, date: Date? = nil, dateTime: Date? = nil, password: String? = nil, callback: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { testEndpointParametersWithRequestBuilder(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(apiResponseQueue) { result -> Void in switch result { case .success: @@ -356,9 +360,9 @@ import Foundation - returns: RequestBuilder */ open class func testEndpointParametersWithRequestBuilder(number: Double, double: Double, patternWithoutDelimiter: String, byte: Data, integer: Int? = nil, int32: Int? = nil, int64: Int64? = nil, float: Float? = nil, string: String? = nil, binary: URL? = nil, date: Date? = nil, dateTime: Date? = nil, password: String? = nil, callback: String? = nil) -> RequestBuilder { - let path = "/fake" - let URLString = PetstoreClientAPI.basePath + path - let formParams: [String: Any?] = [ + let localVariablePath = "/fake" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableFormParams: [String: Any?] = [ "integer": integer?.encodeToJSON(), "int32": int32?.encodeToJSON(), "int64": int64?.encodeToJSON(), @@ -375,20 +379,20 @@ import Foundation "callback": callback?.encodeToJSON(), ] - let nonNullParameters = APIHelper.rejectNil(formParams) - let parameters = APIHelper.convertBoolToString(nonNullParameters) + let localVariableNonNullParameters = APIHelper.rejectNil(localVariableFormParams) + let localVariableParameters = APIHelper.convertBoolToString(localVariableNonNullParameters) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ "Content-Type": "application/x-www-form-urlencoded", ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -472,7 +476,7 @@ import Foundation - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func testEnumParameters(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func testEnumParameters(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { testEnumParametersWithRequestBuilder(enumHeaderStringArray: enumHeaderStringArray, enumHeaderString: enumHeaderString, enumQueryStringArray: enumQueryStringArray, enumQueryString: enumQueryString, enumQueryInteger: enumQueryInteger, enumQueryDouble: enumQueryDouble, enumFormStringArray: enumFormStringArray, enumFormString: enumFormString).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -498,35 +502,35 @@ import Foundation - returns: RequestBuilder */ open class func testEnumParametersWithRequestBuilder(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil) -> RequestBuilder { - let path = "/fake" - let URLString = PetstoreClientAPI.basePath + path - let formParams: [String: Any?] = [ + let localVariablePath = "/fake" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableFormParams: [String: Any?] = [ "enum_form_string_array": enumFormStringArray?.encodeToJSON(), "enum_form_string": enumFormString?.encodeToJSON(), ] - let nonNullParameters = APIHelper.rejectNil(formParams) - let parameters = APIHelper.convertBoolToString(nonNullParameters) + let localVariableNonNullParameters = APIHelper.rejectNil(localVariableFormParams) + let localVariableParameters = APIHelper.convertBoolToString(localVariableNonNullParameters) - var urlComponents = URLComponents(string: URLString) - urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ + var localVariableUrlComponents = URLComponents(string: localVariableURLString) + localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ "enum_query_string_array": enumQueryStringArray?.encodeToJSON(), "enum_query_string": enumQueryString?.encodeToJSON(), "enum_query_integer": enumQueryInteger?.encodeToJSON(), "enum_query_double": enumQueryDouble?.encodeToJSON(), ]) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ "Content-Type": "application/x-www-form-urlencoded", "enum_header_string_array": enumHeaderStringArray?.encodeToJSON(), "enum_header_string": enumHeaderString?.encodeToJSON(), ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -541,7 +545,7 @@ import Foundation - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func testGroupParameters(requiredStringGroup: Int, requiredBooleanGroup: Bool, requiredInt64Group: Int64, stringGroup: Int? = nil, booleanGroup: Bool? = nil, int64Group: Int64? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func testGroupParameters(requiredStringGroup: Int, requiredBooleanGroup: Bool, requiredInt64Group: Int64, stringGroup: Int? = nil, booleanGroup: Bool? = nil, int64Group: Int64? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { testGroupParametersWithRequestBuilder(requiredStringGroup: requiredStringGroup, requiredBooleanGroup: requiredBooleanGroup, requiredInt64Group: requiredInt64Group, stringGroup: stringGroup, booleanGroup: booleanGroup, int64Group: int64Group).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -565,28 +569,28 @@ import Foundation - returns: RequestBuilder */ open class func testGroupParametersWithRequestBuilder(requiredStringGroup: Int, requiredBooleanGroup: Bool, requiredInt64Group: Int64, stringGroup: Int? = nil, booleanGroup: Bool? = nil, int64Group: Int64? = nil) -> RequestBuilder { - let path = "/fake" - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + let localVariablePath = "/fake" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - var urlComponents = URLComponents(string: URLString) - urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ + var localVariableUrlComponents = URLComponents(string: localVariableURLString) + localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ "required_string_group": requiredStringGroup.encodeToJSON(), "required_int64_group": requiredInt64Group.encodeToJSON(), "string_group": stringGroup?.encodeToJSON(), "int64_group": int64Group?.encodeToJSON(), ]) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ "required_boolean_group": requiredBooleanGroup.encodeToJSON(), "boolean_group": booleanGroup?.encodeToJSON(), ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "DELETE", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -596,7 +600,7 @@ import Foundation - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func testInlineAdditionalProperties(param: [String: String], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func testInlineAdditionalProperties(param: [String: String], apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { testInlineAdditionalPropertiesWithRequestBuilder(param: param).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -614,21 +618,21 @@ import Foundation - returns: RequestBuilder */ open class func testInlineAdditionalPropertiesWithRequestBuilder(param: [String: String]) -> RequestBuilder { - let path = "/fake/inline-additionalProperties" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: param) + let localVariablePath = "/fake/inline-additionalProperties" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: param) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -639,7 +643,7 @@ import Foundation - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func testJsonFormData(param: String, param2: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func testJsonFormData(param: String, param2: String, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { testJsonFormDataWithRequestBuilder(param: param, param2: param2).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -658,27 +662,26 @@ import Foundation - returns: RequestBuilder */ open class func testJsonFormDataWithRequestBuilder(param: String, param2: String) -> RequestBuilder { - let path = "/fake/jsonFormData" - let URLString = PetstoreClientAPI.basePath + path - let formParams: [String: Any?] = [ + let localVariablePath = "/fake/jsonFormData" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableFormParams: [String: Any?] = [ "param": param.encodeToJSON(), "param2": param2.encodeToJSON(), ] - let nonNullParameters = APIHelper.rejectNil(formParams) - let parameters = APIHelper.convertBoolToString(nonNullParameters) + let localVariableNonNullParameters = APIHelper.rejectNil(localVariableFormParams) + let localVariableParameters = APIHelper.convertBoolToString(localVariableNonNullParameters) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ "Content-Type": "application/x-www-form-urlencoded", ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } - } 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 cae3d8e7da2..1a85f0ae98a 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 @@ -6,8 +6,12 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif @objc open class FakeClassnameTags123API : NSObject { + /** To test class name in snake case @@ -15,7 +19,7 @@ import Foundation - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func testClassname(body: Client, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Client?, _ error: Error?) -> Void)) { + open class func testClassname(body: Client, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Client?, _ error: Error?) -> Void)) { testClassnameWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -37,21 +41,20 @@ import Foundation - returns: RequestBuilder */ open class func testClassnameWithRequestBuilder(body: Client) -> RequestBuilder { - let path = "/fake_classname_test" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/fake_classname_test" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "PATCH", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "PATCH", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } - } 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 a46c4b36d5c..260f720e5f0 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 @@ -6,8 +6,12 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif @objc open class PetAPI : NSObject { + /** Add a new pet to the store @@ -15,7 +19,7 @@ import Foundation - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func addPet(body: Pet, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func addPet(body: Pet, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { addPetWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -36,21 +40,21 @@ import Foundation - returns: RequestBuilder */ open class func addPetWithRequestBuilder(body: Pet) -> RequestBuilder { - let path = "/pet" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/pet" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -61,7 +65,7 @@ import Foundation - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func deletePet(petId: Int64, apiKey: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func deletePet(petId: Int64, apiKey: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { deletePetWithRequestBuilder(petId: petId, apiKey: apiKey).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -83,24 +87,24 @@ import Foundation - returns: RequestBuilder */ open class func deletePetWithRequestBuilder(petId: Int64, apiKey: String? = nil) -> RequestBuilder { - var path = "/pet/{petId}" + var localVariablePath = "/pet/{petId}" let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))" let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" - path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + localVariablePath = localVariablePath.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ "api_key": apiKey?.encodeToJSON(), ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "DELETE", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -119,7 +123,7 @@ import Foundation - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func findPetsByStatus(status: [String], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: [Pet]?, _ error: Error?) -> Void)) { + open class func findPetsByStatus(status: [String], apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: [Pet]?, _ error: Error?) -> Void)) { findPetsByStatusWithRequestBuilder(status: status).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -141,24 +145,24 @@ import Foundation - returns: RequestBuilder<[Pet]> */ open class func findPetsByStatusWithRequestBuilder(status: [String]) -> RequestBuilder<[Pet]> { - let path = "/pet/findByStatus" - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + let localVariablePath = "/pet/findByStatus" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - var urlComponents = URLComponents(string: URLString) - urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ + var localVariableUrlComponents = URLComponents(string: localVariableURLString) + localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ "status": status.encodeToJSON(), ]) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -169,7 +173,7 @@ import Foundation - parameter completion: completion handler to receive the data and the error objects */ @available(*, deprecated, message: "This operation is deprecated.") - open class func findPetsByTags(tags: [String], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: [Pet]?, _ error: Error?) -> Void)) { + open class func findPetsByTags(tags: [String], apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: [Pet]?, _ error: Error?) -> Void)) { findPetsByTagsWithRequestBuilder(tags: tags).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -192,24 +196,24 @@ import Foundation */ @available(*, deprecated, message: "This operation is deprecated.") open class func findPetsByTagsWithRequestBuilder(tags: [String]) -> RequestBuilder<[Pet]> { - let path = "/pet/findByTags" - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + let localVariablePath = "/pet/findByTags" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - var urlComponents = URLComponents(string: URLString) - urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ + var localVariableUrlComponents = URLComponents(string: localVariableURLString) + localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ "tags": tags.encodeToJSON(), ]) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -219,7 +223,7 @@ import Foundation - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func getPetById(petId: Int64, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Pet?, _ error: Error?) -> Void)) { + open class func getPetById(petId: Int64, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Pet?, _ error: Error?) -> Void)) { getPetByIdWithRequestBuilder(petId: petId).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -241,24 +245,24 @@ import Foundation - returns: RequestBuilder */ open class func getPetByIdWithRequestBuilder(petId: Int64) -> RequestBuilder { - var path = "/pet/{petId}" + var localVariablePath = "/pet/{petId}" let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))" let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" - path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + localVariablePath = localVariablePath.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -268,7 +272,7 @@ import Foundation - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func updatePet(body: Pet, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func updatePet(body: Pet, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { updatePetWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -289,21 +293,21 @@ import Foundation - returns: RequestBuilder */ open class func updatePetWithRequestBuilder(body: Pet) -> RequestBuilder { - let path = "/pet" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/pet" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "PUT", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -315,7 +319,7 @@ import Foundation - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func updatePetWithForm(petId: Int64, name: String? = nil, status: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func updatePetWithForm(petId: Int64, name: String? = nil, status: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { updatePetWithFormWithRequestBuilder(petId: petId, name: name, status: status).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -338,30 +342,30 @@ import Foundation - returns: RequestBuilder */ open class func updatePetWithFormWithRequestBuilder(petId: Int64, name: String? = nil, status: String? = nil) -> RequestBuilder { - var path = "/pet/{petId}" + var localVariablePath = "/pet/{petId}" let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))" let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" - path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path - let formParams: [String: Any?] = [ + localVariablePath = localVariablePath.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableFormParams: [String: Any?] = [ "name": name?.encodeToJSON(), "status": status?.encodeToJSON(), ] - let nonNullParameters = APIHelper.rejectNil(formParams) - let parameters = APIHelper.convertBoolToString(nonNullParameters) + let localVariableNonNullParameters = APIHelper.rejectNil(localVariableFormParams) + let localVariableParameters = APIHelper.convertBoolToString(localVariableNonNullParameters) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ "Content-Type": "application/x-www-form-urlencoded", ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -373,7 +377,7 @@ import Foundation - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func uploadFile(petId: Int64, additionalMetadata: String? = nil, file: URL? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: ApiResponse?, _ error: Error?) -> Void)) { + open class func uploadFile(petId: Int64, additionalMetadata: String? = nil, file: URL? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: ApiResponse?, _ error: Error?) -> Void)) { uploadFileWithRequestBuilder(petId: petId, additionalMetadata: additionalMetadata, file: file).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -396,30 +400,30 @@ import Foundation - returns: RequestBuilder */ open class func uploadFileWithRequestBuilder(petId: Int64, additionalMetadata: String? = nil, file: URL? = nil) -> RequestBuilder { - var path = "/pet/{petId}/uploadImage" + var localVariablePath = "/pet/{petId}/uploadImage" let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))" let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" - path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path - let formParams: [String: Any?] = [ + localVariablePath = localVariablePath.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableFormParams: [String: Any?] = [ "additionalMetadata": additionalMetadata?.encodeToJSON(), "file": file?.encodeToJSON(), ] - let nonNullParameters = APIHelper.rejectNil(formParams) - let parameters = APIHelper.convertBoolToString(nonNullParameters) + let localVariableNonNullParameters = APIHelper.rejectNil(localVariableFormParams) + let localVariableParameters = APIHelper.convertBoolToString(localVariableNonNullParameters) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ "Content-Type": "multipart/form-data", ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -431,7 +435,7 @@ import Foundation - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func uploadFileWithRequiredFile(petId: Int64, requiredFile: URL, additionalMetadata: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: ApiResponse?, _ error: Error?) -> Void)) { + open class func uploadFileWithRequiredFile(petId: Int64, requiredFile: URL, additionalMetadata: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: ApiResponse?, _ error: Error?) -> Void)) { uploadFileWithRequiredFileWithRequestBuilder(petId: petId, requiredFile: requiredFile, additionalMetadata: additionalMetadata).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -454,30 +458,29 @@ import Foundation - returns: RequestBuilder */ open class func uploadFileWithRequiredFileWithRequestBuilder(petId: Int64, requiredFile: URL, additionalMetadata: String? = nil) -> RequestBuilder { - var path = "/fake/{petId}/uploadImageWithRequiredFile" + var localVariablePath = "/fake/{petId}/uploadImageWithRequiredFile" let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))" let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" - path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path - let formParams: [String: Any?] = [ + localVariablePath = localVariablePath.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableFormParams: [String: Any?] = [ "additionalMetadata": additionalMetadata?.encodeToJSON(), "requiredFile": requiredFile.encodeToJSON(), ] - let nonNullParameters = APIHelper.rejectNil(formParams) - let parameters = APIHelper.convertBoolToString(nonNullParameters) + let localVariableNonNullParameters = APIHelper.rejectNil(localVariableFormParams) + let localVariableParameters = APIHelper.convertBoolToString(localVariableNonNullParameters) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ "Content-Type": "multipart/form-data", ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } - } diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift index 990aaaef8be..af6cb556b0c 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift @@ -6,8 +6,12 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif @objc open class StoreAPI : NSObject { + /** Delete purchase order by ID @@ -15,7 +19,7 @@ import Foundation - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func deleteOrder(orderId: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func deleteOrder(orderId: String, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { deleteOrderWithRequestBuilder(orderId: orderId).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -34,24 +38,24 @@ import Foundation - returns: RequestBuilder */ open class func deleteOrderWithRequestBuilder(orderId: String) -> RequestBuilder { - var path = "/store/order/{order_id}" + var localVariablePath = "/store/order/{order_id}" let orderIdPreEscape = "\(APIHelper.mapValueToPathItem(orderId))" let orderIdPostEscape = orderIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" - path = path.replacingOccurrences(of: "{order_id}", with: orderIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + localVariablePath = localVariablePath.replacingOccurrences(of: "{order_id}", with: orderIdPostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "DELETE", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -60,7 +64,7 @@ import Foundation - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func getInventory(apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: [String: Int]?, _ error: Error?) -> Void)) { + open class func getInventory(apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: [String: Int]?, _ error: Error?) -> Void)) { getInventoryWithRequestBuilder().execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -81,21 +85,21 @@ import Foundation - returns: RequestBuilder<[String: Int]> */ open class func getInventoryWithRequestBuilder() -> RequestBuilder<[String: Int]> { - let path = "/store/inventory" - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + let localVariablePath = "/store/inventory" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder<[String: Int]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder<[String: Int]>.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -105,7 +109,7 @@ import Foundation - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func getOrderById(orderId: Int64, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Order?, _ error: Error?) -> Void)) { + open class func getOrderById(orderId: Int64, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Order?, _ error: Error?) -> Void)) { getOrderByIdWithRequestBuilder(orderId: orderId).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -124,24 +128,24 @@ import Foundation - returns: RequestBuilder */ open class func getOrderByIdWithRequestBuilder(orderId: Int64) -> RequestBuilder { - var path = "/store/order/{order_id}" + var localVariablePath = "/store/order/{order_id}" let orderIdPreEscape = "\(APIHelper.mapValueToPathItem(orderId))" let orderIdPostEscape = orderIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" - path = path.replacingOccurrences(of: "{order_id}", with: orderIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + localVariablePath = localVariablePath.replacingOccurrences(of: "{order_id}", with: orderIdPostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -151,7 +155,7 @@ import Foundation - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func placeOrder(body: Order, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Order?, _ error: Error?) -> Void)) { + open class func placeOrder(body: Order, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Order?, _ error: Error?) -> Void)) { placeOrderWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -169,21 +173,20 @@ import Foundation - returns: RequestBuilder */ open class func placeOrderWithRequestBuilder(body: Order) -> RequestBuilder { - let path = "/store/order" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/store/order" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } - } diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift index 8fd6953a3f6..8e2627a0aaf 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift @@ -6,8 +6,12 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif @objc open class UserAPI : NSObject { + /** Create user @@ -15,7 +19,7 @@ import Foundation - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func createUser(body: User, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func createUser(body: User, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { createUserWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -34,21 +38,21 @@ import Foundation - returns: RequestBuilder */ open class func createUserWithRequestBuilder(body: User) -> RequestBuilder { - let path = "/user" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/user" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -58,7 +62,7 @@ import Foundation - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func createUsersWithArrayInput(body: [User], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func createUsersWithArrayInput(body: [User], apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { createUsersWithArrayInputWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -76,21 +80,21 @@ import Foundation - returns: RequestBuilder */ open class func createUsersWithArrayInputWithRequestBuilder(body: [User]) -> RequestBuilder { - let path = "/user/createWithArray" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/user/createWithArray" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -100,7 +104,7 @@ import Foundation - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func createUsersWithListInput(body: [User], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func createUsersWithListInput(body: [User], apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { createUsersWithListInputWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -118,21 +122,21 @@ import Foundation - returns: RequestBuilder */ open class func createUsersWithListInputWithRequestBuilder(body: [User]) -> RequestBuilder { - let path = "/user/createWithList" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/user/createWithList" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -142,7 +146,7 @@ import Foundation - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func deleteUser(username: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func deleteUser(username: String, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { deleteUserWithRequestBuilder(username: username).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -161,24 +165,24 @@ import Foundation - returns: RequestBuilder */ open class func deleteUserWithRequestBuilder(username: String) -> RequestBuilder { - var path = "/user/{username}" + var localVariablePath = "/user/{username}" let usernamePreEscape = "\(APIHelper.mapValueToPathItem(username))" let usernamePostEscape = usernamePreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" - path = path.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + localVariablePath = localVariablePath.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "DELETE", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -188,7 +192,7 @@ import Foundation - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func getUserByName(username: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: User?, _ error: Error?) -> Void)) { + open class func getUserByName(username: String, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: User?, _ error: Error?) -> Void)) { getUserByNameWithRequestBuilder(username: username).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -206,24 +210,24 @@ import Foundation - returns: RequestBuilder */ open class func getUserByNameWithRequestBuilder(username: String) -> RequestBuilder { - var path = "/user/{username}" + var localVariablePath = "/user/{username}" let usernamePreEscape = "\(APIHelper.mapValueToPathItem(username))" let usernamePostEscape = usernamePreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" - path = path.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + localVariablePath = localVariablePath.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -234,7 +238,7 @@ import Foundation - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func loginUser(username: String, password: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: String?, _ error: Error?) -> Void)) { + open class func loginUser(username: String, password: String, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: String?, _ error: Error?) -> Void)) { loginUserWithRequestBuilder(username: username, password: password).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -254,25 +258,25 @@ import Foundation - returns: RequestBuilder */ open class func loginUserWithRequestBuilder(username: String, password: String) -> RequestBuilder { - let path = "/user/login" - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + let localVariablePath = "/user/login" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - var urlComponents = URLComponents(string: URLString) - urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ + var localVariableUrlComponents = URLComponents(string: localVariableURLString) + localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ "username": username.encodeToJSON(), "password": password.encodeToJSON(), ]) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -281,7 +285,7 @@ import Foundation - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func logoutUser(apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func logoutUser(apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { logoutUserWithRequestBuilder().execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -298,21 +302,21 @@ import Foundation - returns: RequestBuilder */ open class func logoutUserWithRequestBuilder() -> RequestBuilder { - let path = "/user/logout" - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + let localVariablePath = "/user/logout" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -323,7 +327,7 @@ import Foundation - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func updateUser(username: String, body: User, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func updateUser(username: String, body: User, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { updateUserWithRequestBuilder(username: username, body: body).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -343,24 +347,23 @@ import Foundation - returns: RequestBuilder */ open class func updateUserWithRequestBuilder(username: String, body: User) -> RequestBuilder { - var path = "/user/{username}" + var localVariablePath = "/user/{username}" let usernamePreEscape = "\(APIHelper.mapValueToPathItem(username))" let usernamePostEscape = usernamePreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" - path = path.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + localVariablePath = localVariablePath.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "PUT", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } - } diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Configuration.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Configuration.swift index 18edabbed78..8fb05331889 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Configuration.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Configuration.swift @@ -7,6 +7,7 @@ import Foundation open class Configuration { + // This value is used to configure the date formatter that is used to serialize dates into JSON format. // You must set it prior to encoding any dates, and it will only be read once. @available(*, unavailable, message: "To set a different date format, use CodableHelper.dateFormatter instead.") diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Extensions.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Extensions.swift index 3aef2d1d6c5..e23035dde30 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Extensions.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Extensions.swift @@ -5,7 +5,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif extension Bool: JSONEncodable { func encodeToJSON() -> Any { return self as Any } @@ -184,44 +186,3 @@ extension HTTPURLResponse { return Array(200 ..< 300).contains(statusCode) } } - -extension AnyCodable: Hashable { - public func hash(into hasher: inout Hasher) { - switch value { - case let value as Bool: - hasher.combine(value) - case let value as Int: - hasher.combine(value) - case let value as Int8: - hasher.combine(value) - case let value as Int16: - hasher.combine(value) - case let value as Int32: - hasher.combine(value) - case let value as Int64: - hasher.combine(value) - case let value as UInt: - hasher.combine(value) - case let value as UInt8: - hasher.combine(value) - case let value as UInt16: - hasher.combine(value) - case let value as UInt32: - hasher.combine(value) - case let value as UInt64: - hasher.combine(value) - case let value as Float: - hasher.combine(value) - case let value as Double: - hasher.combine(value) - case let value as String: - hasher.combine(value) - case let value as [String: AnyCodable]: - hasher.combine(value) - case let value as [AnyCodable]: - hasher.combine(value) - default: - hasher.combine(0) - } - } -} \ No newline at end of file diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesClass.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesClass.swift index aab3e933f3f..1421cb642ee 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesClass.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesClass.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif @objc public class AdditionalPropertiesClass: NSObject, Codable { @@ -17,6 +19,7 @@ import AnyCodable self.mapString = mapString self.mapMapString = mapMapString } + public enum CodingKeys: String, CodingKey, CaseIterable { case mapString = "map_string" case mapMapString = "map_map_string" @@ -29,7 +32,5 @@ import AnyCodable try container.encodeIfPresent(mapString, forKey: .mapString) try container.encodeIfPresent(mapMapString, forKey: .mapMapString) } - - - } + diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Animal.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Animal.swift index edd4017fd47..d60621e7bf6 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Animal.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Animal.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif @objc public class Animal: NSObject, Codable { @@ -17,6 +19,7 @@ import AnyCodable self._className = _className self.color = color } + public enum CodingKeys: String, CodingKey, CaseIterable { case _className = "className" case color @@ -29,7 +32,5 @@ import AnyCodable try container.encode(_className, forKey: ._className) try container.encodeIfPresent(color, forKey: .color) } - - - } + diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/AnimalFarm.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/AnimalFarm.swift index b20b894a1ad..a0b09cb9761 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/AnimalFarm.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/AnimalFarm.swift @@ -6,6 +6,8 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public typealias AnimalFarm = [Animal] diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift index 7c6f40923fa..1b42b26535c 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif @objc public class ApiResponse: NSObject, Codable { @@ -24,6 +26,7 @@ import AnyCodable self.type = type self.message = message } + public enum CodingKeys: String, CodingKey, CaseIterable { case code case type @@ -38,7 +41,5 @@ import AnyCodable try container.encodeIfPresent(type, forKey: .type) try container.encodeIfPresent(message, forKey: .message) } - - - } + diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfArrayOfNumberOnly.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfArrayOfNumberOnly.swift index 1971654130e..08aca8598d0 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfArrayOfNumberOnly.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfArrayOfNumberOnly.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif @objc public class ArrayOfArrayOfNumberOnly: NSObject, Codable { @@ -15,6 +17,7 @@ import AnyCodable public init(arrayArrayNumber: [[Double]]? = nil) { self.arrayArrayNumber = arrayArrayNumber } + public enum CodingKeys: String, CodingKey, CaseIterable { case arrayArrayNumber = "ArrayArrayNumber" } @@ -25,7 +28,5 @@ import AnyCodable var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(arrayArrayNumber, forKey: .arrayArrayNumber) } - - - } + diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfNumberOnly.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfNumberOnly.swift index 5802e520a2a..e8114a8f45e 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfNumberOnly.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfNumberOnly.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif @objc public class ArrayOfNumberOnly: NSObject, Codable { @@ -15,6 +17,7 @@ import AnyCodable public init(arrayNumber: [Double]? = nil) { self.arrayNumber = arrayNumber } + public enum CodingKeys: String, CodingKey, CaseIterable { case arrayNumber = "ArrayNumber" } @@ -25,7 +28,5 @@ import AnyCodable var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(arrayNumber, forKey: .arrayNumber) } - - - } + diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/ArrayTest.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/ArrayTest.swift index 1f33262b749..be0dea61b91 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/ArrayTest.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/ArrayTest.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif @objc public class ArrayTest: NSObject, Codable { @@ -19,6 +21,7 @@ import AnyCodable self.arrayArrayOfInteger = arrayArrayOfInteger self.arrayArrayOfModel = arrayArrayOfModel } + public enum CodingKeys: String, CodingKey, CaseIterable { case arrayOfString = "array_of_string" case arrayArrayOfInteger = "array_array_of_integer" @@ -33,7 +36,5 @@ import AnyCodable try container.encodeIfPresent(arrayArrayOfInteger, forKey: .arrayArrayOfInteger) try container.encodeIfPresent(arrayArrayOfModel, forKey: .arrayArrayOfModel) } - - - } + diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Capitalization.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Capitalization.swift index 0ede392b725..6f137adc91f 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Capitalization.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Capitalization.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif @objc public class Capitalization: NSObject, Codable { @@ -26,6 +28,7 @@ import AnyCodable self.sCAETHFlowPoints = sCAETHFlowPoints self.ATT_NAME = ATT_NAME } + public enum CodingKeys: String, CodingKey, CaseIterable { case smallCamel case capitalCamel = "CapitalCamel" @@ -46,7 +49,5 @@ import AnyCodable try container.encodeIfPresent(sCAETHFlowPoints, forKey: .sCAETHFlowPoints) try container.encodeIfPresent(ATT_NAME, forKey: .ATT_NAME) } - - - } + diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Cat.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Cat.swift index ac482af7867..60eccac9412 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Cat.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Cat.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif @objc public class Cat: NSObject, Codable { @@ -24,6 +26,7 @@ import AnyCodable self.color = color self.declawed = declawed } + public enum CodingKeys: String, CodingKey, CaseIterable { case _className = "className" case color @@ -38,7 +41,5 @@ import AnyCodable try container.encodeIfPresent(color, forKey: .color) try container.encodeIfPresent(declawed, forKey: .declawed) } - - - } + diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/CatAllOf.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/CatAllOf.swift index 714af722413..cce886558e8 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/CatAllOf.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/CatAllOf.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif @objc public class CatAllOf: NSObject, Codable { @@ -20,6 +22,7 @@ import AnyCodable public init(declawed: Bool? = nil) { self.declawed = declawed } + public enum CodingKeys: String, CodingKey, CaseIterable { case declawed } @@ -30,7 +33,5 @@ import AnyCodable var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(declawed, forKey: .declawed) } - - - } + diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Category.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Category.swift index 4545308c0b5..c8e542ad6b5 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Category.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Category.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif @objc public class Category: NSObject, Codable { @@ -22,6 +24,7 @@ import AnyCodable self._id = _id self.name = name } + public enum CodingKeys: String, CodingKey, CaseIterable { case _id = "id" case name @@ -34,7 +37,5 @@ import AnyCodable try container.encodeIfPresent(_id, forKey: ._id) try container.encode(name, forKey: .name) } - - - } + diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/ClassModel.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/ClassModel.swift index a16525261cd..6bc90a989bd 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/ClassModel.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/ClassModel.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif /** Model for testing model with \"_class\" property */ @objc public class ClassModel: NSObject, Codable { @@ -16,6 +18,7 @@ import AnyCodable public init(_class: String? = nil) { self._class = _class } + public enum CodingKeys: String, CodingKey, CaseIterable { case _class } @@ -26,7 +29,5 @@ import AnyCodable var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(_class, forKey: ._class) } - - - } + diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Client.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Client.swift index 1a3e53ef2f3..a3585de4f0d 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Client.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Client.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif @objc public class Client: NSObject, Codable { @@ -15,6 +17,7 @@ import AnyCodable public init(client: String? = nil) { self.client = client } + public enum CodingKeys: String, CodingKey, CaseIterable { case client } @@ -25,7 +28,5 @@ import AnyCodable var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(client, forKey: .client) } - - - } + diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Dog.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Dog.swift index b6de22c5940..2b060c8ad38 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Dog.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Dog.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif @objc public class Dog: NSObject, Codable { @@ -19,6 +21,7 @@ import AnyCodable self.color = color self.breed = breed } + public enum CodingKeys: String, CodingKey, CaseIterable { case _className = "className" case color @@ -33,7 +36,5 @@ import AnyCodable try container.encodeIfPresent(color, forKey: .color) try container.encodeIfPresent(breed, forKey: .breed) } - - - } + diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/DogAllOf.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/DogAllOf.swift index 88215365c68..d92db038ca4 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/DogAllOf.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/DogAllOf.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif @objc public class DogAllOf: NSObject, Codable { @@ -15,6 +17,7 @@ import AnyCodable public init(breed: String? = nil) { self.breed = breed } + public enum CodingKeys: String, CodingKey, CaseIterable { case breed } @@ -25,7 +28,5 @@ import AnyCodable var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(breed, forKey: .breed) } - - - } + diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/EnumArrays.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/EnumArrays.swift index c3f1766d81c..1269cb72e27 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/EnumArrays.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/EnumArrays.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif @objc public class EnumArrays: NSObject, Codable { @@ -25,6 +27,7 @@ import AnyCodable self.justSymbol = justSymbol self.arrayEnum = arrayEnum } + public enum CodingKeys: String, CodingKey, CaseIterable { case justSymbol = "just_symbol" case arrayEnum = "array_enum" @@ -37,7 +40,5 @@ import AnyCodable try container.encodeIfPresent(justSymbol, forKey: .justSymbol) try container.encodeIfPresent(arrayEnum, forKey: .arrayEnum) } - - - } + diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/EnumClass.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/EnumClass.swift index ab01cf297f8..6ea2895aee5 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/EnumClass.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/EnumClass.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public enum EnumClass: String, Codable, CaseIterable { case abc = "_abc" diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/EnumTest.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/EnumTest.swift index ac8620deb3b..066d266386b 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/EnumTest.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/EnumTest.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif @objc public class EnumTest: NSObject, Codable { @@ -41,6 +43,7 @@ import AnyCodable self.enumNumber = enumNumber self.outerEnum = outerEnum } + public enum CodingKeys: String, CodingKey, CaseIterable { case enumString = "enum_string" case enumStringRequired = "enum_string_required" @@ -59,7 +62,5 @@ import AnyCodable try container.encodeIfPresent(enumNumber, forKey: .enumNumber) try container.encodeIfPresent(outerEnum, forKey: .outerEnum) } - - - } + diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/File.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/File.swift index 0fac5200c96..b175f6370d2 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/File.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/File.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif /** Must be named `File` for test. */ @objc public class File: NSObject, Codable { @@ -17,6 +19,7 @@ import AnyCodable public init(sourceURI: String? = nil) { self.sourceURI = sourceURI } + public enum CodingKeys: String, CodingKey, CaseIterable { case sourceURI } @@ -27,7 +30,5 @@ import AnyCodable var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(sourceURI, forKey: .sourceURI) } - - - } + diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/FileSchemaTestClass.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/FileSchemaTestClass.swift index 062b68c5e5a..24a6e66432b 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/FileSchemaTestClass.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/FileSchemaTestClass.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif @objc public class FileSchemaTestClass: NSObject, Codable { @@ -17,6 +19,7 @@ import AnyCodable self.file = file self.files = files } + public enum CodingKeys: String, CodingKey, CaseIterable { case file case files @@ -29,7 +32,5 @@ import AnyCodable try container.encodeIfPresent(file, forKey: .file) try container.encodeIfPresent(files, forKey: .files) } - - - } + diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/FormatTest.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/FormatTest.swift index dacf0f0fc21..413656ff25e 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/FormatTest.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/FormatTest.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif @objc public class FormatTest: NSObject, Codable { @@ -64,6 +66,7 @@ import AnyCodable self.uuid = uuid self.password = password } + public enum CodingKeys: String, CodingKey, CaseIterable { case integer case int32 @@ -98,7 +101,5 @@ import AnyCodable try container.encodeIfPresent(uuid, forKey: .uuid) try container.encode(password, forKey: .password) } - - - } + diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/HasOnlyReadOnly.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/HasOnlyReadOnly.swift index ac9b61b5a15..eac4a144616 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/HasOnlyReadOnly.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/HasOnlyReadOnly.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif @objc public class HasOnlyReadOnly: NSObject, Codable { @@ -17,6 +19,7 @@ import AnyCodable self.bar = bar self.foo = foo } + public enum CodingKeys: String, CodingKey, CaseIterable { case bar case foo @@ -29,7 +32,5 @@ import AnyCodable try container.encodeIfPresent(bar, forKey: .bar) try container.encodeIfPresent(foo, forKey: .foo) } - - - } + diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/List.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/List.swift index cfb6cbbe8d5..f48559c0c45 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/List.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/List.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif @objc public class List: NSObject, Codable { @@ -15,6 +17,7 @@ import AnyCodable public init(_123list: String? = nil) { self._123list = _123list } + public enum CodingKeys: String, CodingKey, CaseIterable { case _123list = "123-list" } @@ -25,7 +28,5 @@ import AnyCodable var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(_123list, forKey: ._123list) } - - - } + diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/MapTest.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/MapTest.swift index 17011781e79..68a3e128cc2 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/MapTest.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/MapTest.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif @objc public class MapTest: NSObject, Codable { @@ -25,6 +27,7 @@ import AnyCodable self.directMap = directMap self.indirectMap = indirectMap } + public enum CodingKeys: String, CodingKey, CaseIterable { case mapMapOfString = "map_map_of_string" case mapOfEnumString = "map_of_enum_string" @@ -41,7 +44,5 @@ import AnyCodable try container.encodeIfPresent(directMap, forKey: .directMap) try container.encodeIfPresent(indirectMap, forKey: .indirectMap) } - - - } + diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/MixedPropertiesAndAdditionalPropertiesClass.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/MixedPropertiesAndAdditionalPropertiesClass.swift index ee69cad2f18..1594ac4a26a 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/MixedPropertiesAndAdditionalPropertiesClass.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/MixedPropertiesAndAdditionalPropertiesClass.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif @objc public class MixedPropertiesAndAdditionalPropertiesClass: NSObject, Codable { @@ -19,6 +21,7 @@ import AnyCodable self.dateTime = dateTime self.map = map } + public enum CodingKeys: String, CodingKey, CaseIterable { case uuid case dateTime @@ -33,7 +36,5 @@ import AnyCodable try container.encodeIfPresent(dateTime, forKey: .dateTime) try container.encodeIfPresent(map, forKey: .map) } - - - } + diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Model200Response.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Model200Response.swift index 19617eb563e..dfae9880b13 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Model200Response.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Model200Response.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif /** Model for testing model name starting with number */ @objc public class Model200Response: NSObject, Codable { @@ -23,6 +25,7 @@ import AnyCodable self.name = name self._class = _class } + public enum CodingKeys: String, CodingKey, CaseIterable { case name case _class = "class" @@ -35,7 +38,5 @@ import AnyCodable try container.encodeIfPresent(name, forKey: .name) try container.encodeIfPresent(_class, forKey: ._class) } - - - } + diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Name.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Name.swift index 50b14e9343a..3b41f3cafd9 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Name.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Name.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif /** Model for testing model name same as property name */ @objc public class Name: NSObject, Codable { @@ -32,6 +34,7 @@ import AnyCodable self.property = property self._123number = _123number } + public enum CodingKeys: String, CodingKey, CaseIterable { case name case snakeCase = "snake_case" @@ -48,7 +51,5 @@ import AnyCodable try container.encodeIfPresent(property, forKey: .property) try container.encodeIfPresent(_123number, forKey: ._123number) } - - - } + diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/NumberOnly.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/NumberOnly.swift index 6da3b7f3634..b828f6d3b47 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/NumberOnly.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/NumberOnly.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif @objc public class NumberOnly: NSObject, Codable { @@ -15,6 +17,7 @@ import AnyCodable public init(justNumber: Double? = nil) { self.justNumber = justNumber } + public enum CodingKeys: String, CodingKey, CaseIterable { case justNumber = "JustNumber" } @@ -25,7 +28,5 @@ import AnyCodable var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(justNumber, forKey: .justNumber) } - - - } + diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Order.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Order.swift index ad21080d024..27237e43da7 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Order.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Order.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif @objc public class Order: NSObject, Codable { @@ -51,6 +53,7 @@ import AnyCodable self.status = status self.complete = complete } + public enum CodingKeys: String, CodingKey, CaseIterable { case _id = "id" case petId @@ -71,7 +74,5 @@ import AnyCodable try container.encodeIfPresent(status, forKey: .status) try container.encodeIfPresent(complete, forKey: .complete) } - - - } + diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/OuterComposite.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/OuterComposite.swift index ad7118aae8b..bbc4536d428 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/OuterComposite.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/OuterComposite.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif @objc public class OuterComposite: NSObject, Codable { @@ -24,6 +26,7 @@ import AnyCodable self.myString = myString self.myBoolean = myBoolean } + public enum CodingKeys: String, CodingKey, CaseIterable { case myNumber = "my_number" case myString = "my_string" @@ -38,7 +41,5 @@ import AnyCodable try container.encodeIfPresent(myString, forKey: .myString) try container.encodeIfPresent(myBoolean, forKey: .myBoolean) } - - - } + diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/OuterEnum.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/OuterEnum.swift index 9bd6f3bef8f..76c34b3c2ce 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/OuterEnum.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/OuterEnum.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public enum OuterEnum: String, Codable, CaseIterable { case placed = "placed" diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Pet.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Pet.swift index dcd875c0898..a59ef82eb80 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Pet.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Pet.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif @objc public class Pet: NSObject, Codable { @@ -36,6 +38,7 @@ import AnyCodable self.tags = tags self.status = status } + public enum CodingKeys: String, CodingKey, CaseIterable { case _id = "id" case category @@ -56,7 +59,5 @@ import AnyCodable try container.encodeIfPresent(tags, forKey: .tags) try container.encodeIfPresent(status, forKey: .status) } - - - } + diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/ReadOnlyFirst.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/ReadOnlyFirst.swift index 1b278c72d11..8aef5456332 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/ReadOnlyFirst.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/ReadOnlyFirst.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif @objc public class ReadOnlyFirst: NSObject, Codable { @@ -17,6 +19,7 @@ import AnyCodable self.bar = bar self.baz = baz } + public enum CodingKeys: String, CodingKey, CaseIterable { case bar case baz @@ -29,7 +32,5 @@ import AnyCodable try container.encodeIfPresent(bar, forKey: .bar) try container.encodeIfPresent(baz, forKey: .baz) } - - - } + diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Return.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Return.swift index f5c4e90d0e1..f497fdc7e09 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Return.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Return.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif /** Model for testing reserved words */ @objc public class Return: NSObject, Codable { @@ -21,6 +23,7 @@ import AnyCodable public init(_return: Int? = nil) { self._return = _return } + public enum CodingKeys: String, CodingKey, CaseIterable { case _return = "return" } @@ -31,7 +34,5 @@ import AnyCodable var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(_return, forKey: ._return) } - - - } + diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/SpecialModelName.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/SpecialModelName.swift index a512f5fb327..8a5860ae0b9 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/SpecialModelName.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/SpecialModelName.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif @objc public class SpecialModelName: NSObject, Codable { @@ -20,6 +22,7 @@ import AnyCodable public init(specialPropertyName: Int64? = nil) { self.specialPropertyName = specialPropertyName } + public enum CodingKeys: String, CodingKey, CaseIterable { case specialPropertyName = "$special[property.name]" } @@ -30,7 +33,5 @@ import AnyCodable var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(specialPropertyName, forKey: .specialPropertyName) } - - - } + diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/StringBooleanMap.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/StringBooleanMap.swift index 1cb86591c3c..4708c93daa0 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/StringBooleanMap.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/StringBooleanMap.swift @@ -6,12 +6,16 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif @objc public class StringBooleanMap: NSObject, Codable { + public enum CodingKeys: CodingKey, CaseIterable { } + public var additionalProperties: [String: Bool] = [:] public subscript(key: String) -> Bool? { @@ -38,11 +42,11 @@ import AnyCodable // Decodable protocol methods public required init(from decoder: Decoder) throws { - let container = try decoder.container(keyedBy: String.self) + let container = try decoder.container(keyedBy: CodingKeys.self) var nonAdditionalPropertyKeys = Set() - additionalProperties = try container.decodeMap(Bool.self, excludedKeys: nonAdditionalPropertyKeys) + let additionalPropertiesContainer = try decoder.container(keyedBy: String.self) + additionalProperties = try additionalPropertiesContainer.decodeMap(Bool.self, excludedKeys: nonAdditionalPropertyKeys) } - - } + diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift index eea33c371ac..6150ef4895f 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif @objc public class Tag: NSObject, Codable { @@ -22,6 +24,7 @@ import AnyCodable self._id = _id self.name = name } + public enum CodingKeys: String, CodingKey, CaseIterable { case _id = "id" case name @@ -34,7 +37,5 @@ import AnyCodable try container.encodeIfPresent(_id, forKey: ._id) try container.encodeIfPresent(name, forKey: .name) } - - - } + diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderDefault.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderDefault.swift index b6c174ed146..27408db6f27 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderDefault.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderDefault.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif @objc public class TypeHolderDefault: NSObject, Codable { @@ -23,6 +25,7 @@ import AnyCodable self.boolItem = boolItem self.arrayItem = arrayItem } + public enum CodingKeys: String, CodingKey, CaseIterable { case stringItem = "string_item" case numberItem = "number_item" @@ -41,7 +44,5 @@ import AnyCodable try container.encode(boolItem, forKey: .boolItem) try container.encode(arrayItem, forKey: .arrayItem) } - - - } + diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderExample.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderExample.swift index d794fec5ce9..61c7c8b4fb4 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderExample.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderExample.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif @objc public class TypeHolderExample: NSObject, Codable { @@ -23,6 +25,7 @@ import AnyCodable self.boolItem = boolItem self.arrayItem = arrayItem } + public enum CodingKeys: String, CodingKey, CaseIterable { case stringItem = "string_item" case numberItem = "number_item" @@ -41,7 +44,5 @@ import AnyCodable try container.encode(boolItem, forKey: .boolItem) try container.encode(arrayItem, forKey: .arrayItem) } - - - } + diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/User.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/User.swift index f233f6cccbd..3c71f76aab0 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/User.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/User.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif @objc public class User: NSObject, Codable { @@ -40,6 +42,7 @@ import AnyCodable self.phone = phone self.userStatus = userStatus } + public enum CodingKeys: String, CodingKey, CaseIterable { case _id = "id" case username @@ -64,7 +67,5 @@ import AnyCodable try container.encodeIfPresent(phone, forKey: .phone) try container.encodeIfPresent(userStatus, forKey: .userStatus) } - - - } + 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 52b2071ec1a..41959190a26 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift @@ -93,14 +93,14 @@ open class URLSessionRequestBuilder: RequestBuilder { return modifiedRequest } - override open func execute(_ apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, _ completion: @escaping (_ result: Swift.Result, Error>) -> Void) { + override open func execute(_ apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, _ completion: @escaping (_ result: Swift.Result, Error>) -> Void) { let urlSessionId = UUID().uuidString // Create a new manager for each request to customize its request header let urlSession = createURLSession() urlSessionStore[urlSessionId] = urlSession guard let xMethod = HTTPMethod(rawValue: method) else { - fatalError("Unsuported Http method - \(method)") + fatalError("Unsupported Http method - \(method)") } let encoding: ParameterEncoding @@ -119,7 +119,7 @@ open class URLSessionRequestBuilder: RequestBuilder { } else if contentType == "application/x-www-form-urlencoded" { encoding = FormURLEncoding() } else { - fatalError("Unsuported Media Type - \(contentType)") + fatalError("Unsupported Media Type - \(contentType)") } } @@ -205,16 +205,18 @@ open class URLSessionRequestBuilder: RequestBuilder { } let fileManager = FileManager.default - let documentsDirectory = fileManager.urls(for: .documentDirectory, in: .userDomainMask)[0] + let cachesDirectory = fileManager.urls(for: .cachesDirectory, in: .userDomainMask)[0] let requestURL = try getURL(from: urlRequest) var requestPath = try getPath(from: requestURL) if let headerFileName = getFileName(fromContentDisposition: httpResponse.allHeaderFields["Content-Disposition"] as? String) { requestPath = requestPath.appending("/\(headerFileName)") + } else { + requestPath = requestPath.appending("/tmp.PetstoreClient.\(UUID().uuidString)") } - let filePath = documentsDirectory.appendingPathComponent(requestPath) + let filePath = cachesDirectory.appendingPathComponent(requestPath) let directoryPath = filePath.deletingLastPathComponent().path try fileManager.createDirectory(atPath: directoryPath, withIntermediateDirectories: true, attributes: nil) @@ -232,6 +234,10 @@ open class URLSessionRequestBuilder: RequestBuilder { completion(.success(Response(response: httpResponse, body: nil))) + case is Data.Type: + + completion(.success(Response(response: httpResponse, body: data as? T))) + default: completion(.success(Response(response: httpResponse, body: data as? T))) @@ -244,7 +250,7 @@ open class URLSessionRequestBuilder: RequestBuilder { for (key, value) in headers { httpHeaders[key] = value } - for (key, value) in PetstoreClientAPI.customHeaders { + for (key, value) in PetstoreClient.customHeaders { httpHeaders[key] = value } return httpHeaders @@ -328,6 +334,43 @@ open class URLSessionDecodableRequestBuilder: URLSessionRequestBui completion(.success(Response(response: httpResponse, body: body as? T))) + case is URL.Type: + do { + + guard error == nil else { + throw DownloadException.responseFailed + } + + guard let data = data else { + throw DownloadException.responseDataMissing + } + + let fileManager = FileManager.default + let cachesDirectory = fileManager.urls(for: .cachesDirectory, in: .userDomainMask)[0] + let requestURL = try getURL(from: urlRequest) + + var requestPath = try getPath(from: requestURL) + + if let headerFileName = getFileName(fromContentDisposition: httpResponse.allHeaderFields["Content-Disposition"] as? String) { + requestPath = requestPath.appending("/\(headerFileName)") + } else { + requestPath = requestPath.appending("/tmp.PetstoreClient.\(UUID().uuidString)") + } + + let filePath = cachesDirectory.appendingPathComponent(requestPath) + let directoryPath = filePath.deletingLastPathComponent().path + + try fileManager.createDirectory(atPath: directoryPath, withIntermediateDirectories: true, attributes: nil) + try data.write(to: filePath, options: .atomic) + + completion(.success(Response(response: httpResponse, body: filePath as? T))) + + } catch let requestParserError as DownloadException { + completion(.failure(ErrorResponse.error(400, data, response, requestParserError))) + } catch { + completion(.failure(ErrorResponse.error(400, data, response, error))) + } + case is Void.Type: completion(.success(Response(response: httpResponse, body: nil))) diff --git a/samples/client/petstore/swift5/objcCompatible/docs/FakeAPI.md b/samples/client/petstore/swift5/objcCompatible/docs/FakeAPI.md index 712fa591f2f..779e16b3ce6 100644 --- a/samples/client/petstore/swift5/objcCompatible/docs/FakeAPI.md +++ b/samples/client/petstore/swift5/objcCompatible/docs/FakeAPI.md @@ -379,7 +379,7 @@ import PetstoreClient let number = 987 // Double | None let double = 987 // Double | None let patternWithoutDelimiter = "patternWithoutDelimiter_example" // String | None -let byte = 987 // Data | None +let byte = Data([9, 8, 7]) // Data | None let integer = 987 // Int | None (optional) let int32 = 987 // Int | None (optional) let int64 = 987 // Int64 | None (optional) diff --git a/samples/client/petstore/swift5/objcCompatible/project.yml b/samples/client/petstore/swift5/objcCompatible/project.yml index 5528eeee513..0493cf65896 100644 --- a/samples/client/petstore/swift5/objcCompatible/project.yml +++ b/samples/client/petstore/swift5/objcCompatible/project.yml @@ -11,5 +11,5 @@ targets: settings: APPLICATION_EXTENSION_API_ONLY: true scheme: {} - + dependencies: - carthage: AnyCodable diff --git a/samples/client/petstore/swift5/oneOf/.gitignore b/samples/client/petstore/swift5/oneOf/.gitignore new file mode 100644 index 00000000000..627d360a903 --- /dev/null +++ b/samples/client/petstore/swift5/oneOf/.gitignore @@ -0,0 +1,105 @@ +# Created by https://www.toptal.com/developers/gitignore/api/swift,xcode +# Edit at https://www.toptal.com/developers/gitignore?templates=swift,xcode + +### Swift ### +# Xcode +# +# gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore + +## User settings +xcuserdata/ + +## compatibility with Xcode 8 and earlier (ignoring not required starting Xcode 9) +*.xcscmblueprint +*.xccheckout + +## compatibility with Xcode 3 and earlier (ignoring not required starting Xcode 4) +build/ +DerivedData/ +*.moved-aside +*.pbxuser +!default.pbxuser +*.mode1v3 +!default.mode1v3 +*.mode2v3 +!default.mode2v3 +*.perspectivev3 +!default.perspectivev3 + +## Obj-C/Swift specific +*.hmap + +## App packaging +*.ipa +*.dSYM.zip +*.dSYM + +## Playgrounds +timeline.xctimeline +playground.xcworkspace + +# Swift Package Manager +# Add this line if you want to avoid checking in source code from Swift Package Manager dependencies. +# Packages/ +# Package.pins +# Package.resolved +# *.xcodeproj +# Xcode automatically generates this directory with a .xcworkspacedata file and xcuserdata +# hence it is not needed unless you have added a package configuration file to your project +# .swiftpm + +.build/ + +# CocoaPods +# We recommend against adding the Pods directory to your .gitignore. However +# you should judge for yourself, the pros and cons are mentioned at: +# https://guides.cocoapods.org/using/using-cocoapods.html#should-i-check-the-pods-directory-into-source-control +# Pods/ +# Add this line if you want to avoid checking in source code from the Xcode workspace +# *.xcworkspace + +# Carthage +# Add this line if you want to avoid checking in source code from Carthage dependencies. +# Carthage/Checkouts + +Carthage/Build/ + +# Add this lines if you are using Accio dependency management (Deprecated since Xcode 12) +# Dependencies/ +# .accio/ + +# fastlane +# It is recommended to not store the screenshots in the git repo. +# Instead, use fastlane to re-generate the screenshots whenever they are needed. +# For more information about the recommended setup visit: +# https://docs.fastlane.tools/best-practices/source-control/#source-control + +fastlane/report.xml +fastlane/Preview.html +fastlane/screenshots/**/*.png +fastlane/test_output + +# Code Injection +# After new code Injection tools there's a generated folder /iOSInjectionProject +# https://github.com/johnno1962/injectionforxcode + +iOSInjectionProject/ + +### Xcode ### +# Xcode +# gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore + + + + +## Gcc Patch +/*.gcno + +### Xcode Patch ### +*.xcodeproj/* +!*.xcodeproj/project.pbxproj +!*.xcodeproj/xcshareddata/ +!*.xcworkspace/contents.xcworkspacedata +**/xcshareddata/WorkspaceSettings.xcsettings + +# End of https://www.toptal.com/developers/gitignore/api/swift,xcode diff --git a/samples/client/petstore/swift5/oneOf/.openapi-generator-ignore b/samples/client/petstore/swift5/oneOf/.openapi-generator-ignore new file mode 100644 index 00000000000..7484ee590a3 --- /dev/null +++ b/samples/client/petstore/swift5/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/petstore/swift5/oneOf/.openapi-generator/FILES b/samples/client/petstore/swift5/oneOf/.openapi-generator/FILES new file mode 100644 index 00000000000..421958ec1d2 --- /dev/null +++ b/samples/client/petstore/swift5/oneOf/.openapi-generator/FILES @@ -0,0 +1,26 @@ +.gitignore +Cartfile +Package.swift +PetstoreClient.podspec +PetstoreClient/Classes/OpenAPIs/APIHelper.swift +PetstoreClient/Classes/OpenAPIs/APIs.swift +PetstoreClient/Classes/OpenAPIs/APIs/DefaultAPI.swift +PetstoreClient/Classes/OpenAPIs/CodableHelper.swift +PetstoreClient/Classes/OpenAPIs/Configuration.swift +PetstoreClient/Classes/OpenAPIs/Extensions.swift +PetstoreClient/Classes/OpenAPIs/JSONDataEncoding.swift +PetstoreClient/Classes/OpenAPIs/JSONEncodingHelper.swift +PetstoreClient/Classes/OpenAPIs/Models.swift +PetstoreClient/Classes/OpenAPIs/Models/Apple.swift +PetstoreClient/Classes/OpenAPIs/Models/Banana.swift +PetstoreClient/Classes/OpenAPIs/Models/Fruit.swift +PetstoreClient/Classes/OpenAPIs/OpenISO8601DateFormatter.swift +PetstoreClient/Classes/OpenAPIs/SynchronizedDictionary.swift +PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift +README.md +docs/Apple.md +docs/Banana.md +docs/DefaultAPI.md +docs/Fruit.md +git_push.sh +project.yml diff --git a/samples/client/petstore/swift5/oneOf/.openapi-generator/VERSION b/samples/client/petstore/swift5/oneOf/.openapi-generator/VERSION new file mode 100644 index 00000000000..4b448de535c --- /dev/null +++ b/samples/client/petstore/swift5/oneOf/.openapi-generator/VERSION @@ -0,0 +1 @@ +5.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/swift5/oneOf/Cartfile b/samples/client/petstore/swift5/oneOf/Cartfile new file mode 100644 index 00000000000..a6a6bcacb1d --- /dev/null +++ b/samples/client/petstore/swift5/oneOf/Cartfile @@ -0,0 +1,2 @@ + +github "Flight-School/AnyCodable" ~> 0.6.1 diff --git a/samples/client/petstore/swift5/oneOf/Package.resolved b/samples/client/petstore/swift5/oneOf/Package.resolved new file mode 100644 index 00000000000..79610c3b3b3 --- /dev/null +++ b/samples/client/petstore/swift5/oneOf/Package.resolved @@ -0,0 +1,16 @@ +{ + "object": { + "pins": [ + { + "package": "AnyCodable", + "repositoryURL": "https://github.com/Flight-School/AnyCodable", + "state": { + "branch": null, + "revision": "69261f239f0fffaf51495dadc4f8483fbfe97025", + "version": "0.6.1" + } + } + ] + }, + "version": 1 +} diff --git a/samples/client/petstore/swift5/oneOf/Package.swift b/samples/client/petstore/swift5/oneOf/Package.swift new file mode 100644 index 00000000000..87bb775fb72 --- /dev/null +++ b/samples/client/petstore/swift5/oneOf/Package.swift @@ -0,0 +1,33 @@ +// swift-tools-version:5.1 + +import PackageDescription + +let package = Package( + name: "PetstoreClient", + platforms: [ + .iOS(.v9), + .macOS(.v10_11), + .tvOS(.v9), + .watchOS(.v3), + ], + products: [ + // Products define the executables and libraries produced by a package, and make them visible to other packages. + .library( + name: "PetstoreClient", + targets: ["PetstoreClient"] + ), + ], + dependencies: [ + // Dependencies declare other packages that this package depends on. + .package(url: "https://github.com/Flight-School/AnyCodable", from: "0.6.1"), + ], + targets: [ + // Targets are the basic building blocks of a package. A target can define a module or a test suite. + // Targets can depend on other targets in this package, and on products in packages which this package depends on. + .target( + name: "PetstoreClient", + dependencies: ["AnyCodable", ], + path: "PetstoreClient/Classes" + ), + ] +) diff --git a/samples/client/petstore/swift5/oneOf/PetstoreClient.podspec b/samples/client/petstore/swift5/oneOf/PetstoreClient.podspec new file mode 100644 index 00000000000..0657f66982e --- /dev/null +++ b/samples/client/petstore/swift5/oneOf/PetstoreClient.podspec @@ -0,0 +1,15 @@ +Pod::Spec.new do |s| + s.name = 'PetstoreClient' + s.ios.deployment_target = '9.0' + s.osx.deployment_target = '10.11' + s.tvos.deployment_target = '9.0' + s.watchos.deployment_target = '3.0' + s.version = '0.0.1' + s.source = { :git => 'git@github.com:OpenAPITools/openapi-generator.git', :tag => 'v0.0.1' } + s.authors = '' + s.license = 'Proprietary' + s.homepage = 'https://github.com/openapitools/openapi-generator' + s.summary = 'PetstoreClient' + s.source_files = 'PetstoreClient/Classes/**/*.swift' + s.dependency 'AnyCodable-FlightSchool', '~> 0.6.1' +end diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/APIHelper.swift b/samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/APIHelper.swift similarity index 100% rename from samples/client/petstore/swift5/urlsessionLibrary/Sources/APIHelper.swift rename to samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/APIHelper.swift diff --git a/samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/APIs.swift b/samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/APIs.swift new file mode 100644 index 00000000000..ed13fa3738a --- /dev/null +++ b/samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/APIs.swift @@ -0,0 +1,65 @@ +// APIs.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation + +@available(*, deprecated, renamed: "PetstoreClient") +public typealias PetstoreClientAPI = PetstoreClient + +open class PetstoreClient { + public static var basePath = "http://localhost" + public static var customHeaders: [String: String] = [:] + public static var credential: URLCredential? + public static var requestBuilderFactory: RequestBuilderFactory = URLSessionRequestBuilderFactory() + public static var apiResponseQueue: DispatchQueue = .main +} + +open class RequestBuilder { + var credential: URLCredential? + var headers: [String: String] + public let parameters: [String: Any]? + public let method: String + public let URLString: String + + /// Optional block to obtain a reference to the request's progress instance when available. + /// With the URLSession http client the request's progress only works on iOS 11.0, macOS 10.13, macCatalyst 13.0, tvOS 11.0, watchOS 4.0. + /// If you need to get the request's progress in older OS versions, please use Alamofire http client. + public var onProgressReady: ((Progress) -> Void)? + + required public init(method: String, URLString: String, parameters: [String: Any]?, headers: [String: String] = [:]) { + self.method = method + self.URLString = URLString + self.parameters = parameters + self.headers = headers + + addHeaders(PetstoreClient.customHeaders) + } + + open func addHeaders(_ aHeaders: [String: String]) { + for (header, value) in aHeaders { + headers[header] = value + } + } + + open func execute(_ apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, _ completion: @escaping (_ result: Swift.Result, Error>) -> Void) { } + + public func addHeader(name: String, value: String) -> Self { + if !value.isEmpty { + headers[name] = value + } + return self + } + + open func addCredential() -> Self { + credential = PetstoreClient.credential + return self + } +} + +public protocol RequestBuilderFactory { + func getNonDecodableBuilder() -> RequestBuilder.Type + func getBuilder() -> RequestBuilder.Type +} diff --git a/samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/APIs/DefaultAPI.swift b/samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/APIs/DefaultAPI.swift new file mode 100644 index 00000000000..a8accc5620a --- /dev/null +++ b/samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/APIs/DefaultAPI.swift @@ -0,0 +1,52 @@ +// +// DefaultAPI.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +open class DefaultAPI { + + /** + + - parameter apiResponseQueue: The queue on which api response is dispatched. + - parameter completion: completion handler to receive the data and the error objects + */ + open class func rootGet(apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Fruit?, _ error: Error?) -> Void)) { + rootGetWithRequestBuilder().execute(apiResponseQueue) { result -> Void in + switch result { + case let .success(response): + completion(response.body, nil) + case let .failure(error): + completion(nil, error) + } + } + } + + /** + - GET / + - returns: RequestBuilder + */ + open class func rootGetWithRequestBuilder() -> RequestBuilder { + let localVariablePath = "/" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil + + let localVariableUrlComponents = URLComponents(string: localVariableURLString) + + let localVariableNillableHeaders: [String: Any?] = [ + : + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() + + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + } +} diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/CodableHelper.swift b/samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/CodableHelper.swift similarity index 100% rename from samples/client/petstore/swift5/urlsessionLibrary/Sources/CodableHelper.swift rename to samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/CodableHelper.swift diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/Configuration.swift b/samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/Configuration.swift similarity index 99% rename from samples/client/petstore/swift5/urlsessionLibrary/Sources/Configuration.swift rename to samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/Configuration.swift index 18edabbed78..8fb05331889 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/Sources/Configuration.swift +++ b/samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/Configuration.swift @@ -7,6 +7,7 @@ import Foundation open class Configuration { + // This value is used to configure the date formatter that is used to serialize dates into JSON format. // You must set it prior to encoding any dates, and it will only be read once. @available(*, unavailable, message: "To set a different date format, use CodableHelper.dateFormatter instead.") diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/Extensions.swift b/samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/Extensions.swift similarity index 78% rename from samples/client/petstore/swift5/urlsessionLibrary/Sources/Extensions.swift rename to samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/Extensions.swift index 3aef2d1d6c5..e23035dde30 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/Sources/Extensions.swift +++ b/samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/Extensions.swift @@ -5,7 +5,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif extension Bool: JSONEncodable { func encodeToJSON() -> Any { return self as Any } @@ -184,44 +186,3 @@ extension HTTPURLResponse { return Array(200 ..< 300).contains(statusCode) } } - -extension AnyCodable: Hashable { - public func hash(into hasher: inout Hasher) { - switch value { - case let value as Bool: - hasher.combine(value) - case let value as Int: - hasher.combine(value) - case let value as Int8: - hasher.combine(value) - case let value as Int16: - hasher.combine(value) - case let value as Int32: - hasher.combine(value) - case let value as Int64: - hasher.combine(value) - case let value as UInt: - hasher.combine(value) - case let value as UInt8: - hasher.combine(value) - case let value as UInt16: - hasher.combine(value) - case let value as UInt32: - hasher.combine(value) - case let value as UInt64: - hasher.combine(value) - case let value as Float: - hasher.combine(value) - case let value as Double: - hasher.combine(value) - case let value as String: - hasher.combine(value) - case let value as [String: AnyCodable]: - hasher.combine(value) - case let value as [AnyCodable]: - hasher.combine(value) - default: - hasher.combine(0) - } - } -} \ No newline at end of file diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/JSONDataEncoding.swift b/samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/JSONDataEncoding.swift similarity index 100% rename from samples/client/petstore/swift5/urlsessionLibrary/Sources/JSONDataEncoding.swift rename to samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/JSONDataEncoding.swift diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/JSONEncodingHelper.swift b/samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/JSONEncodingHelper.swift similarity index 100% rename from samples/client/petstore/swift5/urlsessionLibrary/Sources/JSONEncodingHelper.swift rename to samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/JSONEncodingHelper.swift diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/Models.swift b/samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/Models.swift similarity index 100% rename from samples/client/petstore/swift5/urlsessionLibrary/Sources/Models.swift rename to samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/Models.swift diff --git a/samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/Models/Apple.swift b/samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/Models/Apple.swift new file mode 100644 index 00000000000..ee0b5786ef1 --- /dev/null +++ b/samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/Models/Apple.swift @@ -0,0 +1,32 @@ +// +// Apple.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct Apple: Codable, Hashable { + + public var kind: String? + + public init(kind: String? = nil) { + self.kind = kind + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case kind + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(kind, forKey: .kind) + } +} + diff --git a/samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/Models/Banana.swift b/samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/Models/Banana.swift new file mode 100644 index 00000000000..1ad6e976a7e --- /dev/null +++ b/samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/Models/Banana.swift @@ -0,0 +1,32 @@ +// +// Banana.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct Banana: Codable, Hashable { + + public var count: Double? + + public init(count: Double? = nil) { + self.count = count + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case count + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(count, forKey: .count) + } +} + diff --git a/samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/Models/Fruit.swift b/samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/Models/Fruit.swift new file mode 100644 index 00000000000..d58ad1f8b31 --- /dev/null +++ b/samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/Models/Fruit.swift @@ -0,0 +1,38 @@ +// +// Fruit.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public enum Fruit: Codable { + case typeApple(Apple) + case typeBanana(Banana) + + public func encode(to encoder: Encoder) throws { + var container = encoder.singleValueContainer() + switch self { + case .typeApple(let value): + try container.encode(value) + case .typeBanana(let value): + try container.encode(value) + } + } + + public init(from decoder: Decoder) throws { + let container = try decoder.singleValueContainer() + if let value = try? container.decode(Apple.self) { + self = .typeApple(value) + } else if let value = try? container.decode(Banana.self) { + self = .typeBanana(value) + } else { + throw DecodingError.typeMismatch(Self.Type.self, .init(codingPath: decoder.codingPath, debugDescription: "Unable to decode instance of Fruit")) + } + } +} + diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/OpenISO8601DateFormatter.swift b/samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/OpenISO8601DateFormatter.swift similarity index 100% rename from samples/client/petstore/swift5/urlsessionLibrary/Sources/OpenISO8601DateFormatter.swift rename to samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/OpenISO8601DateFormatter.swift diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/SynchronizedDictionary.swift b/samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/SynchronizedDictionary.swift similarity index 100% rename from samples/client/petstore/swift5/urlsessionLibrary/Sources/SynchronizedDictionary.swift rename to samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/SynchronizedDictionary.swift diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/URLSessionImplementations.swift b/samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift similarity index 89% rename from samples/client/petstore/swift5/urlsessionLibrary/Sources/URLSessionImplementations.swift rename to samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift index 52b2071ec1a..41959190a26 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/Sources/URLSessionImplementations.swift +++ b/samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift @@ -93,14 +93,14 @@ open class URLSessionRequestBuilder: RequestBuilder { return modifiedRequest } - override open func execute(_ apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, _ completion: @escaping (_ result: Swift.Result, Error>) -> Void) { + override open func execute(_ apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, _ completion: @escaping (_ result: Swift.Result, Error>) -> Void) { let urlSessionId = UUID().uuidString // Create a new manager for each request to customize its request header let urlSession = createURLSession() urlSessionStore[urlSessionId] = urlSession guard let xMethod = HTTPMethod(rawValue: method) else { - fatalError("Unsuported Http method - \(method)") + fatalError("Unsupported Http method - \(method)") } let encoding: ParameterEncoding @@ -119,7 +119,7 @@ open class URLSessionRequestBuilder: RequestBuilder { } else if contentType == "application/x-www-form-urlencoded" { encoding = FormURLEncoding() } else { - fatalError("Unsuported Media Type - \(contentType)") + fatalError("Unsupported Media Type - \(contentType)") } } @@ -205,16 +205,18 @@ open class URLSessionRequestBuilder: RequestBuilder { } let fileManager = FileManager.default - let documentsDirectory = fileManager.urls(for: .documentDirectory, in: .userDomainMask)[0] + let cachesDirectory = fileManager.urls(for: .cachesDirectory, in: .userDomainMask)[0] let requestURL = try getURL(from: urlRequest) var requestPath = try getPath(from: requestURL) if let headerFileName = getFileName(fromContentDisposition: httpResponse.allHeaderFields["Content-Disposition"] as? String) { requestPath = requestPath.appending("/\(headerFileName)") + } else { + requestPath = requestPath.appending("/tmp.PetstoreClient.\(UUID().uuidString)") } - let filePath = documentsDirectory.appendingPathComponent(requestPath) + let filePath = cachesDirectory.appendingPathComponent(requestPath) let directoryPath = filePath.deletingLastPathComponent().path try fileManager.createDirectory(atPath: directoryPath, withIntermediateDirectories: true, attributes: nil) @@ -232,6 +234,10 @@ open class URLSessionRequestBuilder: RequestBuilder { completion(.success(Response(response: httpResponse, body: nil))) + case is Data.Type: + + completion(.success(Response(response: httpResponse, body: data as? T))) + default: completion(.success(Response(response: httpResponse, body: data as? T))) @@ -244,7 +250,7 @@ open class URLSessionRequestBuilder: RequestBuilder { for (key, value) in headers { httpHeaders[key] = value } - for (key, value) in PetstoreClientAPI.customHeaders { + for (key, value) in PetstoreClient.customHeaders { httpHeaders[key] = value } return httpHeaders @@ -328,6 +334,43 @@ open class URLSessionDecodableRequestBuilder: URLSessionRequestBui completion(.success(Response(response: httpResponse, body: body as? T))) + case is URL.Type: + do { + + guard error == nil else { + throw DownloadException.responseFailed + } + + guard let data = data else { + throw DownloadException.responseDataMissing + } + + let fileManager = FileManager.default + let cachesDirectory = fileManager.urls(for: .cachesDirectory, in: .userDomainMask)[0] + let requestURL = try getURL(from: urlRequest) + + var requestPath = try getPath(from: requestURL) + + if let headerFileName = getFileName(fromContentDisposition: httpResponse.allHeaderFields["Content-Disposition"] as? String) { + requestPath = requestPath.appending("/\(headerFileName)") + } else { + requestPath = requestPath.appending("/tmp.PetstoreClient.\(UUID().uuidString)") + } + + let filePath = cachesDirectory.appendingPathComponent(requestPath) + let directoryPath = filePath.deletingLastPathComponent().path + + try fileManager.createDirectory(atPath: directoryPath, withIntermediateDirectories: true, attributes: nil) + try data.write(to: filePath, options: .atomic) + + completion(.success(Response(response: httpResponse, body: filePath as? T))) + + } catch let requestParserError as DownloadException { + completion(.failure(ErrorResponse.error(400, data, response, requestParserError))) + } catch { + completion(.failure(ErrorResponse.error(400, data, response, error))) + } + case is Void.Type: completion(.success(Response(response: httpResponse, body: nil))) diff --git a/samples/client/petstore/swift5/oneOf/README.md b/samples/client/petstore/swift5/oneOf/README.md new file mode 100644 index 00000000000..58f7c7f65ce --- /dev/null +++ b/samples/client/petstore/swift5/oneOf/README.md @@ -0,0 +1,46 @@ +# Swift5 API client for PetstoreClient + +No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + +## 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: 0.0.1 +- Package version: +- Build package: org.openapitools.codegen.languages.Swift5ClientCodegen + +## Installation + +### Carthage + +Run `carthage update` + +### CocoaPods + +Run `pod install` + +## Documentation for API Endpoints + +All URIs are relative to *http://localhost* + +Class | Method | HTTP request | Description +------------ | ------------- | ------------- | ------------- +*DefaultAPI* | [**rootGet**](docs/DefaultAPI.md#rootget) | **GET** / | + + +## Documentation For Models + + - [Apple](docs/Apple.md) + - [Banana](docs/Banana.md) + - [Fruit](docs/Fruit.md) + + +## Documentation For Authorization + + All endpoints do not require authorization. + + +## Author + + + diff --git a/samples/client/petstore/swift5/oneOf/docs/Apple.md b/samples/client/petstore/swift5/oneOf/docs/Apple.md new file mode 100644 index 00000000000..12ead3f7cb0 --- /dev/null +++ b/samples/client/petstore/swift5/oneOf/docs/Apple.md @@ -0,0 +1,11 @@ +# Apple + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**kind** | **String** | | [optional] +**color** | **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/swift5/oneOf/docs/Banana.md b/samples/client/petstore/swift5/oneOf/docs/Banana.md new file mode 100644 index 00000000000..e194ddc30d4 --- /dev/null +++ b/samples/client/petstore/swift5/oneOf/docs/Banana.md @@ -0,0 +1,11 @@ +# Banana + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**count** | **Double** | | [optional] +**color** | **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/swift5/oneOf/docs/DefaultAPI.md b/samples/client/petstore/swift5/oneOf/docs/DefaultAPI.md new file mode 100644 index 00000000000..bcefe1e3ffa --- /dev/null +++ b/samples/client/petstore/swift5/oneOf/docs/DefaultAPI.md @@ -0,0 +1,52 @@ +# DefaultAPI + +All URIs are relative to *http://localhost* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**rootGet**](DefaultAPI.md#rootget) | **GET** / | + + +# **rootGet** +```swift + open class func rootGet(completion: @escaping (_ data: Fruit?, _ error: Error?) -> Void) +``` + + + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + + +DefaultAPI.rootGet() { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### Parameters +This endpoint does not need any parameter. + +### Return type + +[**Fruit**](Fruit.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **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/petstore/swift5/oneOf/docs/Fruit.md b/samples/client/petstore/swift5/oneOf/docs/Fruit.md new file mode 100644 index 00000000000..3efd863258b --- /dev/null +++ b/samples/client/petstore/swift5/oneOf/docs/Fruit.md @@ -0,0 +1,12 @@ +# Fruit + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**color** | **String** | | [optional] +**kind** | **String** | | [optional] +**count** | **Double** | | [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/swift5/oneOf/git_push.sh b/samples/client/petstore/swift5/oneOf/git_push.sh new file mode 100644 index 00000000000..ced3be2b0c7 --- /dev/null +++ b/samples/client/petstore/swift5/oneOf/git_push.sh @@ -0,0 +1,58 @@ +#!/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-pestore-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/swift5/oneOf/pom.xml b/samples/client/petstore/swift5/oneOf/pom.xml new file mode 100644 index 00000000000..c1b201eb3b4 --- /dev/null +++ b/samples/client/petstore/swift5/oneOf/pom.xml @@ -0,0 +1,43 @@ + + 4.0.0 + io.swagger + Swift5PetstoreClientTests + pom + 1.0-SNAPSHOT + Swift5 Swagger Petstore Client + + + + maven-dependency-plugin + + + package + + copy-dependencies + + + ${project.build.directory} + + + + + + org.codehaus.mojo + exec-maven-plugin + 1.2.1 + + + xcodebuild-test + integration-test + + exec + + + ./run_spmbuild.sh + + + + + + + diff --git a/samples/client/petstore/swift5/oneOf/project.yml b/samples/client/petstore/swift5/oneOf/project.yml new file mode 100644 index 00000000000..1949ec8ed3b --- /dev/null +++ b/samples/client/petstore/swift5/oneOf/project.yml @@ -0,0 +1,15 @@ +name: PetstoreClient +targets: + PetstoreClient: + type: framework + platform: iOS + deploymentTarget: "9.0" + sources: [PetstoreClient] + info: + path: ./Info.plist + version: 0.0.1 + settings: + APPLICATION_EXTENSION_API_ONLY: true + scheme: {} + dependencies: + - carthage: AnyCodable diff --git a/samples/client/petstore/swift5/oneOf/run_spmbuild.sh b/samples/client/petstore/swift5/oneOf/run_spmbuild.sh new file mode 100755 index 00000000000..1a9f585ad05 --- /dev/null +++ b/samples/client/petstore/swift5/oneOf/run_spmbuild.sh @@ -0,0 +1,3 @@ +#!/bin/sh + +swift build && exit ${PIPESTATUS[0]} diff --git a/samples/client/petstore/swift5/promisekitLibrary/.gitignore b/samples/client/petstore/swift5/promisekitLibrary/.gitignore index 5e5d5cebcf4..627d360a903 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/.gitignore +++ b/samples/client/petstore/swift5/promisekitLibrary/.gitignore @@ -1,12 +1,22 @@ +# Created by https://www.toptal.com/developers/gitignore/api/swift,xcode +# Edit at https://www.toptal.com/developers/gitignore?templates=swift,xcode + +### Swift ### # Xcode # # gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore -## Build generated -build/ -DerivedData +## User settings +xcuserdata/ -## Various settings +## compatibility with Xcode 8 and earlier (ignoring not required starting Xcode 9) +*.xcscmblueprint +*.xccheckout + +## compatibility with Xcode 3 and earlier (ignoring not required starting Xcode 4) +build/ +DerivedData/ +*.moved-aside *.pbxuser !default.pbxuser *.mode1v3 @@ -15,49 +25,81 @@ DerivedData !default.mode2v3 *.perspectivev3 !default.perspectivev3 -xcuserdata - -## Other -*.xccheckout -*.moved-aside -*.xcuserstate -*.xcscmblueprint ## Obj-C/Swift specific *.hmap + +## App packaging *.ipa +*.dSYM.zip +*.dSYM ## Playgrounds timeline.xctimeline playground.xcworkspace # Swift Package Manager -# # Add this line if you want to avoid checking in source code from Swift Package Manager dependencies. # Packages/ +# Package.pins +# Package.resolved +# *.xcodeproj +# Xcode automatically generates this directory with a .xcworkspacedata file and xcuserdata +# hence it is not needed unless you have added a package configuration file to your project +# .swiftpm + .build/ # CocoaPods -# # We recommend against adding the Pods directory to your .gitignore. However # you should judge for yourself, the pros and cons are mentioned at: # https://guides.cocoapods.org/using/using-cocoapods.html#should-i-check-the-pods-directory-into-source-control -# # Pods/ +# Add this line if you want to avoid checking in source code from the Xcode workspace +# *.xcworkspace # Carthage -# # Add this line if you want to avoid checking in source code from Carthage dependencies. # Carthage/Checkouts -Carthage/Build +Carthage/Build/ + +# Add this lines if you are using Accio dependency management (Deprecated since Xcode 12) +# Dependencies/ +# .accio/ # fastlane -# -# It is recommended to not store the screenshots in the git repo. Instead, use fastlane to re-generate the -# screenshots whenever they are needed. +# It is recommended to not store the screenshots in the git repo. +# Instead, use fastlane to re-generate the screenshots whenever they are needed. # For more information about the recommended setup visit: -# https://github.com/fastlane/fastlane/blob/master/docs/Gitignore.md +# https://docs.fastlane.tools/best-practices/source-control/#source-control fastlane/report.xml -fastlane/screenshots +fastlane/Preview.html +fastlane/screenshots/**/*.png +fastlane/test_output + +# Code Injection +# After new code Injection tools there's a generated folder /iOSInjectionProject +# https://github.com/johnno1962/injectionforxcode + +iOSInjectionProject/ + +### Xcode ### +# Xcode +# gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore + + + + +## Gcc Patch +/*.gcno + +### Xcode Patch ### +*.xcodeproj/* +!*.xcodeproj/project.pbxproj +!*.xcodeproj/xcshareddata/ +!*.xcworkspace/contents.xcworkspacedata +**/xcshareddata/WorkspaceSettings.xcsettings + +# End of https://www.toptal.com/developers/gitignore/api/swift,xcode diff --git a/samples/client/petstore/swift5/promisekitLibrary/.openapi-generator/VERSION b/samples/client/petstore/swift5/promisekitLibrary/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/.openapi-generator/VERSION +++ b/samples/client/petstore/swift5/promisekitLibrary/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/client/petstore/swift5/promisekitLibrary/Cartfile b/samples/client/petstore/swift5/promisekitLibrary/Cartfile index 84476a72b7c..19c497555a1 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/Cartfile +++ b/samples/client/petstore/swift5/promisekitLibrary/Cartfile @@ -1,3 +1,3 @@ -github "mxcl/PromiseKit" ~> 6.13.1 -github "Flight-School/AnyCodable" ~> 0.4.0 +github "mxcl/PromiseKit" ~> 6.15.3 +github "Flight-School/AnyCodable" ~> 0.6.1 diff --git a/samples/client/petstore/swift5/promisekitLibrary/Package.resolved b/samples/client/petstore/swift5/promisekitLibrary/Package.resolved index b74611fc3d6..a5cb30382b9 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/Package.resolved +++ b/samples/client/petstore/swift5/promisekitLibrary/Package.resolved @@ -2,12 +2,21 @@ "object": { "pins": [ { - "package": "PromiseKit", - "repositoryURL": "https://github.com/mxcl/PromiseKit.git", + "package": "AnyCodable", + "repositoryURL": "https://github.com/Flight-School/AnyCodable", "state": { "branch": null, - "revision": "80963d4317bcdc03891e0fbaa744f20511d1bc08", - "version": "6.12.0" + "revision": "69261f239f0fffaf51495dadc4f8483fbfe97025", + "version": "0.6.1" + } + }, + { + "package": "PromiseKit", + "repositoryURL": "https://github.com/mxcl/PromiseKit", + "state": { + "branch": null, + "revision": "d2f7ba14bcdc45e18f4f60ad9df883fb9055f081", + "version": "6.15.3" } } ] diff --git a/samples/client/petstore/swift5/promisekitLibrary/Package.swift b/samples/client/petstore/swift5/promisekitLibrary/Package.swift index d88580abc72..1f18577a228 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/Package.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/Package.swift @@ -19,8 +19,8 @@ let package = Package( ], dependencies: [ // Dependencies declare other packages that this package depends on. - .package(url: "https://github.com/Flight-School/AnyCodable", .exact("0.4.0")), - .package(url: "https://github.com/mxcl/PromiseKit.git", from: "6.12.0"), + .package(url: "https://github.com/Flight-School/AnyCodable", from: "0.6.1"), + .package(url: "https://github.com/mxcl/PromiseKit", from: "6.15.3"), ], targets: [ // Targets are the basic building blocks of a package. A target can define a module or a test suite. diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient.podspec b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient.podspec index 44b020f516e..a4bc33bd51b 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient.podspec +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient.podspec @@ -11,6 +11,6 @@ Pod::Spec.new do |s| s.homepage = 'https://github.com/openapitools/openapi-generator' s.summary = 'PetstoreClient' s.source_files = 'PetstoreClient/Classes/**/*.swift' - s.dependency 'PromiseKit/CorePromise', '~> 6.13.1' - s.dependency 'AnyCodable-FlightSchool', '~> 0.4.0' + s.dependency 'PromiseKit/CorePromise', '~> 6.15.3' + s.dependency 'AnyCodable-FlightSchool', '~> 0.6.1' end diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs.swift b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs.swift index dbdab491ff7..941c61b713a 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs.swift @@ -6,10 +6,13 @@ import Foundation -open class PetstoreClientAPI { +@available(*, deprecated, renamed: "PetstoreClient") +public typealias PetstoreClientAPI = PetstoreClient + +open class PetstoreClient { public static var basePath = "http://petstore.swagger.io:80/v2" - public static var credential: URLCredential? public static var customHeaders: [String: String] = [:] + public static var credential: URLCredential? public static var requestBuilderFactory: RequestBuilderFactory = URLSessionRequestBuilderFactory() public static var apiResponseQueue: DispatchQueue = .main } @@ -32,7 +35,7 @@ open class RequestBuilder { self.parameters = parameters self.headers = headers - addHeaders(PetstoreClientAPI.customHeaders) + addHeaders(PetstoreClient.customHeaders) } open func addHeaders(_ aHeaders: [String: String]) { @@ -41,7 +44,7 @@ open class RequestBuilder { } } - open func execute(_ apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, _ completion: @escaping (_ result: Swift.Result, Error>) -> Void) { } + open func execute(_ apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, _ completion: @escaping (_ result: Swift.Result, Error>) -> Void) { } public func addHeader(name: String, value: String) -> Self { if !value.isEmpty { @@ -51,7 +54,7 @@ open class RequestBuilder { } open func addCredential() -> Self { - credential = PetstoreClientAPI.credential + credential = PetstoreClient.credential return self } } 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 96d992e7647..b6b46f860e6 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 @@ -7,8 +7,12 @@ import Foundation import PromiseKit +#if canImport(AnyCodable) +import AnyCodable +#endif open class AnotherFakeAPI { + /** To test special tags @@ -16,7 +20,7 @@ open class AnotherFakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Promise */ - open class func call123testSpecialTags( body: Client, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Promise { + open class func call123testSpecialTags( body: Client, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> Promise { let deferred = Promise.pending() call123testSpecialTagsWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { @@ -37,21 +41,20 @@ open class AnotherFakeAPI { - returns: RequestBuilder */ open class func call123testSpecialTagsWithRequestBuilder(body: Client) -> RequestBuilder { - let path = "/another-fake/dummy" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/another-fake/dummy" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "PATCH", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "PATCH", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } - } 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 eadb85f7b62..418fbd1f1b0 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 @@ -7,15 +7,19 @@ import Foundation import PromiseKit +#if canImport(AnyCodable) +import AnyCodable +#endif open class FakeAPI { + /** - parameter body: (body) Input boolean as post body (optional) - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Promise */ - open class func fakeOuterBooleanSerialize( body: Bool? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Promise { + open class func fakeOuterBooleanSerialize( body: Bool? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> Promise { let deferred = Promise.pending() fakeOuterBooleanSerializeWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { @@ -35,21 +39,21 @@ open class FakeAPI { - returns: RequestBuilder */ open class func fakeOuterBooleanSerializeWithRequestBuilder(body: Bool? = nil) -> RequestBuilder { - let path = "/fake/outer/boolean" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/fake/outer/boolean" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -58,7 +62,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Promise */ - open class func fakeOuterCompositeSerialize( body: OuterComposite? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Promise { + open class func fakeOuterCompositeSerialize( body: OuterComposite? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> Promise { let deferred = Promise.pending() fakeOuterCompositeSerializeWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { @@ -78,21 +82,21 @@ open class FakeAPI { - returns: RequestBuilder */ open class func fakeOuterCompositeSerializeWithRequestBuilder(body: OuterComposite? = nil) -> RequestBuilder { - let path = "/fake/outer/composite" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/fake/outer/composite" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -101,7 +105,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Promise */ - open class func fakeOuterNumberSerialize( body: Double? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Promise { + open class func fakeOuterNumberSerialize( body: Double? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> Promise { let deferred = Promise.pending() fakeOuterNumberSerializeWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { @@ -121,21 +125,21 @@ open class FakeAPI { - returns: RequestBuilder */ open class func fakeOuterNumberSerializeWithRequestBuilder(body: Double? = nil) -> RequestBuilder { - let path = "/fake/outer/number" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/fake/outer/number" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -144,7 +148,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Promise */ - open class func fakeOuterStringSerialize( body: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Promise { + open class func fakeOuterStringSerialize( body: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> Promise { let deferred = Promise.pending() fakeOuterStringSerializeWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { @@ -164,21 +168,21 @@ open class FakeAPI { - returns: RequestBuilder */ open class func fakeOuterStringSerializeWithRequestBuilder(body: String? = nil) -> RequestBuilder { - let path = "/fake/outer/string" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/fake/outer/string" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -187,7 +191,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Promise */ - open class func testBodyWithFileSchema( body: FileSchemaTestClass, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Promise { + open class func testBodyWithFileSchema( body: FileSchemaTestClass, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> Promise { let deferred = Promise.pending() testBodyWithFileSchemaWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { @@ -207,21 +211,21 @@ open class FakeAPI { - returns: RequestBuilder */ open class func testBodyWithFileSchemaWithRequestBuilder(body: FileSchemaTestClass) -> RequestBuilder { - let path = "/fake/body-with-file-schema" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/fake/body-with-file-schema" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "PUT", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -231,7 +235,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Promise */ - open class func testBodyWithQueryParams( query: String, body: User, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Promise { + open class func testBodyWithQueryParams( query: String, body: User, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> Promise { let deferred = Promise.pending() testBodyWithQueryParamsWithRequestBuilder(query: query, body: body).execute(apiResponseQueue) { result -> Void in switch result { @@ -251,24 +255,24 @@ open class FakeAPI { - returns: RequestBuilder */ open class func testBodyWithQueryParamsWithRequestBuilder(query: String, body: User) -> RequestBuilder { - let path = "/fake/body-with-query-params" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/fake/body-with-query-params" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - var urlComponents = URLComponents(string: URLString) - urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ + var localVariableUrlComponents = URLComponents(string: localVariableURLString) + localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ "query": query.encodeToJSON(), ]) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "PUT", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -278,7 +282,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Promise */ - open class func testClientModel( body: Client, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Promise { + open class func testClientModel( body: Client, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> Promise { let deferred = Promise.pending() testClientModelWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { @@ -299,21 +303,21 @@ open class FakeAPI { - returns: RequestBuilder */ open class func testClientModelWithRequestBuilder(body: Client) -> RequestBuilder { - let path = "/fake" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/fake" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "PATCH", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "PATCH", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -336,7 +340,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Promise */ - open class func testEndpointParameters( number: Double, double: Double, patternWithoutDelimiter: String, byte: Data, integer: Int? = nil, int32: Int? = nil, int64: Int64? = nil, float: Float? = nil, string: String? = nil, binary: URL? = nil, date: Date? = nil, dateTime: Date? = nil, password: String? = nil, callback: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Promise { + open class func testEndpointParameters( number: Double, double: Double, patternWithoutDelimiter: String, byte: Data, integer: Int? = nil, int32: Int? = nil, int64: Int64? = nil, float: Float? = nil, string: String? = nil, binary: URL? = nil, date: Date? = nil, dateTime: Date? = nil, password: String? = nil, callback: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> Promise { let deferred = Promise.pending() testEndpointParametersWithRequestBuilder(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(apiResponseQueue) { result -> Void in switch result { @@ -373,9 +377,9 @@ open class FakeAPI { - returns: RequestBuilder */ open class func testEndpointParametersWithRequestBuilder(number: Double, double: Double, patternWithoutDelimiter: String, byte: Data, integer: Int? = nil, int32: Int? = nil, int64: Int64? = nil, float: Float? = nil, string: String? = nil, binary: URL? = nil, date: Date? = nil, dateTime: Date? = nil, password: String? = nil, callback: String? = nil) -> RequestBuilder { - let path = "/fake" - let URLString = PetstoreClientAPI.basePath + path - let formParams: [String: Any?] = [ + let localVariablePath = "/fake" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableFormParams: [String: Any?] = [ "integer": integer?.encodeToJSON(), "int32": int32?.encodeToJSON(), "int64": int64?.encodeToJSON(), @@ -392,20 +396,20 @@ open class FakeAPI { "callback": callback?.encodeToJSON(), ] - let nonNullParameters = APIHelper.rejectNil(formParams) - let parameters = APIHelper.convertBoolToString(nonNullParameters) + let localVariableNonNullParameters = APIHelper.rejectNil(localVariableFormParams) + let localVariableParameters = APIHelper.convertBoolToString(localVariableNonNullParameters) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ "Content-Type": "application/x-www-form-urlencoded", ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -489,7 +493,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Promise */ - open class func testEnumParameters( enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Promise { + open class func testEnumParameters( enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> Promise { let deferred = Promise.pending() testEnumParametersWithRequestBuilder(enumHeaderStringArray: enumHeaderStringArray, enumHeaderString: enumHeaderString, enumQueryStringArray: enumQueryStringArray, enumQueryString: enumQueryString, enumQueryInteger: enumQueryInteger, enumQueryDouble: enumQueryDouble, enumFormStringArray: enumFormStringArray, enumFormString: enumFormString).execute(apiResponseQueue) { result -> Void in switch result { @@ -517,35 +521,35 @@ open class FakeAPI { - returns: RequestBuilder */ open class func testEnumParametersWithRequestBuilder(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil) -> RequestBuilder { - let path = "/fake" - let URLString = PetstoreClientAPI.basePath + path - let formParams: [String: Any?] = [ + let localVariablePath = "/fake" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableFormParams: [String: Any?] = [ "enum_form_string_array": enumFormStringArray?.encodeToJSON(), "enum_form_string": enumFormString?.encodeToJSON(), ] - let nonNullParameters = APIHelper.rejectNil(formParams) - let parameters = APIHelper.convertBoolToString(nonNullParameters) + let localVariableNonNullParameters = APIHelper.rejectNil(localVariableFormParams) + let localVariableParameters = APIHelper.convertBoolToString(localVariableNonNullParameters) - var urlComponents = URLComponents(string: URLString) - urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ + var localVariableUrlComponents = URLComponents(string: localVariableURLString) + localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ "enum_query_string_array": enumQueryStringArray?.encodeToJSON(), "enum_query_string": enumQueryString?.encodeToJSON(), "enum_query_integer": enumQueryInteger?.encodeToJSON(), "enum_query_double": enumQueryDouble?.encodeToJSON(), ]) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ "Content-Type": "application/x-www-form-urlencoded", "enum_header_string_array": enumHeaderStringArray?.encodeToJSON(), "enum_header_string": enumHeaderString?.encodeToJSON(), ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -560,7 +564,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Promise */ - open class func testGroupParameters( requiredStringGroup: Int, requiredBooleanGroup: Bool, requiredInt64Group: Int64, stringGroup: Int? = nil, booleanGroup: Bool? = nil, int64Group: Int64? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Promise { + open class func testGroupParameters( requiredStringGroup: Int, requiredBooleanGroup: Bool, requiredInt64Group: Int64, stringGroup: Int? = nil, booleanGroup: Bool? = nil, int64Group: Int64? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> Promise { let deferred = Promise.pending() testGroupParametersWithRequestBuilder(requiredStringGroup: requiredStringGroup, requiredBooleanGroup: requiredBooleanGroup, requiredInt64Group: requiredInt64Group, stringGroup: stringGroup, booleanGroup: booleanGroup, int64Group: int64Group).execute(apiResponseQueue) { result -> Void in switch result { @@ -586,28 +590,28 @@ open class FakeAPI { - returns: RequestBuilder */ open class func testGroupParametersWithRequestBuilder(requiredStringGroup: Int, requiredBooleanGroup: Bool, requiredInt64Group: Int64, stringGroup: Int? = nil, booleanGroup: Bool? = nil, int64Group: Int64? = nil) -> RequestBuilder { - let path = "/fake" - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + let localVariablePath = "/fake" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - var urlComponents = URLComponents(string: URLString) - urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ + var localVariableUrlComponents = URLComponents(string: localVariableURLString) + localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ "required_string_group": requiredStringGroup.encodeToJSON(), "required_int64_group": requiredInt64Group.encodeToJSON(), "string_group": stringGroup?.encodeToJSON(), "int64_group": int64Group?.encodeToJSON(), ]) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ "required_boolean_group": requiredBooleanGroup.encodeToJSON(), "boolean_group": booleanGroup?.encodeToJSON(), ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "DELETE", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -617,7 +621,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Promise */ - open class func testInlineAdditionalProperties( param: [String: String], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Promise { + open class func testInlineAdditionalProperties( param: [String: String], apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> Promise { let deferred = Promise.pending() testInlineAdditionalPropertiesWithRequestBuilder(param: param).execute(apiResponseQueue) { result -> Void in switch result { @@ -637,21 +641,21 @@ open class FakeAPI { - returns: RequestBuilder */ open class func testInlineAdditionalPropertiesWithRequestBuilder(param: [String: String]) -> RequestBuilder { - let path = "/fake/inline-additionalProperties" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: param) + let localVariablePath = "/fake/inline-additionalProperties" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: param) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -662,7 +666,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Promise */ - open class func testJsonFormData( param: String, param2: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Promise { + open class func testJsonFormData( param: String, param2: String, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> Promise { let deferred = Promise.pending() testJsonFormDataWithRequestBuilder(param: param, param2: param2).execute(apiResponseQueue) { result -> Void in switch result { @@ -683,27 +687,26 @@ open class FakeAPI { - returns: RequestBuilder */ open class func testJsonFormDataWithRequestBuilder(param: String, param2: String) -> RequestBuilder { - let path = "/fake/jsonFormData" - let URLString = PetstoreClientAPI.basePath + path - let formParams: [String: Any?] = [ + let localVariablePath = "/fake/jsonFormData" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableFormParams: [String: Any?] = [ "param": param.encodeToJSON(), "param2": param2.encodeToJSON(), ] - let nonNullParameters = APIHelper.rejectNil(formParams) - let parameters = APIHelper.convertBoolToString(nonNullParameters) + let localVariableNonNullParameters = APIHelper.rejectNil(localVariableFormParams) + let localVariableParameters = APIHelper.convertBoolToString(localVariableNonNullParameters) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ "Content-Type": "application/x-www-form-urlencoded", ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } - } 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 14e41e22c1d..379ab863940 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 @@ -7,8 +7,12 @@ import Foundation import PromiseKit +#if canImport(AnyCodable) +import AnyCodable +#endif open class FakeClassnameTags123API { + /** To test class name in snake case @@ -16,7 +20,7 @@ open class FakeClassnameTags123API { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Promise */ - open class func testClassname( body: Client, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Promise { + open class func testClassname( body: Client, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> Promise { let deferred = Promise.pending() testClassnameWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { @@ -40,21 +44,20 @@ open class FakeClassnameTags123API { - returns: RequestBuilder */ open class func testClassnameWithRequestBuilder(body: Client) -> RequestBuilder { - let path = "/fake_classname_test" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/fake_classname_test" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "PATCH", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "PATCH", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } - } 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 4160df0cc9e..683baa07b70 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 @@ -7,8 +7,12 @@ import Foundation import PromiseKit +#if canImport(AnyCodable) +import AnyCodable +#endif open class PetAPI { + /** Add a new pet to the store @@ -16,7 +20,7 @@ open class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Promise */ - open class func addPet( body: Pet, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Promise { + open class func addPet( body: Pet, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> Promise { let deferred = Promise.pending() addPetWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { @@ -39,21 +43,21 @@ open class PetAPI { - returns: RequestBuilder */ open class func addPetWithRequestBuilder(body: Pet) -> RequestBuilder { - let path = "/pet" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/pet" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -64,7 +68,7 @@ open class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Promise */ - open class func deletePet( petId: Int64, apiKey: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Promise { + open class func deletePet( petId: Int64, apiKey: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> Promise { let deferred = Promise.pending() deletePetWithRequestBuilder(petId: petId, apiKey: apiKey).execute(apiResponseQueue) { result -> Void in switch result { @@ -88,24 +92,24 @@ open class PetAPI { - returns: RequestBuilder */ open class func deletePetWithRequestBuilder(petId: Int64, apiKey: String? = nil) -> RequestBuilder { - var path = "/pet/{petId}" + var localVariablePath = "/pet/{petId}" let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))" let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" - path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + localVariablePath = localVariablePath.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ "api_key": apiKey?.encodeToJSON(), ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "DELETE", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -124,7 +128,7 @@ open class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Promise<[Pet]> */ - open class func findPetsByStatus( status: [String], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Promise<[Pet]> { + open class func findPetsByStatus( status: [String], apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> Promise<[Pet]> { let deferred = Promise<[Pet]>.pending() findPetsByStatusWithRequestBuilder(status: status).execute(apiResponseQueue) { result -> Void in switch result { @@ -148,24 +152,24 @@ open class PetAPI { - returns: RequestBuilder<[Pet]> */ open class func findPetsByStatusWithRequestBuilder(status: [String]) -> RequestBuilder<[Pet]> { - let path = "/pet/findByStatus" - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + let localVariablePath = "/pet/findByStatus" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - var urlComponents = URLComponents(string: URLString) - urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ + var localVariableUrlComponents = URLComponents(string: localVariableURLString) + localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ "status": status.encodeToJSON(), ]) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -176,7 +180,7 @@ open class PetAPI { - returns: Promise<[Pet]> */ @available(*, deprecated, message: "This operation is deprecated.") - open class func findPetsByTags( tags: [String], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Promise<[Pet]> { + open class func findPetsByTags( tags: [String], apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> Promise<[Pet]> { let deferred = Promise<[Pet]>.pending() findPetsByTagsWithRequestBuilder(tags: tags).execute(apiResponseQueue) { result -> Void in switch result { @@ -201,24 +205,24 @@ open class PetAPI { */ @available(*, deprecated, message: "This operation is deprecated.") open class func findPetsByTagsWithRequestBuilder(tags: [String]) -> RequestBuilder<[Pet]> { - let path = "/pet/findByTags" - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + let localVariablePath = "/pet/findByTags" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - var urlComponents = URLComponents(string: URLString) - urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ + var localVariableUrlComponents = URLComponents(string: localVariableURLString) + localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ "tags": tags.encodeToJSON(), ]) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -228,7 +232,7 @@ open class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Promise */ - open class func getPetById( petId: Int64, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Promise { + open class func getPetById( petId: Int64, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> Promise { let deferred = Promise.pending() getPetByIdWithRequestBuilder(petId: petId).execute(apiResponseQueue) { result -> Void in switch result { @@ -252,24 +256,24 @@ open class PetAPI { - returns: RequestBuilder */ open class func getPetByIdWithRequestBuilder(petId: Int64) -> RequestBuilder { - var path = "/pet/{petId}" + var localVariablePath = "/pet/{petId}" let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))" let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" - path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + localVariablePath = localVariablePath.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -279,7 +283,7 @@ open class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Promise */ - open class func updatePet( body: Pet, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Promise { + open class func updatePet( body: Pet, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> Promise { let deferred = Promise.pending() updatePetWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { @@ -302,21 +306,21 @@ open class PetAPI { - returns: RequestBuilder */ open class func updatePetWithRequestBuilder(body: Pet) -> RequestBuilder { - let path = "/pet" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/pet" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "PUT", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -328,7 +332,7 @@ open class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Promise */ - open class func updatePetWithForm( petId: Int64, name: String? = nil, status: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Promise { + open class func updatePetWithForm( petId: Int64, name: String? = nil, status: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> Promise { let deferred = Promise.pending() updatePetWithFormWithRequestBuilder(petId: petId, name: name, status: status).execute(apiResponseQueue) { result -> Void in switch result { @@ -353,30 +357,30 @@ open class PetAPI { - returns: RequestBuilder */ open class func updatePetWithFormWithRequestBuilder(petId: Int64, name: String? = nil, status: String? = nil) -> RequestBuilder { - var path = "/pet/{petId}" + var localVariablePath = "/pet/{petId}" let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))" let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" - path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path - let formParams: [String: Any?] = [ + localVariablePath = localVariablePath.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableFormParams: [String: Any?] = [ "name": name?.encodeToJSON(), "status": status?.encodeToJSON(), ] - let nonNullParameters = APIHelper.rejectNil(formParams) - let parameters = APIHelper.convertBoolToString(nonNullParameters) + let localVariableNonNullParameters = APIHelper.rejectNil(localVariableFormParams) + let localVariableParameters = APIHelper.convertBoolToString(localVariableNonNullParameters) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ "Content-Type": "application/x-www-form-urlencoded", ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -388,7 +392,7 @@ open class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Promise */ - open class func uploadFile( petId: Int64, additionalMetadata: String? = nil, file: URL? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Promise { + open class func uploadFile( petId: Int64, additionalMetadata: String? = nil, file: URL? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> Promise { let deferred = Promise.pending() uploadFileWithRequestBuilder(petId: petId, additionalMetadata: additionalMetadata, file: file).execute(apiResponseQueue) { result -> Void in switch result { @@ -413,30 +417,30 @@ open class PetAPI { - returns: RequestBuilder */ open class func uploadFileWithRequestBuilder(petId: Int64, additionalMetadata: String? = nil, file: URL? = nil) -> RequestBuilder { - var path = "/pet/{petId}/uploadImage" + var localVariablePath = "/pet/{petId}/uploadImage" let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))" let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" - path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path - let formParams: [String: Any?] = [ + localVariablePath = localVariablePath.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableFormParams: [String: Any?] = [ "additionalMetadata": additionalMetadata?.encodeToJSON(), "file": file?.encodeToJSON(), ] - let nonNullParameters = APIHelper.rejectNil(formParams) - let parameters = APIHelper.convertBoolToString(nonNullParameters) + let localVariableNonNullParameters = APIHelper.rejectNil(localVariableFormParams) + let localVariableParameters = APIHelper.convertBoolToString(localVariableNonNullParameters) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ "Content-Type": "multipart/form-data", ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -448,7 +452,7 @@ open class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Promise */ - open class func uploadFileWithRequiredFile( petId: Int64, requiredFile: URL, additionalMetadata: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Promise { + open class func uploadFileWithRequiredFile( petId: Int64, requiredFile: URL, additionalMetadata: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> Promise { let deferred = Promise.pending() uploadFileWithRequiredFileWithRequestBuilder(petId: petId, requiredFile: requiredFile, additionalMetadata: additionalMetadata).execute(apiResponseQueue) { result -> Void in switch result { @@ -473,30 +477,29 @@ open class PetAPI { - returns: RequestBuilder */ open class func uploadFileWithRequiredFileWithRequestBuilder(petId: Int64, requiredFile: URL, additionalMetadata: String? = nil) -> RequestBuilder { - var path = "/fake/{petId}/uploadImageWithRequiredFile" + var localVariablePath = "/fake/{petId}/uploadImageWithRequiredFile" let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))" let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" - path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path - let formParams: [String: Any?] = [ + localVariablePath = localVariablePath.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableFormParams: [String: Any?] = [ "additionalMetadata": additionalMetadata?.encodeToJSON(), "requiredFile": requiredFile.encodeToJSON(), ] - let nonNullParameters = APIHelper.rejectNil(formParams) - let parameters = APIHelper.convertBoolToString(nonNullParameters) + let localVariableNonNullParameters = APIHelper.rejectNil(localVariableFormParams) + let localVariableParameters = APIHelper.convertBoolToString(localVariableNonNullParameters) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ "Content-Type": "multipart/form-data", ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } - } diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift index 88305f77980..fcc555ed5fb 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift @@ -7,8 +7,12 @@ import Foundation import PromiseKit +#if canImport(AnyCodable) +import AnyCodable +#endif open class StoreAPI { + /** Delete purchase order by ID @@ -16,7 +20,7 @@ open class StoreAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Promise */ - open class func deleteOrder( orderId: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Promise { + open class func deleteOrder( orderId: String, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> Promise { let deferred = Promise.pending() deleteOrderWithRequestBuilder(orderId: orderId).execute(apiResponseQueue) { result -> Void in switch result { @@ -37,24 +41,24 @@ open class StoreAPI { - returns: RequestBuilder */ open class func deleteOrderWithRequestBuilder(orderId: String) -> RequestBuilder { - var path = "/store/order/{order_id}" + var localVariablePath = "/store/order/{order_id}" let orderIdPreEscape = "\(APIHelper.mapValueToPathItem(orderId))" let orderIdPostEscape = orderIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" - path = path.replacingOccurrences(of: "{order_id}", with: orderIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + localVariablePath = localVariablePath.replacingOccurrences(of: "{order_id}", with: orderIdPostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "DELETE", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -63,7 +67,7 @@ open class StoreAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Promise<[String: Int]> */ - open class func getInventory(apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Promise<[String: Int]> { + open class func getInventory(apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> Promise<[String: Int]> { let deferred = Promise<[String: Int]>.pending() getInventoryWithRequestBuilder().execute(apiResponseQueue) { result -> Void in switch result { @@ -86,21 +90,21 @@ open class StoreAPI { - returns: RequestBuilder<[String: Int]> */ open class func getInventoryWithRequestBuilder() -> RequestBuilder<[String: Int]> { - let path = "/store/inventory" - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + let localVariablePath = "/store/inventory" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder<[String: Int]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder<[String: Int]>.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -110,7 +114,7 @@ open class StoreAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Promise */ - open class func getOrderById( orderId: Int64, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Promise { + open class func getOrderById( orderId: Int64, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> Promise { let deferred = Promise.pending() getOrderByIdWithRequestBuilder(orderId: orderId).execute(apiResponseQueue) { result -> Void in switch result { @@ -131,24 +135,24 @@ open class StoreAPI { - returns: RequestBuilder */ open class func getOrderByIdWithRequestBuilder(orderId: Int64) -> RequestBuilder { - var path = "/store/order/{order_id}" + var localVariablePath = "/store/order/{order_id}" let orderIdPreEscape = "\(APIHelper.mapValueToPathItem(orderId))" let orderIdPostEscape = orderIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" - path = path.replacingOccurrences(of: "{order_id}", with: orderIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + localVariablePath = localVariablePath.replacingOccurrences(of: "{order_id}", with: orderIdPostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -158,7 +162,7 @@ open class StoreAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Promise */ - open class func placeOrder( body: Order, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Promise { + open class func placeOrder( body: Order, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> Promise { let deferred = Promise.pending() placeOrderWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { @@ -178,21 +182,20 @@ open class StoreAPI { - returns: RequestBuilder */ open class func placeOrderWithRequestBuilder(body: Order) -> RequestBuilder { - let path = "/store/order" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/store/order" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } - } diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift index 1bdb1159573..535525375b2 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift @@ -7,8 +7,12 @@ import Foundation import PromiseKit +#if canImport(AnyCodable) +import AnyCodable +#endif open class UserAPI { + /** Create user @@ -16,7 +20,7 @@ open class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Promise */ - open class func createUser( body: User, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Promise { + open class func createUser( body: User, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> Promise { let deferred = Promise.pending() createUserWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { @@ -37,21 +41,21 @@ open class UserAPI { - returns: RequestBuilder */ open class func createUserWithRequestBuilder(body: User) -> RequestBuilder { - let path = "/user" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/user" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -61,7 +65,7 @@ open class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Promise */ - open class func createUsersWithArrayInput( body: [User], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Promise { + open class func createUsersWithArrayInput( body: [User], apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> Promise { let deferred = Promise.pending() createUsersWithArrayInputWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { @@ -81,21 +85,21 @@ open class UserAPI { - returns: RequestBuilder */ open class func createUsersWithArrayInputWithRequestBuilder(body: [User]) -> RequestBuilder { - let path = "/user/createWithArray" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/user/createWithArray" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -105,7 +109,7 @@ open class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Promise */ - open class func createUsersWithListInput( body: [User], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Promise { + open class func createUsersWithListInput( body: [User], apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> Promise { let deferred = Promise.pending() createUsersWithListInputWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { @@ -125,21 +129,21 @@ open class UserAPI { - returns: RequestBuilder */ open class func createUsersWithListInputWithRequestBuilder(body: [User]) -> RequestBuilder { - let path = "/user/createWithList" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/user/createWithList" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -149,7 +153,7 @@ open class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Promise */ - open class func deleteUser( username: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Promise { + open class func deleteUser( username: String, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> Promise { let deferred = Promise.pending() deleteUserWithRequestBuilder(username: username).execute(apiResponseQueue) { result -> Void in switch result { @@ -170,24 +174,24 @@ open class UserAPI { - returns: RequestBuilder */ open class func deleteUserWithRequestBuilder(username: String) -> RequestBuilder { - var path = "/user/{username}" + var localVariablePath = "/user/{username}" let usernamePreEscape = "\(APIHelper.mapValueToPathItem(username))" let usernamePostEscape = usernamePreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" - path = path.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + localVariablePath = localVariablePath.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "DELETE", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -197,7 +201,7 @@ open class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Promise */ - open class func getUserByName( username: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Promise { + open class func getUserByName( username: String, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> Promise { let deferred = Promise.pending() getUserByNameWithRequestBuilder(username: username).execute(apiResponseQueue) { result -> Void in switch result { @@ -217,24 +221,24 @@ open class UserAPI { - returns: RequestBuilder */ open class func getUserByNameWithRequestBuilder(username: String) -> RequestBuilder { - var path = "/user/{username}" + var localVariablePath = "/user/{username}" let usernamePreEscape = "\(APIHelper.mapValueToPathItem(username))" let usernamePostEscape = usernamePreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" - path = path.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + localVariablePath = localVariablePath.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -245,7 +249,7 @@ open class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Promise */ - open class func loginUser( username: String, password: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Promise { + open class func loginUser( username: String, password: String, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> Promise { let deferred = Promise.pending() loginUserWithRequestBuilder(username: username, password: password).execute(apiResponseQueue) { result -> Void in switch result { @@ -267,25 +271,25 @@ open class UserAPI { - returns: RequestBuilder */ open class func loginUserWithRequestBuilder(username: String, password: String) -> RequestBuilder { - let path = "/user/login" - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + let localVariablePath = "/user/login" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - var urlComponents = URLComponents(string: URLString) - urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ + var localVariableUrlComponents = URLComponents(string: localVariableURLString) + localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ "username": username.encodeToJSON(), "password": password.encodeToJSON(), ]) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -294,7 +298,7 @@ open class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Promise */ - open class func logoutUser(apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Promise { + open class func logoutUser(apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> Promise { let deferred = Promise.pending() logoutUserWithRequestBuilder().execute(apiResponseQueue) { result -> Void in switch result { @@ -313,21 +317,21 @@ open class UserAPI { - returns: RequestBuilder */ open class func logoutUserWithRequestBuilder() -> RequestBuilder { - let path = "/user/logout" - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + let localVariablePath = "/user/logout" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -338,7 +342,7 @@ open class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Promise */ - open class func updateUser( username: String, body: User, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Promise { + open class func updateUser( username: String, body: User, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> Promise { let deferred = Promise.pending() updateUserWithRequestBuilder(username: username, body: body).execute(apiResponseQueue) { result -> Void in switch result { @@ -360,24 +364,23 @@ open class UserAPI { - returns: RequestBuilder */ open class func updateUserWithRequestBuilder(username: String, body: User) -> RequestBuilder { - var path = "/user/{username}" + var localVariablePath = "/user/{username}" let usernamePreEscape = "\(APIHelper.mapValueToPathItem(username))" let usernamePostEscape = usernamePreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" - path = path.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + localVariablePath = localVariablePath.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "PUT", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } - } diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Configuration.swift b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Configuration.swift index 18edabbed78..8fb05331889 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Configuration.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Configuration.swift @@ -7,6 +7,7 @@ import Foundation open class Configuration { + // This value is used to configure the date formatter that is used to serialize dates into JSON format. // You must set it prior to encoding any dates, and it will only be read once. @available(*, unavailable, message: "To set a different date format, use CodableHelper.dateFormatter instead.") diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Extensions.swift b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Extensions.swift index 78d15ab2990..68c3c6ee7e4 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Extensions.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Extensions.swift @@ -5,7 +5,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif import PromiseKit extension Bool: JSONEncodable { @@ -200,44 +202,3 @@ extension RequestBuilder { return deferred.promise } } - -extension AnyCodable: Hashable { - public func hash(into hasher: inout Hasher) { - switch value { - case let value as Bool: - hasher.combine(value) - case let value as Int: - hasher.combine(value) - case let value as Int8: - hasher.combine(value) - case let value as Int16: - hasher.combine(value) - case let value as Int32: - hasher.combine(value) - case let value as Int64: - hasher.combine(value) - case let value as UInt: - hasher.combine(value) - case let value as UInt8: - hasher.combine(value) - case let value as UInt16: - hasher.combine(value) - case let value as UInt32: - hasher.combine(value) - case let value as UInt64: - hasher.combine(value) - case let value as Float: - hasher.combine(value) - case let value as Double: - hasher.combine(value) - case let value as String: - hasher.combine(value) - case let value as [String: AnyCodable]: - hasher.combine(value) - case let value as [AnyCodable]: - hasher.combine(value) - default: - hasher.combine(0) - } - } -} \ No newline at end of file diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesClass.swift b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesClass.swift index 75ab9bc8d0a..621afb93561 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesClass.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesClass.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct AdditionalPropertiesClass: Codable, Hashable { @@ -17,6 +19,7 @@ public struct AdditionalPropertiesClass: Codable, Hashable { self.mapString = mapString self.mapMapString = mapMapString } + public enum CodingKeys: String, CodingKey, CaseIterable { case mapString = "map_string" case mapMapString = "map_map_string" @@ -29,7 +32,5 @@ public struct AdditionalPropertiesClass: Codable, Hashable { try container.encodeIfPresent(mapString, forKey: .mapString) try container.encodeIfPresent(mapMapString, forKey: .mapMapString) } - - - } + diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Animal.swift b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Animal.swift index 0f825cf24d0..cdd4f5335b9 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Animal.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Animal.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct Animal: Codable, Hashable { @@ -17,6 +19,7 @@ public struct Animal: Codable, Hashable { self.className = className self.color = color } + public enum CodingKeys: String, CodingKey, CaseIterable { case className case color @@ -29,7 +32,5 @@ public struct Animal: Codable, Hashable { try container.encode(className, forKey: .className) try container.encodeIfPresent(color, forKey: .color) } - - - } + diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/AnimalFarm.swift b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/AnimalFarm.swift index b20b894a1ad..a0b09cb9761 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/AnimalFarm.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/AnimalFarm.swift @@ -6,6 +6,8 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public typealias AnimalFarm = [Animal] diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift index 2b66af2dc94..c365505ab9d 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct ApiResponse: Codable, Hashable { @@ -19,6 +21,7 @@ public struct ApiResponse: Codable, Hashable { self.type = type self.message = message } + public enum CodingKeys: String, CodingKey, CaseIterable { case code case type @@ -33,7 +36,5 @@ public struct ApiResponse: Codable, Hashable { try container.encodeIfPresent(type, forKey: .type) try container.encodeIfPresent(message, forKey: .message) } - - - } + diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfArrayOfNumberOnly.swift b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfArrayOfNumberOnly.swift index 06f0640475c..226f7456181 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfArrayOfNumberOnly.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfArrayOfNumberOnly.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct ArrayOfArrayOfNumberOnly: Codable, Hashable { @@ -15,6 +17,7 @@ public struct ArrayOfArrayOfNumberOnly: Codable, Hashable { public init(arrayArrayNumber: [[Double]]? = nil) { self.arrayArrayNumber = arrayArrayNumber } + public enum CodingKeys: String, CodingKey, CaseIterable { case arrayArrayNumber = "ArrayArrayNumber" } @@ -25,7 +28,5 @@ public struct ArrayOfArrayOfNumberOnly: Codable, Hashable { var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(arrayArrayNumber, forKey: .arrayArrayNumber) } - - - } + diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfNumberOnly.swift b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfNumberOnly.swift index 8c50c7fa1e4..39831127871 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfNumberOnly.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfNumberOnly.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct ArrayOfNumberOnly: Codable, Hashable { @@ -15,6 +17,7 @@ public struct ArrayOfNumberOnly: Codable, Hashable { public init(arrayNumber: [Double]? = nil) { self.arrayNumber = arrayNumber } + public enum CodingKeys: String, CodingKey, CaseIterable { case arrayNumber = "ArrayNumber" } @@ -25,7 +28,5 @@ public struct ArrayOfNumberOnly: Codable, Hashable { var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(arrayNumber, forKey: .arrayNumber) } - - - } + diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayTest.swift b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayTest.swift index 461ec7cd9ac..8865d76bef2 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayTest.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayTest.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct ArrayTest: Codable, Hashable { @@ -19,6 +21,7 @@ public struct ArrayTest: Codable, Hashable { self.arrayArrayOfInteger = arrayArrayOfInteger self.arrayArrayOfModel = arrayArrayOfModel } + public enum CodingKeys: String, CodingKey, CaseIterable { case arrayOfString = "array_of_string" case arrayArrayOfInteger = "array_array_of_integer" @@ -33,7 +36,5 @@ public struct ArrayTest: Codable, Hashable { try container.encodeIfPresent(arrayArrayOfInteger, forKey: .arrayArrayOfInteger) try container.encodeIfPresent(arrayArrayOfModel, forKey: .arrayArrayOfModel) } - - - } + diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Capitalization.swift b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Capitalization.swift index fbe62983d5e..71cd93bce5f 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Capitalization.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Capitalization.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct Capitalization: Codable, Hashable { @@ -26,6 +28,7 @@ public struct Capitalization: Codable, Hashable { self.sCAETHFlowPoints = sCAETHFlowPoints self.ATT_NAME = ATT_NAME } + public enum CodingKeys: String, CodingKey, CaseIterable { case smallCamel case capitalCamel = "CapitalCamel" @@ -46,7 +49,5 @@ public struct Capitalization: Codable, Hashable { try container.encodeIfPresent(sCAETHFlowPoints, forKey: .sCAETHFlowPoints) try container.encodeIfPresent(ATT_NAME, forKey: .ATT_NAME) } - - - } + diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Cat.swift b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Cat.swift index 7f3a86932f1..457e04bd475 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Cat.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Cat.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct Cat: Codable, Hashable { @@ -19,6 +21,7 @@ public struct Cat: Codable, Hashable { self.color = color self.declawed = declawed } + public enum CodingKeys: String, CodingKey, CaseIterable { case className case color @@ -33,7 +36,5 @@ public struct Cat: Codable, Hashable { try container.encodeIfPresent(color, forKey: .color) try container.encodeIfPresent(declawed, forKey: .declawed) } - - - } + diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/CatAllOf.swift b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/CatAllOf.swift index 8df23954832..8caebb1c206 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/CatAllOf.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/CatAllOf.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct CatAllOf: Codable, Hashable { @@ -15,6 +17,7 @@ public struct CatAllOf: Codable, Hashable { public init(declawed: Bool? = nil) { self.declawed = declawed } + public enum CodingKeys: String, CodingKey, CaseIterable { case declawed } @@ -25,7 +28,5 @@ public struct CatAllOf: Codable, Hashable { var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(declawed, forKey: .declawed) } - - - } + diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Category.swift b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Category.swift index 4109db4d1ef..89016ca353d 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Category.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Category.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct Category: Codable, Hashable { @@ -17,6 +19,7 @@ public struct Category: Codable, Hashable { self.id = id self.name = name } + public enum CodingKeys: String, CodingKey, CaseIterable { case id case name @@ -29,7 +32,5 @@ public struct Category: Codable, Hashable { try container.encodeIfPresent(id, forKey: .id) try container.encode(name, forKey: .name) } - - - } + diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/ClassModel.swift b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/ClassModel.swift index 7269ddbef6f..16e69e560bd 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/ClassModel.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/ClassModel.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif /** Model for testing model with \"_class\" property */ public struct ClassModel: Codable, Hashable { @@ -16,6 +18,7 @@ public struct ClassModel: Codable, Hashable { public init(_class: String? = nil) { self._class = _class } + public enum CodingKeys: String, CodingKey, CaseIterable { case _class } @@ -26,7 +29,5 @@ public struct ClassModel: Codable, Hashable { var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(_class, forKey: ._class) } - - - } + diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Client.swift b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Client.swift index 7d6eff2ffe1..60dbc5dc5c1 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Client.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Client.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct Client: Codable, Hashable { @@ -15,6 +17,7 @@ public struct Client: Codable, Hashable { public init(client: String? = nil) { self.client = client } + public enum CodingKeys: String, CodingKey, CaseIterable { case client } @@ -25,7 +28,5 @@ public struct Client: Codable, Hashable { var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(client, forKey: .client) } - - - } + diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Dog.swift b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Dog.swift index b5f2bcea38a..658732a7f36 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Dog.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Dog.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct Dog: Codable, Hashable { @@ -19,6 +21,7 @@ public struct Dog: Codable, Hashable { self.color = color self.breed = breed } + public enum CodingKeys: String, CodingKey, CaseIterable { case className case color @@ -33,7 +36,5 @@ public struct Dog: Codable, Hashable { try container.encodeIfPresent(color, forKey: .color) try container.encodeIfPresent(breed, forKey: .breed) } - - - } + diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/DogAllOf.swift b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/DogAllOf.swift index 1bfa23d7bc6..82b0dedf35b 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/DogAllOf.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/DogAllOf.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct DogAllOf: Codable, Hashable { @@ -15,6 +17,7 @@ public struct DogAllOf: Codable, Hashable { public init(breed: String? = nil) { self.breed = breed } + public enum CodingKeys: String, CodingKey, CaseIterable { case breed } @@ -25,7 +28,5 @@ public struct DogAllOf: Codable, Hashable { var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(breed, forKey: .breed) } - - - } + diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumArrays.swift b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumArrays.swift index 73368c42143..1d8ce99539c 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumArrays.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumArrays.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct EnumArrays: Codable, Hashable { @@ -25,6 +27,7 @@ public struct EnumArrays: Codable, Hashable { self.justSymbol = justSymbol self.arrayEnum = arrayEnum } + public enum CodingKeys: String, CodingKey, CaseIterable { case justSymbol = "just_symbol" case arrayEnum = "array_enum" @@ -37,7 +40,5 @@ public struct EnumArrays: Codable, Hashable { try container.encodeIfPresent(justSymbol, forKey: .justSymbol) try container.encodeIfPresent(arrayEnum, forKey: .arrayEnum) } - - - } + diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumClass.swift b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumClass.swift index ab01cf297f8..6ea2895aee5 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumClass.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumClass.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public enum EnumClass: String, Codable, CaseIterable { case abc = "_abc" diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumTest.swift b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumTest.swift index 60a81bcac77..8c8bca49774 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumTest.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumTest.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct EnumTest: Codable, Hashable { @@ -41,6 +43,7 @@ public struct EnumTest: Codable, Hashable { self.enumNumber = enumNumber self.outerEnum = outerEnum } + public enum CodingKeys: String, CodingKey, CaseIterable { case enumString = "enum_string" case enumStringRequired = "enum_string_required" @@ -59,7 +62,5 @@ public struct EnumTest: Codable, Hashable { try container.encodeIfPresent(enumNumber, forKey: .enumNumber) try container.encodeIfPresent(outerEnum, forKey: .outerEnum) } - - - } + diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/File.swift b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/File.swift index 90283656d1b..05dd5b1a825 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/File.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/File.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif /** Must be named `File` for test. */ public struct File: Codable, Hashable { @@ -17,6 +19,7 @@ public struct File: Codable, Hashable { public init(sourceURI: String? = nil) { self.sourceURI = sourceURI } + public enum CodingKeys: String, CodingKey, CaseIterable { case sourceURI } @@ -27,7 +30,5 @@ public struct File: Codable, Hashable { var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(sourceURI, forKey: .sourceURI) } - - - } + diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/FileSchemaTestClass.swift b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/FileSchemaTestClass.swift index cff92673bbe..3ca66a31359 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/FileSchemaTestClass.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/FileSchemaTestClass.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct FileSchemaTestClass: Codable, Hashable { @@ -17,6 +19,7 @@ public struct FileSchemaTestClass: Codable, Hashable { self.file = file self.files = files } + public enum CodingKeys: String, CodingKey, CaseIterable { case file case files @@ -29,7 +32,5 @@ public struct FileSchemaTestClass: Codable, Hashable { try container.encodeIfPresent(file, forKey: .file) try container.encodeIfPresent(files, forKey: .files) } - - - } + diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/FormatTest.swift b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/FormatTest.swift index fc86676eec3..a7a4b39e720 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/FormatTest.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/FormatTest.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct FormatTest: Codable, Hashable { @@ -39,6 +41,7 @@ public struct FormatTest: Codable, Hashable { self.uuid = uuid self.password = password } + public enum CodingKeys: String, CodingKey, CaseIterable { case integer case int32 @@ -73,7 +76,5 @@ public struct FormatTest: Codable, Hashable { try container.encodeIfPresent(uuid, forKey: .uuid) try container.encode(password, forKey: .password) } - - - } + diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/HasOnlyReadOnly.swift b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/HasOnlyReadOnly.swift index d7960f5c800..54ed8a723c6 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/HasOnlyReadOnly.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/HasOnlyReadOnly.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct HasOnlyReadOnly: Codable, Hashable { @@ -17,6 +19,7 @@ public struct HasOnlyReadOnly: Codable, Hashable { self.bar = bar self.foo = foo } + public enum CodingKeys: String, CodingKey, CaseIterable { case bar case foo @@ -29,7 +32,5 @@ public struct HasOnlyReadOnly: Codable, Hashable { try container.encodeIfPresent(bar, forKey: .bar) try container.encodeIfPresent(foo, forKey: .foo) } - - - } + diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/List.swift b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/List.swift index c5d4f2cae56..67e3048469f 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/List.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/List.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct List: Codable, Hashable { @@ -15,6 +17,7 @@ public struct List: Codable, Hashable { public init(_123list: String? = nil) { self._123list = _123list } + public enum CodingKeys: String, CodingKey, CaseIterable { case _123list = "123-list" } @@ -25,7 +28,5 @@ public struct List: Codable, Hashable { var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(_123list, forKey: ._123list) } - - - } + diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/MapTest.swift b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/MapTest.swift index b54bd01e5dc..1e728fcdf58 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/MapTest.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/MapTest.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct MapTest: Codable, Hashable { @@ -25,6 +27,7 @@ public struct MapTest: Codable, Hashable { self.directMap = directMap self.indirectMap = indirectMap } + public enum CodingKeys: String, CodingKey, CaseIterable { case mapMapOfString = "map_map_of_string" case mapOfEnumString = "map_of_enum_string" @@ -41,7 +44,5 @@ public struct MapTest: Codable, Hashable { try container.encodeIfPresent(directMap, forKey: .directMap) try container.encodeIfPresent(indirectMap, forKey: .indirectMap) } - - - } + diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/MixedPropertiesAndAdditionalPropertiesClass.swift b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/MixedPropertiesAndAdditionalPropertiesClass.swift index c8f639ef43d..c79ca459217 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/MixedPropertiesAndAdditionalPropertiesClass.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/MixedPropertiesAndAdditionalPropertiesClass.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct MixedPropertiesAndAdditionalPropertiesClass: Codable, Hashable { @@ -19,6 +21,7 @@ public struct MixedPropertiesAndAdditionalPropertiesClass: Codable, Hashable { self.dateTime = dateTime self.map = map } + public enum CodingKeys: String, CodingKey, CaseIterable { case uuid case dateTime @@ -33,7 +36,5 @@ public struct MixedPropertiesAndAdditionalPropertiesClass: Codable, Hashable { try container.encodeIfPresent(dateTime, forKey: .dateTime) try container.encodeIfPresent(map, forKey: .map) } - - - } + diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Model200Response.swift b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Model200Response.swift index 5368032f09b..23402143f71 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Model200Response.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Model200Response.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif /** Model for testing model name starting with number */ public struct Model200Response: Codable, Hashable { @@ -18,6 +20,7 @@ public struct Model200Response: Codable, Hashable { self.name = name self._class = _class } + public enum CodingKeys: String, CodingKey, CaseIterable { case name case _class = "class" @@ -30,7 +33,5 @@ public struct Model200Response: Codable, Hashable { try container.encodeIfPresent(name, forKey: .name) try container.encodeIfPresent(_class, forKey: ._class) } - - - } + diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Name.swift b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Name.swift index 84a40e1c101..a28f46a33ce 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Name.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Name.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif /** Model for testing model name same as property name */ public struct Name: Codable, Hashable { @@ -22,6 +24,7 @@ public struct Name: Codable, Hashable { self.property = property self._123number = _123number } + public enum CodingKeys: String, CodingKey, CaseIterable { case name case snakeCase = "snake_case" @@ -38,7 +41,5 @@ public struct Name: Codable, Hashable { try container.encodeIfPresent(property, forKey: .property) try container.encodeIfPresent(_123number, forKey: ._123number) } - - - } + diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/NumberOnly.swift b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/NumberOnly.swift index 710f41648f9..87ceb64bb97 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/NumberOnly.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/NumberOnly.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct NumberOnly: Codable, Hashable { @@ -15,6 +17,7 @@ public struct NumberOnly: Codable, Hashable { public init(justNumber: Double? = nil) { self.justNumber = justNumber } + public enum CodingKeys: String, CodingKey, CaseIterable { case justNumber = "JustNumber" } @@ -25,7 +28,5 @@ public struct NumberOnly: Codable, Hashable { var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(justNumber, forKey: .justNumber) } - - - } + diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Order.swift b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Order.swift index 15726ab16a4..e2eeced4c57 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Order.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Order.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct Order: Codable, Hashable { @@ -31,6 +33,7 @@ public struct Order: Codable, Hashable { self.status = status self.complete = complete } + public enum CodingKeys: String, CodingKey, CaseIterable { case id case petId @@ -51,7 +54,5 @@ public struct Order: Codable, Hashable { try container.encodeIfPresent(status, forKey: .status) try container.encodeIfPresent(complete, forKey: .complete) } - - - } + diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/OuterComposite.swift b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/OuterComposite.swift index 36904afbd50..edeaccaeaa6 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/OuterComposite.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/OuterComposite.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct OuterComposite: Codable, Hashable { @@ -19,6 +21,7 @@ public struct OuterComposite: Codable, Hashable { self.myString = myString self.myBoolean = myBoolean } + public enum CodingKeys: String, CodingKey, CaseIterable { case myNumber = "my_number" case myString = "my_string" @@ -33,7 +36,5 @@ public struct OuterComposite: Codable, Hashable { try container.encodeIfPresent(myString, forKey: .myString) try container.encodeIfPresent(myBoolean, forKey: .myBoolean) } - - - } + diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/OuterEnum.swift b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/OuterEnum.swift index 9bd6f3bef8f..76c34b3c2ce 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/OuterEnum.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/OuterEnum.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public enum OuterEnum: String, Codable, CaseIterable { case placed = "placed" diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Pet.swift b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Pet.swift index 7a1c2826a19..ddd1186b891 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Pet.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Pet.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct Pet: Codable, Hashable { @@ -31,6 +33,7 @@ public struct Pet: Codable, Hashable { self.tags = tags self.status = status } + public enum CodingKeys: String, CodingKey, CaseIterable { case id case category @@ -51,7 +54,5 @@ public struct Pet: Codable, Hashable { try container.encodeIfPresent(tags, forKey: .tags) try container.encodeIfPresent(status, forKey: .status) } - - - } + diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/ReadOnlyFirst.swift b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/ReadOnlyFirst.swift index 38fb57af328..57ba3f577c8 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/ReadOnlyFirst.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/ReadOnlyFirst.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct ReadOnlyFirst: Codable, Hashable { @@ -17,6 +19,7 @@ public struct ReadOnlyFirst: Codable, Hashable { self.bar = bar self.baz = baz } + public enum CodingKeys: String, CodingKey, CaseIterable { case bar case baz @@ -29,7 +32,5 @@ public struct ReadOnlyFirst: Codable, Hashable { try container.encodeIfPresent(bar, forKey: .bar) try container.encodeIfPresent(baz, forKey: .baz) } - - - } + diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Return.swift b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Return.swift index ed7e538a06d..afc2b51f8f3 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Return.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Return.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif /** Model for testing reserved words */ public struct Return: Codable, Hashable { @@ -16,6 +18,7 @@ public struct Return: Codable, Hashable { public init(_return: Int? = nil) { self._return = _return } + public enum CodingKeys: String, CodingKey, CaseIterable { case _return = "return" } @@ -26,7 +29,5 @@ public struct Return: Codable, Hashable { var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(_return, forKey: ._return) } - - - } + diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/SpecialModelName.swift b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/SpecialModelName.swift index 18747e071bc..bfe9723f888 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/SpecialModelName.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/SpecialModelName.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct SpecialModelName: Codable, Hashable { @@ -15,6 +17,7 @@ public struct SpecialModelName: Codable, Hashable { public init(specialPropertyName: Int64? = nil) { self.specialPropertyName = specialPropertyName } + public enum CodingKeys: String, CodingKey, CaseIterable { case specialPropertyName = "$special[property.name]" } @@ -25,7 +28,5 @@ public struct SpecialModelName: Codable, Hashable { var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(specialPropertyName, forKey: .specialPropertyName) } - - - } + diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/StringBooleanMap.swift b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/StringBooleanMap.swift index 0699c25ff7e..126c35c85a6 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/StringBooleanMap.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/StringBooleanMap.swift @@ -6,12 +6,16 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct StringBooleanMap: Codable, Hashable { + public enum CodingKeys: CodingKey, CaseIterable { } + public var additionalProperties: [String: Bool] = [:] public subscript(key: String) -> Bool? { @@ -38,11 +42,11 @@ public struct StringBooleanMap: Codable, Hashable { // Decodable protocol methods public init(from decoder: Decoder) throws { - let container = try decoder.container(keyedBy: String.self) + let container = try decoder.container(keyedBy: CodingKeys.self) var nonAdditionalPropertyKeys = Set() - additionalProperties = try container.decodeMap(Bool.self, excludedKeys: nonAdditionalPropertyKeys) + let additionalPropertiesContainer = try decoder.container(keyedBy: String.self) + additionalProperties = try additionalPropertiesContainer.decodeMap(Bool.self, excludedKeys: nonAdditionalPropertyKeys) } - - } + diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift index 11c5f7a750b..07b826264f3 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct Tag: Codable, Hashable { @@ -17,6 +19,7 @@ public struct Tag: Codable, Hashable { self.id = id self.name = name } + public enum CodingKeys: String, CodingKey, CaseIterable { case id case name @@ -29,7 +32,5 @@ public struct Tag: Codable, Hashable { try container.encodeIfPresent(id, forKey: .id) try container.encodeIfPresent(name, forKey: .name) } - - - } + diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderDefault.swift b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderDefault.swift index 35b1a5833b9..e58eecd960f 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderDefault.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderDefault.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct TypeHolderDefault: Codable, Hashable { @@ -23,6 +25,7 @@ public struct TypeHolderDefault: Codable, Hashable { self.boolItem = boolItem self.arrayItem = arrayItem } + public enum CodingKeys: String, CodingKey, CaseIterable { case stringItem = "string_item" case numberItem = "number_item" @@ -41,7 +44,5 @@ public struct TypeHolderDefault: Codable, Hashable { try container.encode(boolItem, forKey: .boolItem) try container.encode(arrayItem, forKey: .arrayItem) } - - - } + diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderExample.swift b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderExample.swift index 37277a4ac00..6c22fdbae7a 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderExample.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderExample.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct TypeHolderExample: Codable, Hashable { @@ -23,6 +25,7 @@ public struct TypeHolderExample: Codable, Hashable { self.boolItem = boolItem self.arrayItem = arrayItem } + public enum CodingKeys: String, CodingKey, CaseIterable { case stringItem = "string_item" case numberItem = "number_item" @@ -41,7 +44,5 @@ public struct TypeHolderExample: Codable, Hashable { try container.encode(boolItem, forKey: .boolItem) try container.encode(arrayItem, forKey: .arrayItem) } - - - } + diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/User.swift b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/User.swift index 2bbc31806ff..7afe359ae40 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/User.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models/User.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct User: Codable, Hashable { @@ -30,6 +32,7 @@ public struct User: Codable, Hashable { self.phone = phone self.userStatus = userStatus } + public enum CodingKeys: String, CodingKey, CaseIterable { case id case username @@ -54,7 +57,5 @@ public struct User: Codable, Hashable { try container.encodeIfPresent(phone, forKey: .phone) try container.encodeIfPresent(userStatus, forKey: .userStatus) } - - - } + 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 52b2071ec1a..41959190a26 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift @@ -93,14 +93,14 @@ open class URLSessionRequestBuilder: RequestBuilder { return modifiedRequest } - override open func execute(_ apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, _ completion: @escaping (_ result: Swift.Result, Error>) -> Void) { + override open func execute(_ apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, _ completion: @escaping (_ result: Swift.Result, Error>) -> Void) { let urlSessionId = UUID().uuidString // Create a new manager for each request to customize its request header let urlSession = createURLSession() urlSessionStore[urlSessionId] = urlSession guard let xMethod = HTTPMethod(rawValue: method) else { - fatalError("Unsuported Http method - \(method)") + fatalError("Unsupported Http method - \(method)") } let encoding: ParameterEncoding @@ -119,7 +119,7 @@ open class URLSessionRequestBuilder: RequestBuilder { } else if contentType == "application/x-www-form-urlencoded" { encoding = FormURLEncoding() } else { - fatalError("Unsuported Media Type - \(contentType)") + fatalError("Unsupported Media Type - \(contentType)") } } @@ -205,16 +205,18 @@ open class URLSessionRequestBuilder: RequestBuilder { } let fileManager = FileManager.default - let documentsDirectory = fileManager.urls(for: .documentDirectory, in: .userDomainMask)[0] + let cachesDirectory = fileManager.urls(for: .cachesDirectory, in: .userDomainMask)[0] let requestURL = try getURL(from: urlRequest) var requestPath = try getPath(from: requestURL) if let headerFileName = getFileName(fromContentDisposition: httpResponse.allHeaderFields["Content-Disposition"] as? String) { requestPath = requestPath.appending("/\(headerFileName)") + } else { + requestPath = requestPath.appending("/tmp.PetstoreClient.\(UUID().uuidString)") } - let filePath = documentsDirectory.appendingPathComponent(requestPath) + let filePath = cachesDirectory.appendingPathComponent(requestPath) let directoryPath = filePath.deletingLastPathComponent().path try fileManager.createDirectory(atPath: directoryPath, withIntermediateDirectories: true, attributes: nil) @@ -232,6 +234,10 @@ open class URLSessionRequestBuilder: RequestBuilder { completion(.success(Response(response: httpResponse, body: nil))) + case is Data.Type: + + completion(.success(Response(response: httpResponse, body: data as? T))) + default: completion(.success(Response(response: httpResponse, body: data as? T))) @@ -244,7 +250,7 @@ open class URLSessionRequestBuilder: RequestBuilder { for (key, value) in headers { httpHeaders[key] = value } - for (key, value) in PetstoreClientAPI.customHeaders { + for (key, value) in PetstoreClient.customHeaders { httpHeaders[key] = value } return httpHeaders @@ -328,6 +334,43 @@ open class URLSessionDecodableRequestBuilder: URLSessionRequestBui completion(.success(Response(response: httpResponse, body: body as? T))) + case is URL.Type: + do { + + guard error == nil else { + throw DownloadException.responseFailed + } + + guard let data = data else { + throw DownloadException.responseDataMissing + } + + let fileManager = FileManager.default + let cachesDirectory = fileManager.urls(for: .cachesDirectory, in: .userDomainMask)[0] + let requestURL = try getURL(from: urlRequest) + + var requestPath = try getPath(from: requestURL) + + if let headerFileName = getFileName(fromContentDisposition: httpResponse.allHeaderFields["Content-Disposition"] as? String) { + requestPath = requestPath.appending("/\(headerFileName)") + } else { + requestPath = requestPath.appending("/tmp.PetstoreClient.\(UUID().uuidString)") + } + + let filePath = cachesDirectory.appendingPathComponent(requestPath) + let directoryPath = filePath.deletingLastPathComponent().path + + try fileManager.createDirectory(atPath: directoryPath, withIntermediateDirectories: true, attributes: nil) + try data.write(to: filePath, options: .atomic) + + completion(.success(Response(response: httpResponse, body: filePath as? T))) + + } catch let requestParserError as DownloadException { + completion(.failure(ErrorResponse.error(400, data, response, requestParserError))) + } catch { + completion(.failure(ErrorResponse.error(400, data, response, error))) + } + case is Void.Type: completion(.success(Response(response: httpResponse, body: nil))) diff --git a/samples/client/petstore/swift5/promisekitLibrary/SwaggerClientTests/.gitignore b/samples/client/petstore/swift5/promisekitLibrary/SwaggerClientTests/.gitignore index 0269c2f56db..22029d2f644 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/SwaggerClientTests/.gitignore +++ b/samples/client/petstore/swift5/promisekitLibrary/SwaggerClientTests/.gitignore @@ -1,14 +1,22 @@ -### https://raw.github.com/github/gitignore/7792e50daeaa6c07460484704671d1dc9f0045a7/Swift.gitignore +# Created by https://www.toptal.com/developers/gitignore/api/swift,xcode +# Edit at https://www.toptal.com/developers/gitignore?templates=swift,xcode +### Swift ### # Xcode # # gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore -## Build generated +## User settings +xcuserdata/ + +## compatibility with Xcode 8 and earlier (ignoring not required starting Xcode 9) +*.xcscmblueprint +*.xccheckout + +## compatibility with Xcode 3 and earlier (ignoring not required starting Xcode 4) build/ DerivedData/ - -## Various settings +*.moved-aside *.pbxuser !default.pbxuser *.mode1v3 @@ -17,15 +25,11 @@ DerivedData/ !default.mode2v3 *.perspectivev3 !default.perspectivev3 -xcuserdata/ - -## Other -*.moved-aside -*.xccheckout -*.xcscmblueprint ## Obj-C/Swift specific *.hmap + +## App packaging *.ipa *.dSYM.zip *.dSYM @@ -35,38 +39,67 @@ timeline.xctimeline playground.xcworkspace # Swift Package Manager -# # Add this line if you want to avoid checking in source code from Swift Package Manager dependencies. # Packages/ # Package.pins # Package.resolved +# *.xcodeproj +# Xcode automatically generates this directory with a .xcworkspacedata file and xcuserdata +# hence it is not needed unless you have added a package configuration file to your project +# .swiftpm + .build/ # CocoaPods -# # We recommend against adding the Pods directory to your .gitignore. However # you should judge for yourself, the pros and cons are mentioned at: # https://guides.cocoapods.org/using/using-cocoapods.html#should-i-check-the-pods-directory-into-source-control -# -Pods/ +# Pods/ +# Add this line if you want to avoid checking in source code from the Xcode workspace +# *.xcworkspace # Carthage -# # Add this line if you want to avoid checking in source code from Carthage dependencies. -Carthage/Checkouts +# Carthage/Checkouts -Carthage/Build +Carthage/Build/ + +# Add this lines if you are using Accio dependency management (Deprecated since Xcode 12) +# Dependencies/ +# .accio/ # fastlane -# -# It is recommended to not store the screenshots in the git repo. Instead, use fastlane to re-generate the -# screenshots whenever they are needed. +# It is recommended to not store the screenshots in the git repo. +# Instead, use fastlane to re-generate the screenshots whenever they are needed. # For more information about the recommended setup visit: # https://docs.fastlane.tools/best-practices/source-control/#source-control fastlane/report.xml fastlane/Preview.html -fastlane/screenshots +fastlane/screenshots/**/*.png fastlane/test_output +# Code Injection +# After new code Injection tools there's a generated folder /iOSInjectionProject +# https://github.com/johnno1962/injectionforxcode +iOSInjectionProject/ + +### Xcode ### +# Xcode +# gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore + + + + +## Gcc Patch +/*.gcno + +### Xcode Patch ### +*.xcodeproj/* +!*.xcodeproj/project.pbxproj +!*.xcodeproj/xcshareddata/ +!*.xcworkspace/contents.xcworkspacedata +**/xcshareddata/WorkspaceSettings.xcsettings + +# End of https://www.toptal.com/developers/gitignore/api/swift,xcode \ No newline at end of file diff --git a/samples/client/petstore/swift5/promisekitLibrary/SwaggerClientTests/Podfile b/samples/client/petstore/swift5/promisekitLibrary/SwaggerClientTests/Podfile deleted file mode 100644 index 77432f9eee9..00000000000 --- a/samples/client/petstore/swift5/promisekitLibrary/SwaggerClientTests/Podfile +++ /dev/null @@ -1,13 +0,0 @@ -platform :ios, '9.0' - -source 'https://cdn.cocoapods.org/' - -use_frameworks! - -target 'SwaggerClient' do - pod "PetstoreClient", :path => "../" - - target 'SwaggerClientTests' do - inherit! :search_paths - end -end diff --git a/samples/client/petstore/swift5/promisekitLibrary/SwaggerClientTests/Podfile.lock b/samples/client/petstore/swift5/promisekitLibrary/SwaggerClientTests/Podfile.lock deleted file mode 100644 index c75f76b2fb8..00000000000 --- a/samples/client/petstore/swift5/promisekitLibrary/SwaggerClientTests/Podfile.lock +++ /dev/null @@ -1,23 +0,0 @@ -PODS: - - PetstoreClient (1.0.0): - - PromiseKit/CorePromise (~> 6.13.1) - - PromiseKit/CorePromise (6.13.1) - -DEPENDENCIES: - - PetstoreClient (from `../`) - -SPEC REPOS: - trunk: - - PromiseKit - -EXTERNAL SOURCES: - PetstoreClient: - :path: "../" - -SPEC CHECKSUMS: - PetstoreClient: bf095c434cf89014d1b574779fcc7701a551fcce - PromiseKit: 28fda91c973cc377875d8c0ea4f973013c05b6db - -PODFILE CHECKSUM: 509bec696cc1d8641751b52e4fe4bef04ac4542c - -COCOAPODS: 1.10.0 diff --git a/samples/client/petstore/swift5/promisekitLibrary/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj b/samples/client/petstore/swift5/promisekitLibrary/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj index 47fa20866ce..6013383e0d1 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj +++ b/samples/client/petstore/swift5/promisekitLibrary/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj @@ -3,11 +3,10 @@ archiveVersion = 1; classes = { }; - objectVersion = 46; + objectVersion = 52; objects = { /* Begin PBXBuildFile section */ - 54DA06C1D70D78EC0EC72B61 /* Pods_SwaggerClientTests.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = F65B6638217EDDC99D103B16 /* Pods_SwaggerClientTests.framework */; }; 6D4EFB951C692C6300B96B06 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6D4EFB941C692C6300B96B06 /* AppDelegate.swift */; }; 6D4EFB971C692C6300B96B06 /* ViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6D4EFB961C692C6300B96B06 /* ViewController.swift */; }; 6D4EFB9A1C692C6300B96B06 /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 6D4EFB981C692C6300B96B06 /* Main.storyboard */; }; @@ -16,7 +15,7 @@ 6D4EFBB51C693BE200B96B06 /* PetAPITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6D4EFBB41C693BE200B96B06 /* PetAPITests.swift */; }; 6D4EFBB71C693BED00B96B06 /* StoreAPITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6D4EFBB61C693BED00B96B06 /* StoreAPITests.swift */; }; 6D4EFBB91C693BFC00B96B06 /* UserAPITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6D4EFBB81C693BFC00B96B06 /* UserAPITests.swift */; }; - 751C65B82F596107A3DC8ED9 /* Pods_SwaggerClient.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 8F60AECFF321A25553B6A5B0 /* Pods_SwaggerClient.framework */; }; + A5782C6B2664F87200CAA106 /* PetstoreClient in Frameworks */ = {isa = PBXBuildFile; productRef = A5782C6A2664F87200CAA106 /* PetstoreClient */; }; A5EA125C2419398500E30FC3 /* UIImage+Extras.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5EA125A2419398500E30FC3 /* UIImage+Extras.swift */; }; A5EA125D2419398500E30FC3 /* FileUtils.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5EA125B2419398500E30FC3 /* FileUtils.swift */; }; /* End PBXBuildFile section */ @@ -32,7 +31,6 @@ /* End PBXContainerItemProxy section */ /* Begin PBXFileReference section */ - 289E8A9E9C0BB66AD190C7C6 /* Pods-SwaggerClientTests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-SwaggerClientTests.debug.xcconfig"; path = "Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests.debug.xcconfig"; sourceTree = ""; }; 6D4EFB911C692C6300B96B06 /* SwaggerClient.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = SwaggerClient.app; sourceTree = BUILT_PRODUCTS_DIR; }; 6D4EFB941C692C6300B96B06 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; 6D4EFB961C692C6300B96B06 /* ViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ViewController.swift; sourceTree = ""; }; @@ -45,14 +43,8 @@ 6D4EFBB41C693BE200B96B06 /* PetAPITests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PetAPITests.swift; sourceTree = ""; }; 6D4EFBB61C693BED00B96B06 /* StoreAPITests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StoreAPITests.swift; sourceTree = ""; }; 6D4EFBB81C693BFC00B96B06 /* UserAPITests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = UserAPITests.swift; sourceTree = ""; }; - 8F60AECFF321A25553B6A5B0 /* Pods_SwaggerClient.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_SwaggerClient.framework; sourceTree = BUILT_PRODUCTS_DIR; }; A5EA125A2419398500E30FC3 /* UIImage+Extras.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "UIImage+Extras.swift"; sourceTree = ""; }; A5EA125B2419398500E30FC3 /* FileUtils.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FileUtils.swift; sourceTree = ""; }; - A638467ACFB30852DEA51F7A /* Pods-SwaggerClient.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-SwaggerClient.debug.xcconfig"; path = "Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient.debug.xcconfig"; sourceTree = ""; }; - B4B2BEC2ECA535C616F2F3FE /* Pods-SwaggerClientTests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-SwaggerClientTests.release.xcconfig"; path = "Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests.release.xcconfig"; sourceTree = ""; }; - C07EC0A94AA0F86D60668B32 /* Pods.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods.framework; sourceTree = BUILT_PRODUCTS_DIR; }; - F65B6638217EDDC99D103B16 /* Pods_SwaggerClientTests.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_SwaggerClientTests.framework; sourceTree = BUILT_PRODUCTS_DIR; }; - FC60BDC7328C2AA916F25840 /* Pods-SwaggerClient.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-SwaggerClient.release.xcconfig"; path = "Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient.release.xcconfig"; sourceTree = ""; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ @@ -60,7 +52,7 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( - 751C65B82F596107A3DC8ED9 /* Pods_SwaggerClient.framework in Frameworks */, + A5782C6B2664F87200CAA106 /* PetstoreClient in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -68,30 +60,15 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( - 54DA06C1D70D78EC0EC72B61 /* Pods_SwaggerClientTests.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */ - 0CAA98BEFA303B94D3664C7D /* Pods */ = { - isa = PBXGroup; - children = ( - A638467ACFB30852DEA51F7A /* Pods-SwaggerClient.debug.xcconfig */, - FC60BDC7328C2AA916F25840 /* Pods-SwaggerClient.release.xcconfig */, - 289E8A9E9C0BB66AD190C7C6 /* Pods-SwaggerClientTests.debug.xcconfig */, - B4B2BEC2ECA535C616F2F3FE /* Pods-SwaggerClientTests.release.xcconfig */, - ); - name = Pods; - sourceTree = ""; - }; 3FABC56EC0BA84CBF4F99564 /* Frameworks */ = { isa = PBXGroup; children = ( - C07EC0A94AA0F86D60668B32 /* Pods.framework */, - 8F60AECFF321A25553B6A5B0 /* Pods_SwaggerClient.framework */, - F65B6638217EDDC99D103B16 /* Pods_SwaggerClientTests.framework */, ); name = Frameworks; sourceTree = ""; @@ -103,7 +80,6 @@ 6D4EFBA81C692C6300B96B06 /* SwaggerClientTests */, 6D4EFB921C692C6300B96B06 /* Products */, 3FABC56EC0BA84CBF4F99564 /* Frameworks */, - 0CAA98BEFA303B94D3664C7D /* Pods */, ); sourceTree = ""; }; @@ -149,17 +125,18 @@ isa = PBXNativeTarget; buildConfigurationList = 6D4EFBAE1C692C6300B96B06 /* Build configuration list for PBXNativeTarget "SwaggerClient" */; buildPhases = ( - 1F03F780DC2D9727E5E64BA9 /* [CP] Check Pods Manifest.lock */, 6D4EFB8D1C692C6300B96B06 /* Sources */, 6D4EFB8E1C692C6300B96B06 /* Frameworks */, 6D4EFB8F1C692C6300B96B06 /* Resources */, - 4485A75250058E2D5BBDF63F /* [CP] Embed Pods Frameworks */, ); buildRules = ( ); dependencies = ( ); name = SwaggerClient; + packageProductDependencies = ( + A5782C6A2664F87200CAA106 /* PetstoreClient */, + ); productName = SwaggerClient; productReference = 6D4EFB911C692C6300B96B06 /* SwaggerClient.app */; productType = "com.apple.product-type.application"; @@ -168,7 +145,6 @@ isa = PBXNativeTarget; buildConfigurationList = 6D4EFBB11C692C6300B96B06 /* Build configuration list for PBXNativeTarget "SwaggerClientTests" */; buildPhases = ( - 79FE27B09B2DD354C831BD49 /* [CP] Check Pods Manifest.lock */, 6D4EFBA11C692C6300B96B06 /* Sources */, 6D4EFBA21C692C6300B96B06 /* Frameworks */, 6D4EFBA31C692C6300B96B06 /* Resources */, @@ -243,65 +219,6 @@ }; /* End PBXResourcesBuildPhase section */ -/* Begin PBXShellScriptBuildPhase section */ - 1F03F780DC2D9727E5E64BA9 /* [CP] Check Pods Manifest.lock */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputPaths = ( - "${PODS_PODFILE_DIR_PATH}/Podfile.lock", - "${PODS_ROOT}/Manifest.lock", - ); - name = "[CP] Check Pods Manifest.lock"; - outputPaths = ( - "$(DERIVED_FILE_DIR)/Pods-SwaggerClient-checkManifestLockResult.txt", - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; - showEnvVarsInLog = 0; - }; - 4485A75250058E2D5BBDF63F /* [CP] Embed Pods Frameworks */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputPaths = ( - "${PODS_ROOT}/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-frameworks.sh", - "${BUILT_PRODUCTS_DIR}/PetstoreClient/PetstoreClient.framework", - "${BUILT_PRODUCTS_DIR}/PromiseKit/PromiseKit.framework", - ); - name = "[CP] Embed Pods Frameworks"; - outputPaths = ( - "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/PetstoreClient.framework", - "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/PromiseKit.framework", - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-frameworks.sh\"\n"; - showEnvVarsInLog = 0; - }; - 79FE27B09B2DD354C831BD49 /* [CP] Check Pods Manifest.lock */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputPaths = ( - "${PODS_PODFILE_DIR_PATH}/Podfile.lock", - "${PODS_ROOT}/Manifest.lock", - ); - name = "[CP] Check Pods Manifest.lock"; - outputPaths = ( - "$(DERIVED_FILE_DIR)/Pods-SwaggerClientTests-checkManifestLockResult.txt", - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; - showEnvVarsInLog = 0; - }; -/* End PBXShellScriptBuildPhase section */ - /* Begin PBXSourcesBuildPhase section */ 6D4EFB8D1C692C6300B96B06 /* Sources */ = { isa = PBXSourcesBuildPhase; @@ -455,7 +372,8 @@ IPHONEOS_DEPLOYMENT_TARGET = 9.2; MTL_ENABLE_DEBUG_INFO = NO; SDKROOT = iphoneos; - SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; SWIFT_VERSION = 4.0; TARGETED_DEVICE_FAMILY = "1,2"; VALIDATE_PRODUCT = YES; @@ -464,11 +382,13 @@ }; 6D4EFBAF1C692C6300B96B06 /* Debug */ = { isa = XCBuildConfiguration; - baseConfigurationReference = A638467ACFB30852DEA51F7A /* Pods-SwaggerClient.debug.xcconfig */; buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; INFOPLIST_FILE = SwaggerClient/Info.plist; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); PRODUCT_BUNDLE_IDENTIFIER = com.swagger.SwaggerClient; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_VERSION = 5.0; @@ -477,11 +397,13 @@ }; 6D4EFBB01C692C6300B96B06 /* Release */ = { isa = XCBuildConfiguration; - baseConfigurationReference = FC60BDC7328C2AA916F25840 /* Pods-SwaggerClient.release.xcconfig */; buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; INFOPLIST_FILE = SwaggerClient/Info.plist; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); PRODUCT_BUNDLE_IDENTIFIER = com.swagger.SwaggerClient; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_VERSION = 5.0; @@ -490,11 +412,14 @@ }; 6D4EFBB21C692C6300B96B06 /* Debug */ = { isa = XCBuildConfiguration; - baseConfigurationReference = 289E8A9E9C0BB66AD190C7C6 /* Pods-SwaggerClientTests.debug.xcconfig */; buildSettings = { BUNDLE_LOADER = "$(TEST_HOST)"; INFOPLIST_FILE = SwaggerClientTests/Info.plist; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); PRODUCT_BUNDLE_IDENTIFIER = com.swagger.SwaggerClientTests; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_VERSION = 5.0; @@ -504,11 +429,14 @@ }; 6D4EFBB31C692C6300B96B06 /* Release */ = { isa = XCBuildConfiguration; - baseConfigurationReference = B4B2BEC2ECA535C616F2F3FE /* Pods-SwaggerClientTests.release.xcconfig */; buildSettings = { BUNDLE_LOADER = "$(TEST_HOST)"; INFOPLIST_FILE = SwaggerClientTests/Info.plist; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); PRODUCT_BUNDLE_IDENTIFIER = com.swagger.SwaggerClientTests; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_VERSION = 5.0; @@ -547,6 +475,13 @@ defaultConfigurationName = Release; }; /* End XCConfigurationList section */ + +/* Begin XCSwiftPackageProductDependency section */ + A5782C6A2664F87200CAA106 /* PetstoreClient */ = { + isa = XCSwiftPackageProductDependency; + productName = PetstoreClient; + }; +/* End XCSwiftPackageProductDependency section */ }; rootObject = 6D4EFB891C692C6300B96B06 /* Project object */; } diff --git a/samples/client/petstore/swift5/promisekitLibrary/SwaggerClientTests/SwaggerClient.xcworkspace/contents.xcworkspacedata b/samples/client/petstore/swift5/promisekitLibrary/SwaggerClientTests/SwaggerClient.xcworkspace/contents.xcworkspacedata index 9b3fa18954f..00ec9b53a7f 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/SwaggerClientTests/SwaggerClient.xcworkspace/contents.xcworkspacedata +++ b/samples/client/petstore/swift5/promisekitLibrary/SwaggerClientTests/SwaggerClient.xcworkspace/contents.xcworkspacedata @@ -2,9 +2,9 @@ + location = "group:.."> + location = "group:SwaggerClient.xcodeproj"> diff --git a/samples/client/petstore/swift5/promisekitLibrary/SwaggerClientTests/SwaggerClient.xcworkspace/xcshareddata/swiftpm/Package.resolved b/samples/client/petstore/swift5/promisekitLibrary/SwaggerClientTests/SwaggerClient.xcworkspace/xcshareddata/swiftpm/Package.resolved new file mode 100644 index 00000000000..63ce26f05eb --- /dev/null +++ b/samples/client/petstore/swift5/promisekitLibrary/SwaggerClientTests/SwaggerClient.xcworkspace/xcshareddata/swiftpm/Package.resolved @@ -0,0 +1,25 @@ +{ + "object": { + "pins": [ + { + "package": "AnyCodable", + "repositoryURL": "https://github.com/Flight-School/AnyCodable", + "state": { + "branch": null, + "revision": "876d162385e9862ae8b3c8d65dc301312b040005", + "version": "0.6.0" + } + }, + { + "package": "PromiseKit", + "repositoryURL": "https://github.com/mxcl/PromiseKit.git", + "state": { + "branch": null, + "revision": "d2f7ba14bcdc45e18f4f60ad9df883fb9055f081", + "version": "6.15.3" + } + } + ] + }, + "version": 1 +} diff --git a/samples/client/petstore/swift5/promisekitLibrary/docs/FakeAPI.md b/samples/client/petstore/swift5/promisekitLibrary/docs/FakeAPI.md index f2b3e2abe1e..a79f3ecc8af 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/docs/FakeAPI.md +++ b/samples/client/petstore/swift5/promisekitLibrary/docs/FakeAPI.md @@ -358,7 +358,7 @@ import PetstoreClient let number = 987 // Double | None let double = 987 // Double | None let patternWithoutDelimiter = "patternWithoutDelimiter_example" // String | None -let byte = 987 // Data | None +let byte = Data([9, 8, 7]) // Data | None let integer = 987 // Int | None (optional) let int32 = 987 // Int | None (optional) let int64 = 987 // Int64 | None (optional) diff --git a/samples/client/petstore/swift5/promisekitLibrary/project.yml b/samples/client/petstore/swift5/promisekitLibrary/project.yml index 043be1cc387..20bb0a7f6e9 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/project.yml +++ b/samples/client/petstore/swift5/promisekitLibrary/project.yml @@ -12,5 +12,5 @@ targets: APPLICATION_EXTENSION_API_ONLY: true scheme: {} dependencies: - - carthage: PromiseKit - carthage: AnyCodable + - carthage: PromiseKit diff --git a/samples/client/petstore/swift5/readonlyProperties/.gitignore b/samples/client/petstore/swift5/readonlyProperties/.gitignore index 5e5d5cebcf4..627d360a903 100644 --- a/samples/client/petstore/swift5/readonlyProperties/.gitignore +++ b/samples/client/petstore/swift5/readonlyProperties/.gitignore @@ -1,12 +1,22 @@ +# Created by https://www.toptal.com/developers/gitignore/api/swift,xcode +# Edit at https://www.toptal.com/developers/gitignore?templates=swift,xcode + +### Swift ### # Xcode # # gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore -## Build generated -build/ -DerivedData +## User settings +xcuserdata/ -## Various settings +## compatibility with Xcode 8 and earlier (ignoring not required starting Xcode 9) +*.xcscmblueprint +*.xccheckout + +## compatibility with Xcode 3 and earlier (ignoring not required starting Xcode 4) +build/ +DerivedData/ +*.moved-aside *.pbxuser !default.pbxuser *.mode1v3 @@ -15,49 +25,81 @@ DerivedData !default.mode2v3 *.perspectivev3 !default.perspectivev3 -xcuserdata - -## Other -*.xccheckout -*.moved-aside -*.xcuserstate -*.xcscmblueprint ## Obj-C/Swift specific *.hmap + +## App packaging *.ipa +*.dSYM.zip +*.dSYM ## Playgrounds timeline.xctimeline playground.xcworkspace # Swift Package Manager -# # Add this line if you want to avoid checking in source code from Swift Package Manager dependencies. # Packages/ +# Package.pins +# Package.resolved +# *.xcodeproj +# Xcode automatically generates this directory with a .xcworkspacedata file and xcuserdata +# hence it is not needed unless you have added a package configuration file to your project +# .swiftpm + .build/ # CocoaPods -# # We recommend against adding the Pods directory to your .gitignore. However # you should judge for yourself, the pros and cons are mentioned at: # https://guides.cocoapods.org/using/using-cocoapods.html#should-i-check-the-pods-directory-into-source-control -# # Pods/ +# Add this line if you want to avoid checking in source code from the Xcode workspace +# *.xcworkspace # Carthage -# # Add this line if you want to avoid checking in source code from Carthage dependencies. # Carthage/Checkouts -Carthage/Build +Carthage/Build/ + +# Add this lines if you are using Accio dependency management (Deprecated since Xcode 12) +# Dependencies/ +# .accio/ # fastlane -# -# It is recommended to not store the screenshots in the git repo. Instead, use fastlane to re-generate the -# screenshots whenever they are needed. +# It is recommended to not store the screenshots in the git repo. +# Instead, use fastlane to re-generate the screenshots whenever they are needed. # For more information about the recommended setup visit: -# https://github.com/fastlane/fastlane/blob/master/docs/Gitignore.md +# https://docs.fastlane.tools/best-practices/source-control/#source-control fastlane/report.xml -fastlane/screenshots +fastlane/Preview.html +fastlane/screenshots/**/*.png +fastlane/test_output + +# Code Injection +# After new code Injection tools there's a generated folder /iOSInjectionProject +# https://github.com/johnno1962/injectionforxcode + +iOSInjectionProject/ + +### Xcode ### +# Xcode +# gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore + + + + +## Gcc Patch +/*.gcno + +### Xcode Patch ### +*.xcodeproj/* +!*.xcodeproj/project.pbxproj +!*.xcodeproj/xcshareddata/ +!*.xcworkspace/contents.xcworkspacedata +**/xcshareddata/WorkspaceSettings.xcsettings + +# End of https://www.toptal.com/developers/gitignore/api/swift,xcode diff --git a/samples/client/petstore/swift5/readonlyProperties/.openapi-generator/VERSION b/samples/client/petstore/swift5/readonlyProperties/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/client/petstore/swift5/readonlyProperties/.openapi-generator/VERSION +++ b/samples/client/petstore/swift5/readonlyProperties/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/client/petstore/swift5/readonlyProperties/Cartfile b/samples/client/petstore/swift5/readonlyProperties/Cartfile index 84aaa61ef2d..a6a6bcacb1d 100644 --- a/samples/client/petstore/swift5/readonlyProperties/Cartfile +++ b/samples/client/petstore/swift5/readonlyProperties/Cartfile @@ -1,2 +1,2 @@ -github "Flight-School/AnyCodable" ~> 0.4.0 +github "Flight-School/AnyCodable" ~> 0.6.1 diff --git a/samples/client/petstore/swift5/readonlyProperties/Package.resolved b/samples/client/petstore/swift5/readonlyProperties/Package.resolved new file mode 100644 index 00000000000..79610c3b3b3 --- /dev/null +++ b/samples/client/petstore/swift5/readonlyProperties/Package.resolved @@ -0,0 +1,16 @@ +{ + "object": { + "pins": [ + { + "package": "AnyCodable", + "repositoryURL": "https://github.com/Flight-School/AnyCodable", + "state": { + "branch": null, + "revision": "69261f239f0fffaf51495dadc4f8483fbfe97025", + "version": "0.6.1" + } + } + ] + }, + "version": 1 +} diff --git a/samples/client/petstore/swift5/readonlyProperties/Package.swift b/samples/client/petstore/swift5/readonlyProperties/Package.swift index b724838fe8d..87bb775fb72 100644 --- a/samples/client/petstore/swift5/readonlyProperties/Package.swift +++ b/samples/client/petstore/swift5/readonlyProperties/Package.swift @@ -19,7 +19,7 @@ let package = Package( ], dependencies: [ // Dependencies declare other packages that this package depends on. - .package(url: "https://github.com/Flight-School/AnyCodable", .exact("0.4.0")), + .package(url: "https://github.com/Flight-School/AnyCodable", from: "0.6.1"), ], targets: [ // Targets are the basic building blocks of a package. A target can define a module or a test suite. diff --git a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient.podspec b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient.podspec index de06558efbd..0e6bf7ec024 100644 --- a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient.podspec +++ b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient.podspec @@ -11,5 +11,5 @@ Pod::Spec.new do |s| s.homepage = 'https://github.com/openapitools/openapi-generator' s.summary = 'PetstoreClient' s.source_files = 'PetstoreClient/Classes/**/*.swift' - s.dependency 'AnyCodable-FlightSchool', '~> 0.4.0' + s.dependency 'AnyCodable-FlightSchool', '~> 0.6.1' end diff --git a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/APIs.swift b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/APIs.swift index dbdab491ff7..941c61b713a 100644 --- a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/APIs.swift +++ b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/APIs.swift @@ -6,10 +6,13 @@ import Foundation -open class PetstoreClientAPI { +@available(*, deprecated, renamed: "PetstoreClient") +public typealias PetstoreClientAPI = PetstoreClient + +open class PetstoreClient { public static var basePath = "http://petstore.swagger.io:80/v2" - public static var credential: URLCredential? public static var customHeaders: [String: String] = [:] + public static var credential: URLCredential? public static var requestBuilderFactory: RequestBuilderFactory = URLSessionRequestBuilderFactory() public static var apiResponseQueue: DispatchQueue = .main } @@ -32,7 +35,7 @@ open class RequestBuilder { self.parameters = parameters self.headers = headers - addHeaders(PetstoreClientAPI.customHeaders) + addHeaders(PetstoreClient.customHeaders) } open func addHeaders(_ aHeaders: [String: String]) { @@ -41,7 +44,7 @@ open class RequestBuilder { } } - open func execute(_ apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, _ completion: @escaping (_ result: Swift.Result, Error>) -> Void) { } + open func execute(_ apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, _ completion: @escaping (_ result: Swift.Result, Error>) -> Void) { } public func addHeader(name: String, value: String) -> Self { if !value.isEmpty { @@ -51,7 +54,7 @@ open class RequestBuilder { } open func addCredential() -> Self { - credential = PetstoreClientAPI.credential + credential = PetstoreClient.credential return self } } 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 72b89640eeb..ac9dd9b74f2 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 @@ -6,8 +6,12 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif open class AnotherFakeAPI { + /** To test special tags @@ -15,7 +19,7 @@ open class AnotherFakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func call123testSpecialTags(body: Client, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Client?, _ error: Error?) -> Void)) { + open class func call123testSpecialTags(body: Client, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Client?, _ error: Error?) -> Void)) { call123testSpecialTagsWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -34,21 +38,20 @@ open class AnotherFakeAPI { - returns: RequestBuilder */ open class func call123testSpecialTagsWithRequestBuilder(body: Client) -> RequestBuilder { - let path = "/another-fake/dummy" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/another-fake/dummy" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "PATCH", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "PATCH", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } - } 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 cf92424d9cc..d7260ca2e3a 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 @@ -6,15 +6,19 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif open class FakeAPI { + /** - parameter body: (body) Input boolean as post body (optional) - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func fakeOuterBooleanSerialize(body: Bool? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Bool?, _ error: Error?) -> Void)) { + open class func fakeOuterBooleanSerialize(body: Bool? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Bool?, _ error: Error?) -> Void)) { fakeOuterBooleanSerializeWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -32,21 +36,21 @@ open class FakeAPI { - returns: RequestBuilder */ open class func fakeOuterBooleanSerializeWithRequestBuilder(body: Bool? = nil) -> RequestBuilder { - let path = "/fake/outer/boolean" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/fake/outer/boolean" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -55,7 +59,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func fakeOuterCompositeSerialize(body: OuterComposite? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: OuterComposite?, _ error: Error?) -> Void)) { + open class func fakeOuterCompositeSerialize(body: OuterComposite? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: OuterComposite?, _ error: Error?) -> Void)) { fakeOuterCompositeSerializeWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -73,21 +77,21 @@ open class FakeAPI { - returns: RequestBuilder */ open class func fakeOuterCompositeSerializeWithRequestBuilder(body: OuterComposite? = nil) -> RequestBuilder { - let path = "/fake/outer/composite" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/fake/outer/composite" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -96,7 +100,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func fakeOuterNumberSerialize(body: Double? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Double?, _ error: Error?) -> Void)) { + open class func fakeOuterNumberSerialize(body: Double? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Double?, _ error: Error?) -> Void)) { fakeOuterNumberSerializeWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -114,21 +118,21 @@ open class FakeAPI { - returns: RequestBuilder */ open class func fakeOuterNumberSerializeWithRequestBuilder(body: Double? = nil) -> RequestBuilder { - let path = "/fake/outer/number" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/fake/outer/number" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -137,7 +141,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func fakeOuterStringSerialize(body: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: String?, _ error: Error?) -> Void)) { + open class func fakeOuterStringSerialize(body: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: String?, _ error: Error?) -> Void)) { fakeOuterStringSerializeWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -155,21 +159,21 @@ open class FakeAPI { - returns: RequestBuilder */ open class func fakeOuterStringSerializeWithRequestBuilder(body: String? = nil) -> RequestBuilder { - let path = "/fake/outer/string" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/fake/outer/string" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -178,7 +182,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func testBodyWithFileSchema(body: FileSchemaTestClass, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func testBodyWithFileSchema(body: FileSchemaTestClass, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { testBodyWithFileSchemaWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -196,21 +200,21 @@ open class FakeAPI { - returns: RequestBuilder */ open class func testBodyWithFileSchemaWithRequestBuilder(body: FileSchemaTestClass) -> RequestBuilder { - let path = "/fake/body-with-file-schema" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/fake/body-with-file-schema" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "PUT", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -220,7 +224,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func testBodyWithQueryParams(query: String, body: User, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func testBodyWithQueryParams(query: String, body: User, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { testBodyWithQueryParamsWithRequestBuilder(query: query, body: body).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -238,24 +242,24 @@ open class FakeAPI { - returns: RequestBuilder */ open class func testBodyWithQueryParamsWithRequestBuilder(query: String, body: User) -> RequestBuilder { - let path = "/fake/body-with-query-params" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/fake/body-with-query-params" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - var urlComponents = URLComponents(string: URLString) - urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ + var localVariableUrlComponents = URLComponents(string: localVariableURLString) + localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ "query": query.encodeToJSON(), ]) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "PUT", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -265,7 +269,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func testClientModel(body: Client, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Client?, _ error: Error?) -> Void)) { + open class func testClientModel(body: Client, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Client?, _ error: Error?) -> Void)) { testClientModelWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -284,21 +288,21 @@ open class FakeAPI { - returns: RequestBuilder */ open class func testClientModelWithRequestBuilder(body: Client) -> RequestBuilder { - let path = "/fake" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/fake" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "PATCH", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "PATCH", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -321,7 +325,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func testEndpointParameters(number: Double, double: Double, patternWithoutDelimiter: String, byte: Data, integer: Int? = nil, int32: Int? = nil, int64: Int64? = nil, float: Float? = nil, string: String? = nil, binary: URL? = nil, date: Date? = nil, dateTime: Date? = nil, password: String? = nil, callback: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func testEndpointParameters(number: Double, double: Double, patternWithoutDelimiter: String, byte: Data, integer: Int? = nil, int32: Int? = nil, int64: Int64? = nil, float: Float? = nil, string: String? = nil, binary: URL? = nil, date: Date? = nil, dateTime: Date? = nil, password: String? = nil, callback: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { testEndpointParametersWithRequestBuilder(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(apiResponseQueue) { result -> Void in switch result { case .success: @@ -356,9 +360,9 @@ open class FakeAPI { - returns: RequestBuilder */ open class func testEndpointParametersWithRequestBuilder(number: Double, double: Double, patternWithoutDelimiter: String, byte: Data, integer: Int? = nil, int32: Int? = nil, int64: Int64? = nil, float: Float? = nil, string: String? = nil, binary: URL? = nil, date: Date? = nil, dateTime: Date? = nil, password: String? = nil, callback: String? = nil) -> RequestBuilder { - let path = "/fake" - let URLString = PetstoreClientAPI.basePath + path - let formParams: [String: Any?] = [ + let localVariablePath = "/fake" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableFormParams: [String: Any?] = [ "integer": integer?.encodeToJSON(), "int32": int32?.encodeToJSON(), "int64": int64?.encodeToJSON(), @@ -375,20 +379,20 @@ open class FakeAPI { "callback": callback?.encodeToJSON(), ] - let nonNullParameters = APIHelper.rejectNil(formParams) - let parameters = APIHelper.convertBoolToString(nonNullParameters) + let localVariableNonNullParameters = APIHelper.rejectNil(localVariableFormParams) + let localVariableParameters = APIHelper.convertBoolToString(localVariableNonNullParameters) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ "Content-Type": "application/x-www-form-urlencoded", ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -472,7 +476,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func testEnumParameters(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func testEnumParameters(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { testEnumParametersWithRequestBuilder(enumHeaderStringArray: enumHeaderStringArray, enumHeaderString: enumHeaderString, enumQueryStringArray: enumQueryStringArray, enumQueryString: enumQueryString, enumQueryInteger: enumQueryInteger, enumQueryDouble: enumQueryDouble, enumFormStringArray: enumFormStringArray, enumFormString: enumFormString).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -498,35 +502,35 @@ open class FakeAPI { - returns: RequestBuilder */ open class func testEnumParametersWithRequestBuilder(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil) -> RequestBuilder { - let path = "/fake" - let URLString = PetstoreClientAPI.basePath + path - let formParams: [String: Any?] = [ + let localVariablePath = "/fake" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableFormParams: [String: Any?] = [ "enum_form_string_array": enumFormStringArray?.encodeToJSON(), "enum_form_string": enumFormString?.encodeToJSON(), ] - let nonNullParameters = APIHelper.rejectNil(formParams) - let parameters = APIHelper.convertBoolToString(nonNullParameters) + let localVariableNonNullParameters = APIHelper.rejectNil(localVariableFormParams) + let localVariableParameters = APIHelper.convertBoolToString(localVariableNonNullParameters) - var urlComponents = URLComponents(string: URLString) - urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ + var localVariableUrlComponents = URLComponents(string: localVariableURLString) + localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ "enum_query_string_array": enumQueryStringArray?.encodeToJSON(), "enum_query_string": enumQueryString?.encodeToJSON(), "enum_query_integer": enumQueryInteger?.encodeToJSON(), "enum_query_double": enumQueryDouble?.encodeToJSON(), ]) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ "Content-Type": "application/x-www-form-urlencoded", "enum_header_string_array": enumHeaderStringArray?.encodeToJSON(), "enum_header_string": enumHeaderString?.encodeToJSON(), ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -541,7 +545,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func testGroupParameters(requiredStringGroup: Int, requiredBooleanGroup: Bool, requiredInt64Group: Int64, stringGroup: Int? = nil, booleanGroup: Bool? = nil, int64Group: Int64? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func testGroupParameters(requiredStringGroup: Int, requiredBooleanGroup: Bool, requiredInt64Group: Int64, stringGroup: Int? = nil, booleanGroup: Bool? = nil, int64Group: Int64? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { testGroupParametersWithRequestBuilder(requiredStringGroup: requiredStringGroup, requiredBooleanGroup: requiredBooleanGroup, requiredInt64Group: requiredInt64Group, stringGroup: stringGroup, booleanGroup: booleanGroup, int64Group: int64Group).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -565,28 +569,28 @@ open class FakeAPI { - returns: RequestBuilder */ open class func testGroupParametersWithRequestBuilder(requiredStringGroup: Int, requiredBooleanGroup: Bool, requiredInt64Group: Int64, stringGroup: Int? = nil, booleanGroup: Bool? = nil, int64Group: Int64? = nil) -> RequestBuilder { - let path = "/fake" - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + let localVariablePath = "/fake" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - var urlComponents = URLComponents(string: URLString) - urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ + var localVariableUrlComponents = URLComponents(string: localVariableURLString) + localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ "required_string_group": requiredStringGroup.encodeToJSON(), "required_int64_group": requiredInt64Group.encodeToJSON(), "string_group": stringGroup?.encodeToJSON(), "int64_group": int64Group?.encodeToJSON(), ]) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ "required_boolean_group": requiredBooleanGroup.encodeToJSON(), "boolean_group": booleanGroup?.encodeToJSON(), ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "DELETE", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -596,7 +600,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func testInlineAdditionalProperties(param: [String: String], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func testInlineAdditionalProperties(param: [String: String], apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { testInlineAdditionalPropertiesWithRequestBuilder(param: param).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -614,21 +618,21 @@ open class FakeAPI { - returns: RequestBuilder */ open class func testInlineAdditionalPropertiesWithRequestBuilder(param: [String: String]) -> RequestBuilder { - let path = "/fake/inline-additionalProperties" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: param) + let localVariablePath = "/fake/inline-additionalProperties" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: param) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -639,7 +643,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func testJsonFormData(param: String, param2: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func testJsonFormData(param: String, param2: String, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { testJsonFormDataWithRequestBuilder(param: param, param2: param2).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -658,27 +662,26 @@ open class FakeAPI { - returns: RequestBuilder */ open class func testJsonFormDataWithRequestBuilder(param: String, param2: String) -> RequestBuilder { - let path = "/fake/jsonFormData" - let URLString = PetstoreClientAPI.basePath + path - let formParams: [String: Any?] = [ + let localVariablePath = "/fake/jsonFormData" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableFormParams: [String: Any?] = [ "param": param.encodeToJSON(), "param2": param2.encodeToJSON(), ] - let nonNullParameters = APIHelper.rejectNil(formParams) - let parameters = APIHelper.convertBoolToString(nonNullParameters) + let localVariableNonNullParameters = APIHelper.rejectNil(localVariableFormParams) + let localVariableParameters = APIHelper.convertBoolToString(localVariableNonNullParameters) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ "Content-Type": "application/x-www-form-urlencoded", ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } - } 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 d4d65166496..a6ca6c66b51 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 @@ -6,8 +6,12 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif open class FakeClassnameTags123API { + /** To test class name in snake case @@ -15,7 +19,7 @@ open class FakeClassnameTags123API { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func testClassname(body: Client, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Client?, _ error: Error?) -> Void)) { + open class func testClassname(body: Client, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Client?, _ error: Error?) -> Void)) { testClassnameWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -37,21 +41,20 @@ open class FakeClassnameTags123API { - returns: RequestBuilder */ open class func testClassnameWithRequestBuilder(body: Client) -> RequestBuilder { - let path = "/fake_classname_test" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/fake_classname_test" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "PATCH", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "PATCH", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } - } 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 a1fe0d12b1d..8b97def931c 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 @@ -6,8 +6,12 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif open class PetAPI { + /** Add a new pet to the store @@ -15,7 +19,7 @@ open class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func addPet(body: Pet, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func addPet(body: Pet, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { addPetWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -36,21 +40,21 @@ open class PetAPI { - returns: RequestBuilder */ open class func addPetWithRequestBuilder(body: Pet) -> RequestBuilder { - let path = "/pet" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/pet" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -61,7 +65,7 @@ open class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func deletePet(petId: Int64, apiKey: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func deletePet(petId: Int64, apiKey: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { deletePetWithRequestBuilder(petId: petId, apiKey: apiKey).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -83,24 +87,24 @@ open class PetAPI { - returns: RequestBuilder */ open class func deletePetWithRequestBuilder(petId: Int64, apiKey: String? = nil) -> RequestBuilder { - var path = "/pet/{petId}" + var localVariablePath = "/pet/{petId}" let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))" let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" - path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + localVariablePath = localVariablePath.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ "api_key": apiKey?.encodeToJSON(), ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "DELETE", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -119,7 +123,7 @@ open class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func findPetsByStatus(status: [String], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: [Pet]?, _ error: Error?) -> Void)) { + open class func findPetsByStatus(status: [String], apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: [Pet]?, _ error: Error?) -> Void)) { findPetsByStatusWithRequestBuilder(status: status).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -141,24 +145,24 @@ open class PetAPI { - returns: RequestBuilder<[Pet]> */ open class func findPetsByStatusWithRequestBuilder(status: [String]) -> RequestBuilder<[Pet]> { - let path = "/pet/findByStatus" - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + let localVariablePath = "/pet/findByStatus" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - var urlComponents = URLComponents(string: URLString) - urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ + var localVariableUrlComponents = URLComponents(string: localVariableURLString) + localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ "status": status.encodeToJSON(), ]) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -169,7 +173,7 @@ open class PetAPI { - parameter completion: completion handler to receive the data and the error objects */ @available(*, deprecated, message: "This operation is deprecated.") - open class func findPetsByTags(tags: [String], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: [Pet]?, _ error: Error?) -> Void)) { + open class func findPetsByTags(tags: [String], apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: [Pet]?, _ error: Error?) -> Void)) { findPetsByTagsWithRequestBuilder(tags: tags).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -192,24 +196,24 @@ open class PetAPI { */ @available(*, deprecated, message: "This operation is deprecated.") open class func findPetsByTagsWithRequestBuilder(tags: [String]) -> RequestBuilder<[Pet]> { - let path = "/pet/findByTags" - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + let localVariablePath = "/pet/findByTags" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - var urlComponents = URLComponents(string: URLString) - urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ + var localVariableUrlComponents = URLComponents(string: localVariableURLString) + localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ "tags": tags.encodeToJSON(), ]) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -219,7 +223,7 @@ open class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func getPetById(petId: Int64, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Pet?, _ error: Error?) -> Void)) { + open class func getPetById(petId: Int64, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Pet?, _ error: Error?) -> Void)) { getPetByIdWithRequestBuilder(petId: petId).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -241,24 +245,24 @@ open class PetAPI { - returns: RequestBuilder */ open class func getPetByIdWithRequestBuilder(petId: Int64) -> RequestBuilder { - var path = "/pet/{petId}" + var localVariablePath = "/pet/{petId}" let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))" let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" - path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + localVariablePath = localVariablePath.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -268,7 +272,7 @@ open class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func updatePet(body: Pet, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func updatePet(body: Pet, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { updatePetWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -289,21 +293,21 @@ open class PetAPI { - returns: RequestBuilder */ open class func updatePetWithRequestBuilder(body: Pet) -> RequestBuilder { - let path = "/pet" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/pet" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "PUT", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -315,7 +319,7 @@ open class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func updatePetWithForm(petId: Int64, name: String? = nil, status: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func updatePetWithForm(petId: Int64, name: String? = nil, status: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { updatePetWithFormWithRequestBuilder(petId: petId, name: name, status: status).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -338,30 +342,30 @@ open class PetAPI { - returns: RequestBuilder */ open class func updatePetWithFormWithRequestBuilder(petId: Int64, name: String? = nil, status: String? = nil) -> RequestBuilder { - var path = "/pet/{petId}" + var localVariablePath = "/pet/{petId}" let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))" let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" - path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path - let formParams: [String: Any?] = [ + localVariablePath = localVariablePath.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableFormParams: [String: Any?] = [ "name": name?.encodeToJSON(), "status": status?.encodeToJSON(), ] - let nonNullParameters = APIHelper.rejectNil(formParams) - let parameters = APIHelper.convertBoolToString(nonNullParameters) + let localVariableNonNullParameters = APIHelper.rejectNil(localVariableFormParams) + let localVariableParameters = APIHelper.convertBoolToString(localVariableNonNullParameters) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ "Content-Type": "application/x-www-form-urlencoded", ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -373,7 +377,7 @@ open class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func uploadFile(petId: Int64, additionalMetadata: String? = nil, file: URL? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: ApiResponse?, _ error: Error?) -> Void)) { + open class func uploadFile(petId: Int64, additionalMetadata: String? = nil, file: URL? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: ApiResponse?, _ error: Error?) -> Void)) { uploadFileWithRequestBuilder(petId: petId, additionalMetadata: additionalMetadata, file: file).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -396,30 +400,30 @@ open class PetAPI { - returns: RequestBuilder */ open class func uploadFileWithRequestBuilder(petId: Int64, additionalMetadata: String? = nil, file: URL? = nil) -> RequestBuilder { - var path = "/pet/{petId}/uploadImage" + var localVariablePath = "/pet/{petId}/uploadImage" let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))" let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" - path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path - let formParams: [String: Any?] = [ + localVariablePath = localVariablePath.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableFormParams: [String: Any?] = [ "additionalMetadata": additionalMetadata?.encodeToJSON(), "file": file?.encodeToJSON(), ] - let nonNullParameters = APIHelper.rejectNil(formParams) - let parameters = APIHelper.convertBoolToString(nonNullParameters) + let localVariableNonNullParameters = APIHelper.rejectNil(localVariableFormParams) + let localVariableParameters = APIHelper.convertBoolToString(localVariableNonNullParameters) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ "Content-Type": "multipart/form-data", ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -431,7 +435,7 @@ open class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func uploadFileWithRequiredFile(petId: Int64, requiredFile: URL, additionalMetadata: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: ApiResponse?, _ error: Error?) -> Void)) { + open class func uploadFileWithRequiredFile(petId: Int64, requiredFile: URL, additionalMetadata: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: ApiResponse?, _ error: Error?) -> Void)) { uploadFileWithRequiredFileWithRequestBuilder(petId: petId, requiredFile: requiredFile, additionalMetadata: additionalMetadata).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -454,30 +458,29 @@ open class PetAPI { - returns: RequestBuilder */ open class func uploadFileWithRequiredFileWithRequestBuilder(petId: Int64, requiredFile: URL, additionalMetadata: String? = nil) -> RequestBuilder { - var path = "/fake/{petId}/uploadImageWithRequiredFile" + var localVariablePath = "/fake/{petId}/uploadImageWithRequiredFile" let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))" let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" - path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path - let formParams: [String: Any?] = [ + localVariablePath = localVariablePath.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableFormParams: [String: Any?] = [ "additionalMetadata": additionalMetadata?.encodeToJSON(), "requiredFile": requiredFile.encodeToJSON(), ] - let nonNullParameters = APIHelper.rejectNil(formParams) - let parameters = APIHelper.convertBoolToString(nonNullParameters) + let localVariableNonNullParameters = APIHelper.rejectNil(localVariableFormParams) + let localVariableParameters = APIHelper.convertBoolToString(localVariableNonNullParameters) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ "Content-Type": "multipart/form-data", ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } - } diff --git a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift index 501f11f5f21..53c1fed1eb3 100644 --- a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift +++ b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift @@ -6,8 +6,12 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif open class StoreAPI { + /** Delete purchase order by ID @@ -15,7 +19,7 @@ open class StoreAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func deleteOrder(orderId: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func deleteOrder(orderId: String, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { deleteOrderWithRequestBuilder(orderId: orderId).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -34,24 +38,24 @@ open class StoreAPI { - returns: RequestBuilder */ open class func deleteOrderWithRequestBuilder(orderId: String) -> RequestBuilder { - var path = "/store/order/{order_id}" + var localVariablePath = "/store/order/{order_id}" let orderIdPreEscape = "\(APIHelper.mapValueToPathItem(orderId))" let orderIdPostEscape = orderIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" - path = path.replacingOccurrences(of: "{order_id}", with: orderIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + localVariablePath = localVariablePath.replacingOccurrences(of: "{order_id}", with: orderIdPostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "DELETE", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -60,7 +64,7 @@ open class StoreAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func getInventory(apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: [String: Int]?, _ error: Error?) -> Void)) { + open class func getInventory(apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: [String: Int]?, _ error: Error?) -> Void)) { getInventoryWithRequestBuilder().execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -81,21 +85,21 @@ open class StoreAPI { - returns: RequestBuilder<[String: Int]> */ open class func getInventoryWithRequestBuilder() -> RequestBuilder<[String: Int]> { - let path = "/store/inventory" - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + let localVariablePath = "/store/inventory" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder<[String: Int]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder<[String: Int]>.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -105,7 +109,7 @@ open class StoreAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func getOrderById(orderId: Int64, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Order?, _ error: Error?) -> Void)) { + open class func getOrderById(orderId: Int64, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Order?, _ error: Error?) -> Void)) { getOrderByIdWithRequestBuilder(orderId: orderId).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -124,24 +128,24 @@ open class StoreAPI { - returns: RequestBuilder */ open class func getOrderByIdWithRequestBuilder(orderId: Int64) -> RequestBuilder { - var path = "/store/order/{order_id}" + var localVariablePath = "/store/order/{order_id}" let orderIdPreEscape = "\(APIHelper.mapValueToPathItem(orderId))" let orderIdPostEscape = orderIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" - path = path.replacingOccurrences(of: "{order_id}", with: orderIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + localVariablePath = localVariablePath.replacingOccurrences(of: "{order_id}", with: orderIdPostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -151,7 +155,7 @@ open class StoreAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func placeOrder(body: Order, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Order?, _ error: Error?) -> Void)) { + open class func placeOrder(body: Order, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Order?, _ error: Error?) -> Void)) { placeOrderWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -169,21 +173,20 @@ open class StoreAPI { - returns: RequestBuilder */ open class func placeOrderWithRequestBuilder(body: Order) -> RequestBuilder { - let path = "/store/order" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/store/order" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } - } diff --git a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift index 254474014d3..c1e5691390e 100644 --- a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift +++ b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift @@ -6,8 +6,12 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif open class UserAPI { + /** Create user @@ -15,7 +19,7 @@ open class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func createUser(body: User, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func createUser(body: User, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { createUserWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -34,21 +38,21 @@ open class UserAPI { - returns: RequestBuilder */ open class func createUserWithRequestBuilder(body: User) -> RequestBuilder { - let path = "/user" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/user" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -58,7 +62,7 @@ open class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func createUsersWithArrayInput(body: [User], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func createUsersWithArrayInput(body: [User], apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { createUsersWithArrayInputWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -76,21 +80,21 @@ open class UserAPI { - returns: RequestBuilder */ open class func createUsersWithArrayInputWithRequestBuilder(body: [User]) -> RequestBuilder { - let path = "/user/createWithArray" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/user/createWithArray" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -100,7 +104,7 @@ open class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func createUsersWithListInput(body: [User], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func createUsersWithListInput(body: [User], apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { createUsersWithListInputWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -118,21 +122,21 @@ open class UserAPI { - returns: RequestBuilder */ open class func createUsersWithListInputWithRequestBuilder(body: [User]) -> RequestBuilder { - let path = "/user/createWithList" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/user/createWithList" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -142,7 +146,7 @@ open class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func deleteUser(username: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func deleteUser(username: String, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { deleteUserWithRequestBuilder(username: username).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -161,24 +165,24 @@ open class UserAPI { - returns: RequestBuilder */ open class func deleteUserWithRequestBuilder(username: String) -> RequestBuilder { - var path = "/user/{username}" + var localVariablePath = "/user/{username}" let usernamePreEscape = "\(APIHelper.mapValueToPathItem(username))" let usernamePostEscape = usernamePreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" - path = path.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + localVariablePath = localVariablePath.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "DELETE", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -188,7 +192,7 @@ open class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func getUserByName(username: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: User?, _ error: Error?) -> Void)) { + open class func getUserByName(username: String, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: User?, _ error: Error?) -> Void)) { getUserByNameWithRequestBuilder(username: username).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -206,24 +210,24 @@ open class UserAPI { - returns: RequestBuilder */ open class func getUserByNameWithRequestBuilder(username: String) -> RequestBuilder { - var path = "/user/{username}" + var localVariablePath = "/user/{username}" let usernamePreEscape = "\(APIHelper.mapValueToPathItem(username))" let usernamePostEscape = usernamePreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" - path = path.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + localVariablePath = localVariablePath.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -234,7 +238,7 @@ open class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func loginUser(username: String, password: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: String?, _ error: Error?) -> Void)) { + open class func loginUser(username: String, password: String, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: String?, _ error: Error?) -> Void)) { loginUserWithRequestBuilder(username: username, password: password).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -254,25 +258,25 @@ open class UserAPI { - returns: RequestBuilder */ open class func loginUserWithRequestBuilder(username: String, password: String) -> RequestBuilder { - let path = "/user/login" - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + let localVariablePath = "/user/login" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - var urlComponents = URLComponents(string: URLString) - urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ + var localVariableUrlComponents = URLComponents(string: localVariableURLString) + localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ "username": username.encodeToJSON(), "password": password.encodeToJSON(), ]) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -281,7 +285,7 @@ open class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func logoutUser(apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func logoutUser(apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { logoutUserWithRequestBuilder().execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -298,21 +302,21 @@ open class UserAPI { - returns: RequestBuilder */ open class func logoutUserWithRequestBuilder() -> RequestBuilder { - let path = "/user/logout" - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + let localVariablePath = "/user/logout" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -323,7 +327,7 @@ open class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func updateUser(username: String, body: User, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func updateUser(username: String, body: User, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { updateUserWithRequestBuilder(username: username, body: body).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -343,24 +347,23 @@ open class UserAPI { - returns: RequestBuilder */ open class func updateUserWithRequestBuilder(username: String, body: User) -> RequestBuilder { - var path = "/user/{username}" + var localVariablePath = "/user/{username}" let usernamePreEscape = "\(APIHelper.mapValueToPathItem(username))" let usernamePostEscape = usernamePreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" - path = path.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + localVariablePath = localVariablePath.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "PUT", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } - } diff --git a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Configuration.swift b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Configuration.swift index 18edabbed78..8fb05331889 100644 --- a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Configuration.swift +++ b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Configuration.swift @@ -7,6 +7,7 @@ import Foundation open class Configuration { + // This value is used to configure the date formatter that is used to serialize dates into JSON format. // You must set it prior to encoding any dates, and it will only be read once. @available(*, unavailable, message: "To set a different date format, use CodableHelper.dateFormatter instead.") diff --git a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Extensions.swift b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Extensions.swift index 3aef2d1d6c5..e23035dde30 100644 --- a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Extensions.swift +++ b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Extensions.swift @@ -5,7 +5,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif extension Bool: JSONEncodable { func encodeToJSON() -> Any { return self as Any } @@ -184,44 +186,3 @@ extension HTTPURLResponse { return Array(200 ..< 300).contains(statusCode) } } - -extension AnyCodable: Hashable { - public func hash(into hasher: inout Hasher) { - switch value { - case let value as Bool: - hasher.combine(value) - case let value as Int: - hasher.combine(value) - case let value as Int8: - hasher.combine(value) - case let value as Int16: - hasher.combine(value) - case let value as Int32: - hasher.combine(value) - case let value as Int64: - hasher.combine(value) - case let value as UInt: - hasher.combine(value) - case let value as UInt8: - hasher.combine(value) - case let value as UInt16: - hasher.combine(value) - case let value as UInt32: - hasher.combine(value) - case let value as UInt64: - hasher.combine(value) - case let value as Float: - hasher.combine(value) - case let value as Double: - hasher.combine(value) - case let value as String: - hasher.combine(value) - case let value as [String: AnyCodable]: - hasher.combine(value) - case let value as [AnyCodable]: - hasher.combine(value) - default: - hasher.combine(0) - } - } -} \ No newline at end of file diff --git a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesClass.swift b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesClass.swift index ccdd14f3260..34f35d9b4c9 100644 --- a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesClass.swift +++ b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesClass.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct AdditionalPropertiesClass: Codable, Hashable { @@ -17,6 +19,7 @@ public struct AdditionalPropertiesClass: Codable, Hashable { self.mapString = mapString self.mapMapString = mapMapString } + public enum CodingKeys: String, CodingKey, CaseIterable { case mapString = "map_string" case mapMapString = "map_map_string" @@ -29,7 +32,5 @@ public struct AdditionalPropertiesClass: Codable, Hashable { try container.encodeIfPresent(mapString, forKey: .mapString) try container.encodeIfPresent(mapMapString, forKey: .mapMapString) } - - - } + diff --git a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/Animal.swift b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/Animal.swift index 4efa18dd316..14bb2bd2fe0 100644 --- a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/Animal.swift +++ b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/Animal.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct Animal: Codable, Hashable { @@ -17,6 +19,7 @@ public struct Animal: Codable, Hashable { self.className = className self.color = color } + public enum CodingKeys: String, CodingKey, CaseIterable { case className case color @@ -29,7 +32,5 @@ public struct Animal: Codable, Hashable { try container.encode(className, forKey: .className) try container.encodeIfPresent(color, forKey: .color) } - - - } + diff --git a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/AnimalFarm.swift b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/AnimalFarm.swift index b20b894a1ad..a0b09cb9761 100644 --- a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/AnimalFarm.swift +++ b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/AnimalFarm.swift @@ -6,6 +6,8 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public typealias AnimalFarm = [Animal] diff --git a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift index 72f8703b0f8..acaac402ef4 100644 --- a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift +++ b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct ApiResponse: Codable, Hashable { @@ -19,6 +21,7 @@ public struct ApiResponse: Codable, Hashable { self.type = type self.message = message } + public enum CodingKeys: String, CodingKey, CaseIterable { case code case type @@ -33,7 +36,5 @@ public struct ApiResponse: Codable, Hashable { try container.encodeIfPresent(type, forKey: .type) try container.encodeIfPresent(message, forKey: .message) } - - - } + diff --git a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfArrayOfNumberOnly.swift b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfArrayOfNumberOnly.swift index 0904c469332..d8ef19116b8 100644 --- a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfArrayOfNumberOnly.swift +++ b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfArrayOfNumberOnly.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct ArrayOfArrayOfNumberOnly: Codable, Hashable { @@ -15,6 +17,7 @@ public struct ArrayOfArrayOfNumberOnly: Codable, Hashable { public init(arrayArrayNumber: [[Double]]? = nil) { self.arrayArrayNumber = arrayArrayNumber } + public enum CodingKeys: String, CodingKey, CaseIterable { case arrayArrayNumber = "ArrayArrayNumber" } @@ -25,7 +28,5 @@ public struct ArrayOfArrayOfNumberOnly: Codable, Hashable { var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(arrayArrayNumber, forKey: .arrayArrayNumber) } - - - } + diff --git a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfNumberOnly.swift b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfNumberOnly.swift index e91f2a29097..949077533e9 100644 --- a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfNumberOnly.swift +++ b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfNumberOnly.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct ArrayOfNumberOnly: Codable, Hashable { @@ -15,6 +17,7 @@ public struct ArrayOfNumberOnly: Codable, Hashable { public init(arrayNumber: [Double]? = nil) { self.arrayNumber = arrayNumber } + public enum CodingKeys: String, CodingKey, CaseIterable { case arrayNumber = "ArrayNumber" } @@ -25,7 +28,5 @@ public struct ArrayOfNumberOnly: Codable, Hashable { var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(arrayNumber, forKey: .arrayNumber) } - - - } + diff --git a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/ArrayTest.swift b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/ArrayTest.swift index 5262ce6185f..6135c1556a2 100644 --- a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/ArrayTest.swift +++ b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/ArrayTest.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct ArrayTest: Codable, Hashable { @@ -19,6 +21,7 @@ public struct ArrayTest: Codable, Hashable { self.arrayArrayOfInteger = arrayArrayOfInteger self.arrayArrayOfModel = arrayArrayOfModel } + public enum CodingKeys: String, CodingKey, CaseIterable { case arrayOfString = "array_of_string" case arrayArrayOfInteger = "array_array_of_integer" @@ -33,7 +36,5 @@ public struct ArrayTest: Codable, Hashable { try container.encodeIfPresent(arrayArrayOfInteger, forKey: .arrayArrayOfInteger) try container.encodeIfPresent(arrayArrayOfModel, forKey: .arrayArrayOfModel) } - - - } + diff --git a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/Capitalization.swift b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/Capitalization.swift index 63f53d28293..6353bd4d8a8 100644 --- a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/Capitalization.swift +++ b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/Capitalization.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct Capitalization: Codable, Hashable { @@ -26,6 +28,7 @@ public struct Capitalization: Codable, Hashable { self.sCAETHFlowPoints = sCAETHFlowPoints self.ATT_NAME = ATT_NAME } + public enum CodingKeys: String, CodingKey, CaseIterable { case smallCamel case capitalCamel = "CapitalCamel" @@ -46,7 +49,5 @@ public struct Capitalization: Codable, Hashable { try container.encodeIfPresent(sCAETHFlowPoints, forKey: .sCAETHFlowPoints) try container.encodeIfPresent(ATT_NAME, forKey: .ATT_NAME) } - - - } + diff --git a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/Cat.swift b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/Cat.swift index a74ed96c8cc..834c51d9152 100644 --- a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/Cat.swift +++ b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/Cat.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct Cat: Codable, Hashable { @@ -19,6 +21,7 @@ public struct Cat: Codable, Hashable { self.color = color self.declawed = declawed } + public enum CodingKeys: String, CodingKey, CaseIterable { case className case color @@ -33,7 +36,5 @@ public struct Cat: Codable, Hashable { try container.encodeIfPresent(color, forKey: .color) try container.encodeIfPresent(declawed, forKey: .declawed) } - - - } + diff --git a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/CatAllOf.swift b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/CatAllOf.swift index d6ef582ff64..b227089dc4f 100644 --- a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/CatAllOf.swift +++ b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/CatAllOf.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct CatAllOf: Codable, Hashable { @@ -15,6 +17,7 @@ public struct CatAllOf: Codable, Hashable { public init(declawed: Bool? = nil) { self.declawed = declawed } + public enum CodingKeys: String, CodingKey, CaseIterable { case declawed } @@ -25,7 +28,5 @@ public struct CatAllOf: Codable, Hashable { var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(declawed, forKey: .declawed) } - - - } + diff --git a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/Category.swift b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/Category.swift index 27c46ebc1ce..1413c58141e 100644 --- a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/Category.swift +++ b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/Category.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct Category: Codable, Hashable { @@ -17,6 +19,7 @@ public struct Category: Codable, Hashable { self.id = id self.name = name } + public enum CodingKeys: String, CodingKey, CaseIterable { case id case name @@ -29,7 +32,5 @@ public struct Category: Codable, Hashable { try container.encodeIfPresent(id, forKey: .id) try container.encode(name, forKey: .name) } - - - } + diff --git a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/ClassModel.swift b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/ClassModel.swift index e5e78f49084..73b8414f342 100644 --- a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/ClassModel.swift +++ b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/ClassModel.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif /** Model for testing model with \"_class\" property */ public struct ClassModel: Codable, Hashable { @@ -16,6 +18,7 @@ public struct ClassModel: Codable, Hashable { public init(_class: String? = nil) { self._class = _class } + public enum CodingKeys: String, CodingKey, CaseIterable { case _class } @@ -26,7 +29,5 @@ public struct ClassModel: Codable, Hashable { var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(_class, forKey: ._class) } - - - } + diff --git a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/Client.swift b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/Client.swift index 7553011dbf3..364b58f1c4e 100644 --- a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/Client.swift +++ b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/Client.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct Client: Codable, Hashable { @@ -15,6 +17,7 @@ public struct Client: Codable, Hashable { public init(client: String? = nil) { self.client = client } + public enum CodingKeys: String, CodingKey, CaseIterable { case client } @@ -25,7 +28,5 @@ public struct Client: Codable, Hashable { var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(client, forKey: .client) } - - - } + diff --git a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/Dog.swift b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/Dog.swift index c458bc06ab0..849fbfed745 100644 --- a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/Dog.swift +++ b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/Dog.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct Dog: Codable, Hashable { @@ -19,6 +21,7 @@ public struct Dog: Codable, Hashable { self.color = color self.breed = breed } + public enum CodingKeys: String, CodingKey, CaseIterable { case className case color @@ -33,7 +36,5 @@ public struct Dog: Codable, Hashable { try container.encodeIfPresent(color, forKey: .color) try container.encodeIfPresent(breed, forKey: .breed) } - - - } + diff --git a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/DogAllOf.swift b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/DogAllOf.swift index 6e165285668..527edd845c4 100644 --- a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/DogAllOf.swift +++ b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/DogAllOf.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct DogAllOf: Codable, Hashable { @@ -15,6 +17,7 @@ public struct DogAllOf: Codable, Hashable { public init(breed: String? = nil) { self.breed = breed } + public enum CodingKeys: String, CodingKey, CaseIterable { case breed } @@ -25,7 +28,5 @@ public struct DogAllOf: Codable, Hashable { var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(breed, forKey: .breed) } - - - } + diff --git a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/EnumArrays.swift b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/EnumArrays.swift index 4850d7bbe5a..1a79ffe95b1 100644 --- a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/EnumArrays.swift +++ b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/EnumArrays.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct EnumArrays: Codable, Hashable { @@ -25,6 +27,7 @@ public struct EnumArrays: Codable, Hashable { self.justSymbol = justSymbol self.arrayEnum = arrayEnum } + public enum CodingKeys: String, CodingKey, CaseIterable { case justSymbol = "just_symbol" case arrayEnum = "array_enum" @@ -37,7 +40,5 @@ public struct EnumArrays: Codable, Hashable { try container.encodeIfPresent(justSymbol, forKey: .justSymbol) try container.encodeIfPresent(arrayEnum, forKey: .arrayEnum) } - - - } + diff --git a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/EnumClass.swift b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/EnumClass.swift index ab01cf297f8..6ea2895aee5 100644 --- a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/EnumClass.swift +++ b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/EnumClass.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public enum EnumClass: String, Codable, CaseIterable { case abc = "_abc" diff --git a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/EnumTest.swift b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/EnumTest.swift index ec8c5ff72bc..c097933904b 100644 --- a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/EnumTest.swift +++ b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/EnumTest.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct EnumTest: Codable, Hashable { @@ -41,6 +43,7 @@ public struct EnumTest: Codable, Hashable { self.enumNumber = enumNumber self.outerEnum = outerEnum } + public enum CodingKeys: String, CodingKey, CaseIterable { case enumString = "enum_string" case enumStringRequired = "enum_string_required" @@ -59,7 +62,5 @@ public struct EnumTest: Codable, Hashable { try container.encodeIfPresent(enumNumber, forKey: .enumNumber) try container.encodeIfPresent(outerEnum, forKey: .outerEnum) } - - - } + diff --git a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/File.swift b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/File.swift index bfe11105fc6..c5ebbaf2f4f 100644 --- a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/File.swift +++ b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/File.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif /** Must be named `File` for test. */ public struct File: Codable, Hashable { @@ -17,6 +19,7 @@ public struct File: Codable, Hashable { public init(sourceURI: String? = nil) { self.sourceURI = sourceURI } + public enum CodingKeys: String, CodingKey, CaseIterable { case sourceURI } @@ -27,7 +30,5 @@ public struct File: Codable, Hashable { var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(sourceURI, forKey: .sourceURI) } - - - } + diff --git a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/FileSchemaTestClass.swift b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/FileSchemaTestClass.swift index dd837236657..c04b1dccf76 100644 --- a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/FileSchemaTestClass.swift +++ b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/FileSchemaTestClass.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct FileSchemaTestClass: Codable, Hashable { @@ -17,6 +19,7 @@ public struct FileSchemaTestClass: Codable, Hashable { self.file = file self.files = files } + public enum CodingKeys: String, CodingKey, CaseIterable { case file case files @@ -29,7 +32,5 @@ public struct FileSchemaTestClass: Codable, Hashable { try container.encodeIfPresent(file, forKey: .file) try container.encodeIfPresent(files, forKey: .files) } - - - } + diff --git a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/FormatTest.swift b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/FormatTest.swift index 078c2c4a08c..65bb0ca0842 100644 --- a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/FormatTest.swift +++ b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/FormatTest.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct FormatTest: Codable, Hashable { @@ -39,6 +41,7 @@ public struct FormatTest: Codable, Hashable { self.uuid = uuid self.password = password } + public enum CodingKeys: String, CodingKey, CaseIterable { case integer case int32 @@ -73,7 +76,5 @@ public struct FormatTest: Codable, Hashable { try container.encodeIfPresent(uuid, forKey: .uuid) try container.encode(password, forKey: .password) } - - - } + diff --git a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/HasOnlyReadOnly.swift b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/HasOnlyReadOnly.swift index cddd61da5f7..e8216047d6e 100644 --- a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/HasOnlyReadOnly.swift +++ b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/HasOnlyReadOnly.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct HasOnlyReadOnly: Codable, Hashable { @@ -17,6 +19,7 @@ public struct HasOnlyReadOnly: Codable, Hashable { self.bar = bar self.foo = foo } + public enum CodingKeys: String, CodingKey, CaseIterable { case bar case foo @@ -29,7 +32,5 @@ public struct HasOnlyReadOnly: Codable, Hashable { try container.encodeIfPresent(bar, forKey: .bar) try container.encodeIfPresent(foo, forKey: .foo) } - - - } + diff --git a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/List.swift b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/List.swift index b03a8bd8cfd..1269b40251d 100644 --- a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/List.swift +++ b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/List.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct List: Codable, Hashable { @@ -15,6 +17,7 @@ public struct List: Codable, Hashable { public init(_123list: String? = nil) { self._123list = _123list } + public enum CodingKeys: String, CodingKey, CaseIterable { case _123list = "123-list" } @@ -25,7 +28,5 @@ public struct List: Codable, Hashable { var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(_123list, forKey: ._123list) } - - - } + diff --git a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/MapTest.swift b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/MapTest.swift index db5928bc97e..19f258d2929 100644 --- a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/MapTest.swift +++ b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/MapTest.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct MapTest: Codable, Hashable { @@ -25,6 +27,7 @@ public struct MapTest: Codable, Hashable { self.directMap = directMap self.indirectMap = indirectMap } + public enum CodingKeys: String, CodingKey, CaseIterable { case mapMapOfString = "map_map_of_string" case mapOfEnumString = "map_of_enum_string" @@ -41,7 +44,5 @@ public struct MapTest: Codable, Hashable { try container.encodeIfPresent(directMap, forKey: .directMap) try container.encodeIfPresent(indirectMap, forKey: .indirectMap) } - - - } + diff --git a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/MixedPropertiesAndAdditionalPropertiesClass.swift b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/MixedPropertiesAndAdditionalPropertiesClass.swift index cd1c8eb22c0..2dd49ab0212 100644 --- a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/MixedPropertiesAndAdditionalPropertiesClass.swift +++ b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/MixedPropertiesAndAdditionalPropertiesClass.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct MixedPropertiesAndAdditionalPropertiesClass: Codable, Hashable { @@ -19,6 +21,7 @@ public struct MixedPropertiesAndAdditionalPropertiesClass: Codable, Hashable { self.dateTime = dateTime self.map = map } + public enum CodingKeys: String, CodingKey, CaseIterable { case uuid case dateTime @@ -33,7 +36,5 @@ public struct MixedPropertiesAndAdditionalPropertiesClass: Codable, Hashable { try container.encodeIfPresent(dateTime, forKey: .dateTime) try container.encodeIfPresent(map, forKey: .map) } - - - } + diff --git a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/Model200Response.swift b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/Model200Response.swift index 070ed68254b..9080e5c382f 100644 --- a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/Model200Response.swift +++ b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/Model200Response.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif /** Model for testing model name starting with number */ public struct Model200Response: Codable, Hashable { @@ -18,6 +20,7 @@ public struct Model200Response: Codable, Hashable { self.name = name self._class = _class } + public enum CodingKeys: String, CodingKey, CaseIterable { case name case _class = "class" @@ -30,7 +33,5 @@ public struct Model200Response: Codable, Hashable { try container.encodeIfPresent(name, forKey: .name) try container.encodeIfPresent(_class, forKey: ._class) } - - - } + diff --git a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/Name.swift b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/Name.swift index c90f8deb556..0280404c044 100644 --- a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/Name.swift +++ b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/Name.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif /** Model for testing model name same as property name */ public struct Name: Codable, Hashable { @@ -22,6 +24,7 @@ public struct Name: Codable, Hashable { self.property = property self._123number = _123number } + public enum CodingKeys: String, CodingKey, CaseIterable { case name case snakeCase = "snake_case" @@ -38,7 +41,5 @@ public struct Name: Codable, Hashable { try container.encodeIfPresent(property, forKey: .property) try container.encodeIfPresent(_123number, forKey: ._123number) } - - - } + diff --git a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/NumberOnly.swift b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/NumberOnly.swift index 32a62548302..36be35a0533 100644 --- a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/NumberOnly.swift +++ b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/NumberOnly.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct NumberOnly: Codable, Hashable { @@ -15,6 +17,7 @@ public struct NumberOnly: Codable, Hashable { public init(justNumber: Double? = nil) { self.justNumber = justNumber } + public enum CodingKeys: String, CodingKey, CaseIterable { case justNumber = "JustNumber" } @@ -25,7 +28,5 @@ public struct NumberOnly: Codable, Hashable { var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(justNumber, forKey: .justNumber) } - - - } + diff --git a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/Order.swift b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/Order.swift index cf5160c930d..bda67408a9d 100644 --- a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/Order.swift +++ b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/Order.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct Order: Codable, Hashable { @@ -31,6 +33,7 @@ public struct Order: Codable, Hashable { self.status = status self.complete = complete } + public enum CodingKeys: String, CodingKey, CaseIterable { case id case petId @@ -51,7 +54,5 @@ public struct Order: Codable, Hashable { try container.encodeIfPresent(status, forKey: .status) try container.encodeIfPresent(complete, forKey: .complete) } - - - } + diff --git a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/OuterComposite.swift b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/OuterComposite.swift index 72a76adba29..d8e7469f99a 100644 --- a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/OuterComposite.swift +++ b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/OuterComposite.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct OuterComposite: Codable, Hashable { @@ -19,6 +21,7 @@ public struct OuterComposite: Codable, Hashable { self.myString = myString self.myBoolean = myBoolean } + public enum CodingKeys: String, CodingKey, CaseIterable { case myNumber = "my_number" case myString = "my_string" @@ -33,7 +36,5 @@ public struct OuterComposite: Codable, Hashable { try container.encodeIfPresent(myString, forKey: .myString) try container.encodeIfPresent(myBoolean, forKey: .myBoolean) } - - - } + diff --git a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/OuterEnum.swift b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/OuterEnum.swift index 9bd6f3bef8f..76c34b3c2ce 100644 --- a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/OuterEnum.swift +++ b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/OuterEnum.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public enum OuterEnum: String, Codable, CaseIterable { case placed = "placed" diff --git a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/Pet.swift b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/Pet.swift index d4753402759..f4f7928e77e 100644 --- a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/Pet.swift +++ b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/Pet.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct Pet: Codable, Hashable { @@ -31,6 +33,7 @@ public struct Pet: Codable, Hashable { self.tags = tags self.status = status } + public enum CodingKeys: String, CodingKey, CaseIterable { case id case category @@ -51,7 +54,5 @@ public struct Pet: Codable, Hashable { try container.encodeIfPresent(tags, forKey: .tags) try container.encodeIfPresent(status, forKey: .status) } - - - } + diff --git a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/ReadOnlyFirst.swift b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/ReadOnlyFirst.swift index 6f285eef8a0..6b80302150a 100644 --- a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/ReadOnlyFirst.swift +++ b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/ReadOnlyFirst.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct ReadOnlyFirst: Codable, Hashable { @@ -17,6 +19,7 @@ public struct ReadOnlyFirst: Codable, Hashable { self.bar = bar self.baz = baz } + public enum CodingKeys: String, CodingKey, CaseIterable { case bar case baz @@ -29,7 +32,5 @@ public struct ReadOnlyFirst: Codable, Hashable { try container.encodeIfPresent(bar, forKey: .bar) try container.encodeIfPresent(baz, forKey: .baz) } - - - } + diff --git a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/Return.swift b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/Return.swift index 2c791780b41..ca4883d9251 100644 --- a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/Return.swift +++ b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/Return.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif /** Model for testing reserved words */ public struct Return: Codable, Hashable { @@ -16,6 +18,7 @@ public struct Return: Codable, Hashable { public init(_return: Int? = nil) { self._return = _return } + public enum CodingKeys: String, CodingKey, CaseIterable { case _return = "return" } @@ -26,7 +29,5 @@ public struct Return: Codable, Hashable { var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(_return, forKey: ._return) } - - - } + diff --git a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/SpecialModelName.swift b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/SpecialModelName.swift index baf14720175..66b8f4d69ff 100644 --- a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/SpecialModelName.swift +++ b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/SpecialModelName.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct SpecialModelName: Codable, Hashable { @@ -15,6 +17,7 @@ public struct SpecialModelName: Codable, Hashable { public init(specialPropertyName: Int64? = nil) { self.specialPropertyName = specialPropertyName } + public enum CodingKeys: String, CodingKey, CaseIterable { case specialPropertyName = "$special[property.name]" } @@ -25,7 +28,5 @@ public struct SpecialModelName: Codable, Hashable { var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(specialPropertyName, forKey: .specialPropertyName) } - - - } + diff --git a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/StringBooleanMap.swift b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/StringBooleanMap.swift index 0b671fe0ad3..11a5a854895 100644 --- a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/StringBooleanMap.swift +++ b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/StringBooleanMap.swift @@ -6,12 +6,16 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct StringBooleanMap: Codable, Hashable { + public enum CodingKeys: CodingKey, CaseIterable { } + public private(set) var additionalProperties: [String: Bool] = [:] public subscript(key: String) -> Bool? { @@ -38,11 +42,11 @@ public struct StringBooleanMap: Codable, Hashable { // Decodable protocol methods public init(from decoder: Decoder) throws { - let container = try decoder.container(keyedBy: String.self) + let container = try decoder.container(keyedBy: CodingKeys.self) var nonAdditionalPropertyKeys = Set() - additionalProperties = try container.decodeMap(Bool.self, excludedKeys: nonAdditionalPropertyKeys) + let additionalPropertiesContainer = try decoder.container(keyedBy: String.self) + additionalProperties = try additionalPropertiesContainer.decodeMap(Bool.self, excludedKeys: nonAdditionalPropertyKeys) } - - } + diff --git a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift index 76fdd4a783d..2af3e2f0698 100644 --- a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift +++ b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct Tag: Codable, Hashable { @@ -17,6 +19,7 @@ public struct Tag: Codable, Hashable { self.id = id self.name = name } + public enum CodingKeys: String, CodingKey, CaseIterable { case id case name @@ -29,7 +32,5 @@ public struct Tag: Codable, Hashable { try container.encodeIfPresent(id, forKey: .id) try container.encodeIfPresent(name, forKey: .name) } - - - } + diff --git a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderDefault.swift b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderDefault.swift index d518a528ba7..125a63b0ed3 100644 --- a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderDefault.swift +++ b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderDefault.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct TypeHolderDefault: Codable, Hashable { @@ -23,6 +25,7 @@ public struct TypeHolderDefault: Codable, Hashable { self.boolItem = boolItem self.arrayItem = arrayItem } + public enum CodingKeys: String, CodingKey, CaseIterable { case stringItem = "string_item" case numberItem = "number_item" @@ -41,7 +44,5 @@ public struct TypeHolderDefault: Codable, Hashable { try container.encode(boolItem, forKey: .boolItem) try container.encode(arrayItem, forKey: .arrayItem) } - - - } + diff --git a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderExample.swift b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderExample.swift index 07ec715e38a..3aa1851a585 100644 --- a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderExample.swift +++ b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderExample.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct TypeHolderExample: Codable, Hashable { @@ -23,6 +25,7 @@ public struct TypeHolderExample: Codable, Hashable { self.boolItem = boolItem self.arrayItem = arrayItem } + public enum CodingKeys: String, CodingKey, CaseIterable { case stringItem = "string_item" case numberItem = "number_item" @@ -41,7 +44,5 @@ public struct TypeHolderExample: Codable, Hashable { try container.encode(boolItem, forKey: .boolItem) try container.encode(arrayItem, forKey: .arrayItem) } - - - } + diff --git a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/User.swift b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/User.swift index f9a7b1e36e3..4af156b9bac 100644 --- a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/User.swift +++ b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models/User.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct User: Codable, Hashable { @@ -30,6 +32,7 @@ public struct User: Codable, Hashable { self.phone = phone self.userStatus = userStatus } + public enum CodingKeys: String, CodingKey, CaseIterable { case id case username @@ -54,7 +57,5 @@ public struct User: Codable, Hashable { try container.encodeIfPresent(phone, forKey: .phone) try container.encodeIfPresent(userStatus, forKey: .userStatus) } - - - } + 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 52b2071ec1a..41959190a26 100644 --- a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift +++ b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift @@ -93,14 +93,14 @@ open class URLSessionRequestBuilder: RequestBuilder { return modifiedRequest } - override open func execute(_ apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, _ completion: @escaping (_ result: Swift.Result, Error>) -> Void) { + override open func execute(_ apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, _ completion: @escaping (_ result: Swift.Result, Error>) -> Void) { let urlSessionId = UUID().uuidString // Create a new manager for each request to customize its request header let urlSession = createURLSession() urlSessionStore[urlSessionId] = urlSession guard let xMethod = HTTPMethod(rawValue: method) else { - fatalError("Unsuported Http method - \(method)") + fatalError("Unsupported Http method - \(method)") } let encoding: ParameterEncoding @@ -119,7 +119,7 @@ open class URLSessionRequestBuilder: RequestBuilder { } else if contentType == "application/x-www-form-urlencoded" { encoding = FormURLEncoding() } else { - fatalError("Unsuported Media Type - \(contentType)") + fatalError("Unsupported Media Type - \(contentType)") } } @@ -205,16 +205,18 @@ open class URLSessionRequestBuilder: RequestBuilder { } let fileManager = FileManager.default - let documentsDirectory = fileManager.urls(for: .documentDirectory, in: .userDomainMask)[0] + let cachesDirectory = fileManager.urls(for: .cachesDirectory, in: .userDomainMask)[0] let requestURL = try getURL(from: urlRequest) var requestPath = try getPath(from: requestURL) if let headerFileName = getFileName(fromContentDisposition: httpResponse.allHeaderFields["Content-Disposition"] as? String) { requestPath = requestPath.appending("/\(headerFileName)") + } else { + requestPath = requestPath.appending("/tmp.PetstoreClient.\(UUID().uuidString)") } - let filePath = documentsDirectory.appendingPathComponent(requestPath) + let filePath = cachesDirectory.appendingPathComponent(requestPath) let directoryPath = filePath.deletingLastPathComponent().path try fileManager.createDirectory(atPath: directoryPath, withIntermediateDirectories: true, attributes: nil) @@ -232,6 +234,10 @@ open class URLSessionRequestBuilder: RequestBuilder { completion(.success(Response(response: httpResponse, body: nil))) + case is Data.Type: + + completion(.success(Response(response: httpResponse, body: data as? T))) + default: completion(.success(Response(response: httpResponse, body: data as? T))) @@ -244,7 +250,7 @@ open class URLSessionRequestBuilder: RequestBuilder { for (key, value) in headers { httpHeaders[key] = value } - for (key, value) in PetstoreClientAPI.customHeaders { + for (key, value) in PetstoreClient.customHeaders { httpHeaders[key] = value } return httpHeaders @@ -328,6 +334,43 @@ open class URLSessionDecodableRequestBuilder: URLSessionRequestBui completion(.success(Response(response: httpResponse, body: body as? T))) + case is URL.Type: + do { + + guard error == nil else { + throw DownloadException.responseFailed + } + + guard let data = data else { + throw DownloadException.responseDataMissing + } + + let fileManager = FileManager.default + let cachesDirectory = fileManager.urls(for: .cachesDirectory, in: .userDomainMask)[0] + let requestURL = try getURL(from: urlRequest) + + var requestPath = try getPath(from: requestURL) + + if let headerFileName = getFileName(fromContentDisposition: httpResponse.allHeaderFields["Content-Disposition"] as? String) { + requestPath = requestPath.appending("/\(headerFileName)") + } else { + requestPath = requestPath.appending("/tmp.PetstoreClient.\(UUID().uuidString)") + } + + let filePath = cachesDirectory.appendingPathComponent(requestPath) + let directoryPath = filePath.deletingLastPathComponent().path + + try fileManager.createDirectory(atPath: directoryPath, withIntermediateDirectories: true, attributes: nil) + try data.write(to: filePath, options: .atomic) + + completion(.success(Response(response: httpResponse, body: filePath as? T))) + + } catch let requestParserError as DownloadException { + completion(.failure(ErrorResponse.error(400, data, response, requestParserError))) + } catch { + completion(.failure(ErrorResponse.error(400, data, response, error))) + } + case is Void.Type: completion(.success(Response(response: httpResponse, body: nil))) diff --git a/samples/client/petstore/swift5/readonlyProperties/docs/FakeAPI.md b/samples/client/petstore/swift5/readonlyProperties/docs/FakeAPI.md index 543869c0d2e..553a46281aa 100644 --- a/samples/client/petstore/swift5/readonlyProperties/docs/FakeAPI.md +++ b/samples/client/petstore/swift5/readonlyProperties/docs/FakeAPI.md @@ -379,7 +379,7 @@ import PetstoreClient let number = 987 // Double | None let double = 987 // Double | None let patternWithoutDelimiter = "patternWithoutDelimiter_example" // String | None -let byte = 987 // Data | None +let byte = Data([9, 8, 7]) // Data | None let integer = 987 // Int | None (optional) let int32 = 987 // Int | None (optional) let int64 = 987 // Int64 | None (optional) diff --git a/samples/client/petstore/swift5/readonlyProperties/pom.xml b/samples/client/petstore/swift5/readonlyProperties/pom.xml new file mode 100644 index 00000000000..c1b201eb3b4 --- /dev/null +++ b/samples/client/petstore/swift5/readonlyProperties/pom.xml @@ -0,0 +1,43 @@ + + 4.0.0 + io.swagger + Swift5PetstoreClientTests + pom + 1.0-SNAPSHOT + Swift5 Swagger Petstore Client + + + + maven-dependency-plugin + + + package + + copy-dependencies + + + ${project.build.directory} + + + + + + org.codehaus.mojo + exec-maven-plugin + 1.2.1 + + + xcodebuild-test + integration-test + + exec + + + ./run_spmbuild.sh + + + + + + + diff --git a/samples/client/petstore/swift5/readonlyProperties/project.yml b/samples/client/petstore/swift5/readonlyProperties/project.yml index 5528eeee513..0493cf65896 100644 --- a/samples/client/petstore/swift5/readonlyProperties/project.yml +++ b/samples/client/petstore/swift5/readonlyProperties/project.yml @@ -11,5 +11,5 @@ targets: settings: APPLICATION_EXTENSION_API_ONLY: true scheme: {} - + dependencies: - carthage: AnyCodable diff --git a/samples/client/petstore/swift5/readonlyProperties/run_spmbuild.sh b/samples/client/petstore/swift5/readonlyProperties/run_spmbuild.sh new file mode 100755 index 00000000000..1a9f585ad05 --- /dev/null +++ b/samples/client/petstore/swift5/readonlyProperties/run_spmbuild.sh @@ -0,0 +1,3 @@ +#!/bin/sh + +swift build && exit ${PIPESTATUS[0]} diff --git a/samples/client/petstore/swift5/resultLibrary/.gitignore b/samples/client/petstore/swift5/resultLibrary/.gitignore index 5e5d5cebcf4..627d360a903 100644 --- a/samples/client/petstore/swift5/resultLibrary/.gitignore +++ b/samples/client/petstore/swift5/resultLibrary/.gitignore @@ -1,12 +1,22 @@ +# Created by https://www.toptal.com/developers/gitignore/api/swift,xcode +# Edit at https://www.toptal.com/developers/gitignore?templates=swift,xcode + +### Swift ### # Xcode # # gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore -## Build generated -build/ -DerivedData +## User settings +xcuserdata/ -## Various settings +## compatibility with Xcode 8 and earlier (ignoring not required starting Xcode 9) +*.xcscmblueprint +*.xccheckout + +## compatibility with Xcode 3 and earlier (ignoring not required starting Xcode 4) +build/ +DerivedData/ +*.moved-aside *.pbxuser !default.pbxuser *.mode1v3 @@ -15,49 +25,81 @@ DerivedData !default.mode2v3 *.perspectivev3 !default.perspectivev3 -xcuserdata - -## Other -*.xccheckout -*.moved-aside -*.xcuserstate -*.xcscmblueprint ## Obj-C/Swift specific *.hmap + +## App packaging *.ipa +*.dSYM.zip +*.dSYM ## Playgrounds timeline.xctimeline playground.xcworkspace # Swift Package Manager -# # Add this line if you want to avoid checking in source code from Swift Package Manager dependencies. # Packages/ +# Package.pins +# Package.resolved +# *.xcodeproj +# Xcode automatically generates this directory with a .xcworkspacedata file and xcuserdata +# hence it is not needed unless you have added a package configuration file to your project +# .swiftpm + .build/ # CocoaPods -# # We recommend against adding the Pods directory to your .gitignore. However # you should judge for yourself, the pros and cons are mentioned at: # https://guides.cocoapods.org/using/using-cocoapods.html#should-i-check-the-pods-directory-into-source-control -# # Pods/ +# Add this line if you want to avoid checking in source code from the Xcode workspace +# *.xcworkspace # Carthage -# # Add this line if you want to avoid checking in source code from Carthage dependencies. # Carthage/Checkouts -Carthage/Build +Carthage/Build/ + +# Add this lines if you are using Accio dependency management (Deprecated since Xcode 12) +# Dependencies/ +# .accio/ # fastlane -# -# It is recommended to not store the screenshots in the git repo. Instead, use fastlane to re-generate the -# screenshots whenever they are needed. +# It is recommended to not store the screenshots in the git repo. +# Instead, use fastlane to re-generate the screenshots whenever they are needed. # For more information about the recommended setup visit: -# https://github.com/fastlane/fastlane/blob/master/docs/Gitignore.md +# https://docs.fastlane.tools/best-practices/source-control/#source-control fastlane/report.xml -fastlane/screenshots +fastlane/Preview.html +fastlane/screenshots/**/*.png +fastlane/test_output + +# Code Injection +# After new code Injection tools there's a generated folder /iOSInjectionProject +# https://github.com/johnno1962/injectionforxcode + +iOSInjectionProject/ + +### Xcode ### +# Xcode +# gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore + + + + +## Gcc Patch +/*.gcno + +### Xcode Patch ### +*.xcodeproj/* +!*.xcodeproj/project.pbxproj +!*.xcodeproj/xcshareddata/ +!*.xcworkspace/contents.xcworkspacedata +**/xcshareddata/WorkspaceSettings.xcsettings + +# End of https://www.toptal.com/developers/gitignore/api/swift,xcode diff --git a/samples/client/petstore/swift5/resultLibrary/.openapi-generator/VERSION b/samples/client/petstore/swift5/resultLibrary/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/client/petstore/swift5/resultLibrary/.openapi-generator/VERSION +++ b/samples/client/petstore/swift5/resultLibrary/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/client/petstore/swift5/resultLibrary/Cartfile b/samples/client/petstore/swift5/resultLibrary/Cartfile index 84aaa61ef2d..a6a6bcacb1d 100644 --- a/samples/client/petstore/swift5/resultLibrary/Cartfile +++ b/samples/client/petstore/swift5/resultLibrary/Cartfile @@ -1,2 +1,2 @@ -github "Flight-School/AnyCodable" ~> 0.4.0 +github "Flight-School/AnyCodable" ~> 0.6.1 diff --git a/samples/client/petstore/swift5/resultLibrary/Package.resolved b/samples/client/petstore/swift5/resultLibrary/Package.resolved new file mode 100644 index 00000000000..79610c3b3b3 --- /dev/null +++ b/samples/client/petstore/swift5/resultLibrary/Package.resolved @@ -0,0 +1,16 @@ +{ + "object": { + "pins": [ + { + "package": "AnyCodable", + "repositoryURL": "https://github.com/Flight-School/AnyCodable", + "state": { + "branch": null, + "revision": "69261f239f0fffaf51495dadc4f8483fbfe97025", + "version": "0.6.1" + } + } + ] + }, + "version": 1 +} diff --git a/samples/client/petstore/swift5/resultLibrary/Package.swift b/samples/client/petstore/swift5/resultLibrary/Package.swift index b724838fe8d..87bb775fb72 100644 --- a/samples/client/petstore/swift5/resultLibrary/Package.swift +++ b/samples/client/petstore/swift5/resultLibrary/Package.swift @@ -19,7 +19,7 @@ let package = Package( ], dependencies: [ // Dependencies declare other packages that this package depends on. - .package(url: "https://github.com/Flight-School/AnyCodable", .exact("0.4.0")), + .package(url: "https://github.com/Flight-School/AnyCodable", from: "0.6.1"), ], targets: [ // Targets are the basic building blocks of a package. A target can define a module or a test suite. diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient.podspec b/samples/client/petstore/swift5/resultLibrary/PetstoreClient.podspec index de06558efbd..0e6bf7ec024 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient.podspec +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient.podspec @@ -11,5 +11,5 @@ Pod::Spec.new do |s| s.homepage = 'https://github.com/openapitools/openapi-generator' s.summary = 'PetstoreClient' s.source_files = 'PetstoreClient/Classes/**/*.swift' - s.dependency 'AnyCodable-FlightSchool', '~> 0.4.0' + s.dependency 'AnyCodable-FlightSchool', '~> 0.6.1' end diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs.swift b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs.swift index dbdab491ff7..941c61b713a 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs.swift @@ -6,10 +6,13 @@ import Foundation -open class PetstoreClientAPI { +@available(*, deprecated, renamed: "PetstoreClient") +public typealias PetstoreClientAPI = PetstoreClient + +open class PetstoreClient { public static var basePath = "http://petstore.swagger.io:80/v2" - public static var credential: URLCredential? public static var customHeaders: [String: String] = [:] + public static var credential: URLCredential? public static var requestBuilderFactory: RequestBuilderFactory = URLSessionRequestBuilderFactory() public static var apiResponseQueue: DispatchQueue = .main } @@ -32,7 +35,7 @@ open class RequestBuilder { self.parameters = parameters self.headers = headers - addHeaders(PetstoreClientAPI.customHeaders) + addHeaders(PetstoreClient.customHeaders) } open func addHeaders(_ aHeaders: [String: String]) { @@ -41,7 +44,7 @@ open class RequestBuilder { } } - open func execute(_ apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, _ completion: @escaping (_ result: Swift.Result, Error>) -> Void) { } + open func execute(_ apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, _ completion: @escaping (_ result: Swift.Result, Error>) -> Void) { } public func addHeader(name: String, value: String) -> Self { if !value.isEmpty { @@ -51,7 +54,7 @@ open class RequestBuilder { } open func addCredential() -> Self { - credential = PetstoreClientAPI.credential + credential = PetstoreClient.credential return self } } 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 19521eb4d65..7c3818d8baa 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 @@ -6,8 +6,12 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif open class AnotherFakeAPI { + /** To test special tags @@ -15,7 +19,7 @@ open class AnotherFakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the result */ - open class func call123testSpecialTags(body: Client, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ result: Swift.Result) -> Void)) { + open class func call123testSpecialTags(body: Client, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ result: Swift.Result) -> Void)) { call123testSpecialTagsWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -34,21 +38,20 @@ open class AnotherFakeAPI { - returns: RequestBuilder */ open class func call123testSpecialTagsWithRequestBuilder(body: Client) -> RequestBuilder { - let path = "/another-fake/dummy" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/another-fake/dummy" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "PATCH", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "PATCH", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } - } 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 a1eb0539707..42e94e88222 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 @@ -6,15 +6,19 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif open class FakeAPI { + /** - parameter body: (body) Input boolean as post body (optional) - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the result */ - open class func fakeOuterBooleanSerialize(body: Bool? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ result: Swift.Result) -> Void)) { + open class func fakeOuterBooleanSerialize(body: Bool? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ result: Swift.Result) -> Void)) { fakeOuterBooleanSerializeWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -32,21 +36,21 @@ open class FakeAPI { - returns: RequestBuilder */ open class func fakeOuterBooleanSerializeWithRequestBuilder(body: Bool? = nil) -> RequestBuilder { - let path = "/fake/outer/boolean" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/fake/outer/boolean" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -55,7 +59,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the result */ - open class func fakeOuterCompositeSerialize(body: OuterComposite? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ result: Swift.Result) -> Void)) { + open class func fakeOuterCompositeSerialize(body: OuterComposite? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ result: Swift.Result) -> Void)) { fakeOuterCompositeSerializeWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -73,21 +77,21 @@ open class FakeAPI { - returns: RequestBuilder */ open class func fakeOuterCompositeSerializeWithRequestBuilder(body: OuterComposite? = nil) -> RequestBuilder { - let path = "/fake/outer/composite" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/fake/outer/composite" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -96,7 +100,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the result */ - open class func fakeOuterNumberSerialize(body: Double? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ result: Swift.Result) -> Void)) { + open class func fakeOuterNumberSerialize(body: Double? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ result: Swift.Result) -> Void)) { fakeOuterNumberSerializeWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -114,21 +118,21 @@ open class FakeAPI { - returns: RequestBuilder */ open class func fakeOuterNumberSerializeWithRequestBuilder(body: Double? = nil) -> RequestBuilder { - let path = "/fake/outer/number" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/fake/outer/number" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -137,7 +141,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the result */ - open class func fakeOuterStringSerialize(body: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ result: Swift.Result) -> Void)) { + open class func fakeOuterStringSerialize(body: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ result: Swift.Result) -> Void)) { fakeOuterStringSerializeWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -155,21 +159,21 @@ open class FakeAPI { - returns: RequestBuilder */ open class func fakeOuterStringSerializeWithRequestBuilder(body: String? = nil) -> RequestBuilder { - let path = "/fake/outer/string" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/fake/outer/string" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -178,7 +182,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the result */ - open class func testBodyWithFileSchema(body: FileSchemaTestClass, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ result: Swift.Result) -> Void)) { + open class func testBodyWithFileSchema(body: FileSchemaTestClass, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ result: Swift.Result) -> Void)) { testBodyWithFileSchemaWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -196,21 +200,21 @@ open class FakeAPI { - returns: RequestBuilder */ open class func testBodyWithFileSchemaWithRequestBuilder(body: FileSchemaTestClass) -> RequestBuilder { - let path = "/fake/body-with-file-schema" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/fake/body-with-file-schema" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "PUT", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -220,7 +224,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the result */ - open class func testBodyWithQueryParams(query: String, body: User, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ result: Swift.Result) -> Void)) { + open class func testBodyWithQueryParams(query: String, body: User, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ result: Swift.Result) -> Void)) { testBodyWithQueryParamsWithRequestBuilder(query: query, body: body).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -238,24 +242,24 @@ open class FakeAPI { - returns: RequestBuilder */ open class func testBodyWithQueryParamsWithRequestBuilder(query: String, body: User) -> RequestBuilder { - let path = "/fake/body-with-query-params" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/fake/body-with-query-params" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - var urlComponents = URLComponents(string: URLString) - urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ + var localVariableUrlComponents = URLComponents(string: localVariableURLString) + localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ "query": query.encodeToJSON(), ]) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "PUT", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -265,7 +269,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the result */ - open class func testClientModel(body: Client, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ result: Swift.Result) -> Void)) { + open class func testClientModel(body: Client, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ result: Swift.Result) -> Void)) { testClientModelWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -284,21 +288,21 @@ open class FakeAPI { - returns: RequestBuilder */ open class func testClientModelWithRequestBuilder(body: Client) -> RequestBuilder { - let path = "/fake" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/fake" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "PATCH", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "PATCH", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -321,7 +325,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the result */ - open class func testEndpointParameters(number: Double, double: Double, patternWithoutDelimiter: String, byte: Data, integer: Int? = nil, int32: Int? = nil, int64: Int64? = nil, float: Float? = nil, string: String? = nil, binary: URL? = nil, date: Date? = nil, dateTime: Date? = nil, password: String? = nil, callback: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ result: Swift.Result) -> Void)) { + open class func testEndpointParameters(number: Double, double: Double, patternWithoutDelimiter: String, byte: Data, integer: Int? = nil, int32: Int? = nil, int64: Int64? = nil, float: Float? = nil, string: String? = nil, binary: URL? = nil, date: Date? = nil, dateTime: Date? = nil, password: String? = nil, callback: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ result: Swift.Result) -> Void)) { testEndpointParametersWithRequestBuilder(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(apiResponseQueue) { result -> Void in switch result { case .success: @@ -356,9 +360,9 @@ open class FakeAPI { - returns: RequestBuilder */ open class func testEndpointParametersWithRequestBuilder(number: Double, double: Double, patternWithoutDelimiter: String, byte: Data, integer: Int? = nil, int32: Int? = nil, int64: Int64? = nil, float: Float? = nil, string: String? = nil, binary: URL? = nil, date: Date? = nil, dateTime: Date? = nil, password: String? = nil, callback: String? = nil) -> RequestBuilder { - let path = "/fake" - let URLString = PetstoreClientAPI.basePath + path - let formParams: [String: Any?] = [ + let localVariablePath = "/fake" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableFormParams: [String: Any?] = [ "integer": integer?.encodeToJSON(), "int32": int32?.encodeToJSON(), "int64": int64?.encodeToJSON(), @@ -375,20 +379,20 @@ open class FakeAPI { "callback": callback?.encodeToJSON(), ] - let nonNullParameters = APIHelper.rejectNil(formParams) - let parameters = APIHelper.convertBoolToString(nonNullParameters) + let localVariableNonNullParameters = APIHelper.rejectNil(localVariableFormParams) + let localVariableParameters = APIHelper.convertBoolToString(localVariableNonNullParameters) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ "Content-Type": "application/x-www-form-urlencoded", ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -472,7 +476,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the result */ - open class func testEnumParameters(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ result: Swift.Result) -> Void)) { + open class func testEnumParameters(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ result: Swift.Result) -> Void)) { testEnumParametersWithRequestBuilder(enumHeaderStringArray: enumHeaderStringArray, enumHeaderString: enumHeaderString, enumQueryStringArray: enumQueryStringArray, enumQueryString: enumQueryString, enumQueryInteger: enumQueryInteger, enumQueryDouble: enumQueryDouble, enumFormStringArray: enumFormStringArray, enumFormString: enumFormString).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -498,35 +502,35 @@ open class FakeAPI { - returns: RequestBuilder */ open class func testEnumParametersWithRequestBuilder(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil) -> RequestBuilder { - let path = "/fake" - let URLString = PetstoreClientAPI.basePath + path - let formParams: [String: Any?] = [ + let localVariablePath = "/fake" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableFormParams: [String: Any?] = [ "enum_form_string_array": enumFormStringArray?.encodeToJSON(), "enum_form_string": enumFormString?.encodeToJSON(), ] - let nonNullParameters = APIHelper.rejectNil(formParams) - let parameters = APIHelper.convertBoolToString(nonNullParameters) + let localVariableNonNullParameters = APIHelper.rejectNil(localVariableFormParams) + let localVariableParameters = APIHelper.convertBoolToString(localVariableNonNullParameters) - var urlComponents = URLComponents(string: URLString) - urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ + var localVariableUrlComponents = URLComponents(string: localVariableURLString) + localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ "enum_query_string_array": enumQueryStringArray?.encodeToJSON(), "enum_query_string": enumQueryString?.encodeToJSON(), "enum_query_integer": enumQueryInteger?.encodeToJSON(), "enum_query_double": enumQueryDouble?.encodeToJSON(), ]) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ "Content-Type": "application/x-www-form-urlencoded", "enum_header_string_array": enumHeaderStringArray?.encodeToJSON(), "enum_header_string": enumHeaderString?.encodeToJSON(), ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -541,7 +545,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the result */ - open class func testGroupParameters(requiredStringGroup: Int, requiredBooleanGroup: Bool, requiredInt64Group: Int64, stringGroup: Int? = nil, booleanGroup: Bool? = nil, int64Group: Int64? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ result: Swift.Result) -> Void)) { + open class func testGroupParameters(requiredStringGroup: Int, requiredBooleanGroup: Bool, requiredInt64Group: Int64, stringGroup: Int? = nil, booleanGroup: Bool? = nil, int64Group: Int64? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ result: Swift.Result) -> Void)) { testGroupParametersWithRequestBuilder(requiredStringGroup: requiredStringGroup, requiredBooleanGroup: requiredBooleanGroup, requiredInt64Group: requiredInt64Group, stringGroup: stringGroup, booleanGroup: booleanGroup, int64Group: int64Group).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -565,28 +569,28 @@ open class FakeAPI { - returns: RequestBuilder */ open class func testGroupParametersWithRequestBuilder(requiredStringGroup: Int, requiredBooleanGroup: Bool, requiredInt64Group: Int64, stringGroup: Int? = nil, booleanGroup: Bool? = nil, int64Group: Int64? = nil) -> RequestBuilder { - let path = "/fake" - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + let localVariablePath = "/fake" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - var urlComponents = URLComponents(string: URLString) - urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ + var localVariableUrlComponents = URLComponents(string: localVariableURLString) + localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ "required_string_group": requiredStringGroup.encodeToJSON(), "required_int64_group": requiredInt64Group.encodeToJSON(), "string_group": stringGroup?.encodeToJSON(), "int64_group": int64Group?.encodeToJSON(), ]) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ "required_boolean_group": requiredBooleanGroup.encodeToJSON(), "boolean_group": booleanGroup?.encodeToJSON(), ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "DELETE", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -596,7 +600,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the result */ - open class func testInlineAdditionalProperties(param: [String: String], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ result: Swift.Result) -> Void)) { + open class func testInlineAdditionalProperties(param: [String: String], apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ result: Swift.Result) -> Void)) { testInlineAdditionalPropertiesWithRequestBuilder(param: param).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -614,21 +618,21 @@ open class FakeAPI { - returns: RequestBuilder */ open class func testInlineAdditionalPropertiesWithRequestBuilder(param: [String: String]) -> RequestBuilder { - let path = "/fake/inline-additionalProperties" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: param) + let localVariablePath = "/fake/inline-additionalProperties" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: param) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -639,7 +643,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the result */ - open class func testJsonFormData(param: String, param2: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ result: Swift.Result) -> Void)) { + open class func testJsonFormData(param: String, param2: String, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ result: Swift.Result) -> Void)) { testJsonFormDataWithRequestBuilder(param: param, param2: param2).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -658,27 +662,26 @@ open class FakeAPI { - returns: RequestBuilder */ open class func testJsonFormDataWithRequestBuilder(param: String, param2: String) -> RequestBuilder { - let path = "/fake/jsonFormData" - let URLString = PetstoreClientAPI.basePath + path - let formParams: [String: Any?] = [ + let localVariablePath = "/fake/jsonFormData" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableFormParams: [String: Any?] = [ "param": param.encodeToJSON(), "param2": param2.encodeToJSON(), ] - let nonNullParameters = APIHelper.rejectNil(formParams) - let parameters = APIHelper.convertBoolToString(nonNullParameters) + let localVariableNonNullParameters = APIHelper.rejectNil(localVariableFormParams) + let localVariableParameters = APIHelper.convertBoolToString(localVariableNonNullParameters) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ "Content-Type": "application/x-www-form-urlencoded", ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } - } 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 f4608c34d82..3dc0e033b32 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 @@ -6,8 +6,12 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif open class FakeClassnameTags123API { + /** To test class name in snake case @@ -15,7 +19,7 @@ open class FakeClassnameTags123API { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the result */ - open class func testClassname(body: Client, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ result: Swift.Result) -> Void)) { + open class func testClassname(body: Client, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ result: Swift.Result) -> Void)) { testClassnameWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -37,21 +41,20 @@ open class FakeClassnameTags123API { - returns: RequestBuilder */ open class func testClassnameWithRequestBuilder(body: Client) -> RequestBuilder { - let path = "/fake_classname_test" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/fake_classname_test" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "PATCH", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "PATCH", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } - } 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 521125d8db8..497686d59d5 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 @@ -6,8 +6,12 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif open class PetAPI { + /** Add a new pet to the store @@ -15,7 +19,7 @@ open class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the result */ - open class func addPet(body: Pet, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ result: Swift.Result) -> Void)) { + open class func addPet(body: Pet, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ result: Swift.Result) -> Void)) { addPetWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -36,21 +40,21 @@ open class PetAPI { - returns: RequestBuilder */ open class func addPetWithRequestBuilder(body: Pet) -> RequestBuilder { - let path = "/pet" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/pet" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -61,7 +65,7 @@ open class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the result */ - open class func deletePet(petId: Int64, apiKey: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ result: Swift.Result) -> Void)) { + open class func deletePet(petId: Int64, apiKey: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ result: Swift.Result) -> Void)) { deletePetWithRequestBuilder(petId: petId, apiKey: apiKey).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -83,24 +87,24 @@ open class PetAPI { - returns: RequestBuilder */ open class func deletePetWithRequestBuilder(petId: Int64, apiKey: String? = nil) -> RequestBuilder { - var path = "/pet/{petId}" + var localVariablePath = "/pet/{petId}" let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))" let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" - path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + localVariablePath = localVariablePath.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ "api_key": apiKey?.encodeToJSON(), ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "DELETE", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -119,7 +123,7 @@ open class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the result */ - open class func findPetsByStatus(status: [String], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ result: Swift.Result<[Pet], Error>) -> Void)) { + open class func findPetsByStatus(status: [String], apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ result: Swift.Result<[Pet], Error>) -> Void)) { findPetsByStatusWithRequestBuilder(status: status).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -141,24 +145,24 @@ open class PetAPI { - returns: RequestBuilder<[Pet]> */ open class func findPetsByStatusWithRequestBuilder(status: [String]) -> RequestBuilder<[Pet]> { - let path = "/pet/findByStatus" - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + let localVariablePath = "/pet/findByStatus" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - var urlComponents = URLComponents(string: URLString) - urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ + var localVariableUrlComponents = URLComponents(string: localVariableURLString) + localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ "status": status.encodeToJSON(), ]) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -169,7 +173,7 @@ open class PetAPI { - parameter completion: completion handler to receive the result */ @available(*, deprecated, message: "This operation is deprecated.") - open class func findPetsByTags(tags: [String], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ result: Swift.Result<[Pet], Error>) -> Void)) { + open class func findPetsByTags(tags: [String], apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ result: Swift.Result<[Pet], Error>) -> Void)) { findPetsByTagsWithRequestBuilder(tags: tags).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -192,24 +196,24 @@ open class PetAPI { */ @available(*, deprecated, message: "This operation is deprecated.") open class func findPetsByTagsWithRequestBuilder(tags: [String]) -> RequestBuilder<[Pet]> { - let path = "/pet/findByTags" - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + let localVariablePath = "/pet/findByTags" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - var urlComponents = URLComponents(string: URLString) - urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ + var localVariableUrlComponents = URLComponents(string: localVariableURLString) + localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ "tags": tags.encodeToJSON(), ]) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -219,7 +223,7 @@ open class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the result */ - open class func getPetById(petId: Int64, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ result: Swift.Result) -> Void)) { + open class func getPetById(petId: Int64, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ result: Swift.Result) -> Void)) { getPetByIdWithRequestBuilder(petId: petId).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -241,24 +245,24 @@ open class PetAPI { - returns: RequestBuilder */ open class func getPetByIdWithRequestBuilder(petId: Int64) -> RequestBuilder { - var path = "/pet/{petId}" + var localVariablePath = "/pet/{petId}" let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))" let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" - path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + localVariablePath = localVariablePath.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -268,7 +272,7 @@ open class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the result */ - open class func updatePet(body: Pet, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ result: Swift.Result) -> Void)) { + open class func updatePet(body: Pet, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ result: Swift.Result) -> Void)) { updatePetWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -289,21 +293,21 @@ open class PetAPI { - returns: RequestBuilder */ open class func updatePetWithRequestBuilder(body: Pet) -> RequestBuilder { - let path = "/pet" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/pet" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "PUT", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -315,7 +319,7 @@ open class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the result */ - open class func updatePetWithForm(petId: Int64, name: String? = nil, status: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ result: Swift.Result) -> Void)) { + open class func updatePetWithForm(petId: Int64, name: String? = nil, status: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ result: Swift.Result) -> Void)) { updatePetWithFormWithRequestBuilder(petId: petId, name: name, status: status).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -338,30 +342,30 @@ open class PetAPI { - returns: RequestBuilder */ open class func updatePetWithFormWithRequestBuilder(petId: Int64, name: String? = nil, status: String? = nil) -> RequestBuilder { - var path = "/pet/{petId}" + var localVariablePath = "/pet/{petId}" let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))" let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" - path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path - let formParams: [String: Any?] = [ + localVariablePath = localVariablePath.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableFormParams: [String: Any?] = [ "name": name?.encodeToJSON(), "status": status?.encodeToJSON(), ] - let nonNullParameters = APIHelper.rejectNil(formParams) - let parameters = APIHelper.convertBoolToString(nonNullParameters) + let localVariableNonNullParameters = APIHelper.rejectNil(localVariableFormParams) + let localVariableParameters = APIHelper.convertBoolToString(localVariableNonNullParameters) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ "Content-Type": "application/x-www-form-urlencoded", ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -373,7 +377,7 @@ open class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the result */ - open class func uploadFile(petId: Int64, additionalMetadata: String? = nil, file: URL? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ result: Swift.Result) -> Void)) { + open class func uploadFile(petId: Int64, additionalMetadata: String? = nil, file: URL? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ result: Swift.Result) -> Void)) { uploadFileWithRequestBuilder(petId: petId, additionalMetadata: additionalMetadata, file: file).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -396,30 +400,30 @@ open class PetAPI { - returns: RequestBuilder */ open class func uploadFileWithRequestBuilder(petId: Int64, additionalMetadata: String? = nil, file: URL? = nil) -> RequestBuilder { - var path = "/pet/{petId}/uploadImage" + var localVariablePath = "/pet/{petId}/uploadImage" let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))" let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" - path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path - let formParams: [String: Any?] = [ + localVariablePath = localVariablePath.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableFormParams: [String: Any?] = [ "additionalMetadata": additionalMetadata?.encodeToJSON(), "file": file?.encodeToJSON(), ] - let nonNullParameters = APIHelper.rejectNil(formParams) - let parameters = APIHelper.convertBoolToString(nonNullParameters) + let localVariableNonNullParameters = APIHelper.rejectNil(localVariableFormParams) + let localVariableParameters = APIHelper.convertBoolToString(localVariableNonNullParameters) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ "Content-Type": "multipart/form-data", ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -431,7 +435,7 @@ open class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the result */ - open class func uploadFileWithRequiredFile(petId: Int64, requiredFile: URL, additionalMetadata: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ result: Swift.Result) -> Void)) { + open class func uploadFileWithRequiredFile(petId: Int64, requiredFile: URL, additionalMetadata: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ result: Swift.Result) -> Void)) { uploadFileWithRequiredFileWithRequestBuilder(petId: petId, requiredFile: requiredFile, additionalMetadata: additionalMetadata).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -454,30 +458,29 @@ open class PetAPI { - returns: RequestBuilder */ open class func uploadFileWithRequiredFileWithRequestBuilder(petId: Int64, requiredFile: URL, additionalMetadata: String? = nil) -> RequestBuilder { - var path = "/fake/{petId}/uploadImageWithRequiredFile" + var localVariablePath = "/fake/{petId}/uploadImageWithRequiredFile" let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))" let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" - path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path - let formParams: [String: Any?] = [ + localVariablePath = localVariablePath.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableFormParams: [String: Any?] = [ "additionalMetadata": additionalMetadata?.encodeToJSON(), "requiredFile": requiredFile.encodeToJSON(), ] - let nonNullParameters = APIHelper.rejectNil(formParams) - let parameters = APIHelper.convertBoolToString(nonNullParameters) + let localVariableNonNullParameters = APIHelper.rejectNil(localVariableFormParams) + let localVariableParameters = APIHelper.convertBoolToString(localVariableNonNullParameters) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ "Content-Type": "multipart/form-data", ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } - } diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift index 18f3dd90a5e..41ceebd8b76 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift @@ -6,8 +6,12 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif open class StoreAPI { + /** Delete purchase order by ID @@ -15,7 +19,7 @@ open class StoreAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the result */ - open class func deleteOrder(orderId: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ result: Swift.Result) -> Void)) { + open class func deleteOrder(orderId: String, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ result: Swift.Result) -> Void)) { deleteOrderWithRequestBuilder(orderId: orderId).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -34,24 +38,24 @@ open class StoreAPI { - returns: RequestBuilder */ open class func deleteOrderWithRequestBuilder(orderId: String) -> RequestBuilder { - var path = "/store/order/{order_id}" + var localVariablePath = "/store/order/{order_id}" let orderIdPreEscape = "\(APIHelper.mapValueToPathItem(orderId))" let orderIdPostEscape = orderIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" - path = path.replacingOccurrences(of: "{order_id}", with: orderIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + localVariablePath = localVariablePath.replacingOccurrences(of: "{order_id}", with: orderIdPostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "DELETE", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -60,7 +64,7 @@ open class StoreAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the result */ - open class func getInventory(apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ result: Swift.Result<[String: Int], Error>) -> Void)) { + open class func getInventory(apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ result: Swift.Result<[String: Int], Error>) -> Void)) { getInventoryWithRequestBuilder().execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -81,21 +85,21 @@ open class StoreAPI { - returns: RequestBuilder<[String: Int]> */ open class func getInventoryWithRequestBuilder() -> RequestBuilder<[String: Int]> { - let path = "/store/inventory" - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + let localVariablePath = "/store/inventory" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder<[String: Int]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder<[String: Int]>.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -105,7 +109,7 @@ open class StoreAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the result */ - open class func getOrderById(orderId: Int64, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ result: Swift.Result) -> Void)) { + open class func getOrderById(orderId: Int64, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ result: Swift.Result) -> Void)) { getOrderByIdWithRequestBuilder(orderId: orderId).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -124,24 +128,24 @@ open class StoreAPI { - returns: RequestBuilder */ open class func getOrderByIdWithRequestBuilder(orderId: Int64) -> RequestBuilder { - var path = "/store/order/{order_id}" + var localVariablePath = "/store/order/{order_id}" let orderIdPreEscape = "\(APIHelper.mapValueToPathItem(orderId))" let orderIdPostEscape = orderIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" - path = path.replacingOccurrences(of: "{order_id}", with: orderIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + localVariablePath = localVariablePath.replacingOccurrences(of: "{order_id}", with: orderIdPostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -151,7 +155,7 @@ open class StoreAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the result */ - open class func placeOrder(body: Order, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ result: Swift.Result) -> Void)) { + open class func placeOrder(body: Order, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ result: Swift.Result) -> Void)) { placeOrderWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -169,21 +173,20 @@ open class StoreAPI { - returns: RequestBuilder */ open class func placeOrderWithRequestBuilder(body: Order) -> RequestBuilder { - let path = "/store/order" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/store/order" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } - } diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift index 2dfa75460f0..da5cd64f60d 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift @@ -6,8 +6,12 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif open class UserAPI { + /** Create user @@ -15,7 +19,7 @@ open class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the result */ - open class func createUser(body: User, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ result: Swift.Result) -> Void)) { + open class func createUser(body: User, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ result: Swift.Result) -> Void)) { createUserWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -34,21 +38,21 @@ open class UserAPI { - returns: RequestBuilder */ open class func createUserWithRequestBuilder(body: User) -> RequestBuilder { - let path = "/user" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/user" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -58,7 +62,7 @@ open class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the result */ - open class func createUsersWithArrayInput(body: [User], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ result: Swift.Result) -> Void)) { + open class func createUsersWithArrayInput(body: [User], apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ result: Swift.Result) -> Void)) { createUsersWithArrayInputWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -76,21 +80,21 @@ open class UserAPI { - returns: RequestBuilder */ open class func createUsersWithArrayInputWithRequestBuilder(body: [User]) -> RequestBuilder { - let path = "/user/createWithArray" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/user/createWithArray" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -100,7 +104,7 @@ open class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the result */ - open class func createUsersWithListInput(body: [User], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ result: Swift.Result) -> Void)) { + open class func createUsersWithListInput(body: [User], apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ result: Swift.Result) -> Void)) { createUsersWithListInputWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -118,21 +122,21 @@ open class UserAPI { - returns: RequestBuilder */ open class func createUsersWithListInputWithRequestBuilder(body: [User]) -> RequestBuilder { - let path = "/user/createWithList" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/user/createWithList" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -142,7 +146,7 @@ open class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the result */ - open class func deleteUser(username: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ result: Swift.Result) -> Void)) { + open class func deleteUser(username: String, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ result: Swift.Result) -> Void)) { deleteUserWithRequestBuilder(username: username).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -161,24 +165,24 @@ open class UserAPI { - returns: RequestBuilder */ open class func deleteUserWithRequestBuilder(username: String) -> RequestBuilder { - var path = "/user/{username}" + var localVariablePath = "/user/{username}" let usernamePreEscape = "\(APIHelper.mapValueToPathItem(username))" let usernamePostEscape = usernamePreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" - path = path.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + localVariablePath = localVariablePath.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "DELETE", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -188,7 +192,7 @@ open class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the result */ - open class func getUserByName(username: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ result: Swift.Result) -> Void)) { + open class func getUserByName(username: String, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ result: Swift.Result) -> Void)) { getUserByNameWithRequestBuilder(username: username).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -206,24 +210,24 @@ open class UserAPI { - returns: RequestBuilder */ open class func getUserByNameWithRequestBuilder(username: String) -> RequestBuilder { - var path = "/user/{username}" + var localVariablePath = "/user/{username}" let usernamePreEscape = "\(APIHelper.mapValueToPathItem(username))" let usernamePostEscape = usernamePreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" - path = path.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + localVariablePath = localVariablePath.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -234,7 +238,7 @@ open class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the result */ - open class func loginUser(username: String, password: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ result: Swift.Result) -> Void)) { + open class func loginUser(username: String, password: String, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ result: Swift.Result) -> Void)) { loginUserWithRequestBuilder(username: username, password: password).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -254,25 +258,25 @@ open class UserAPI { - returns: RequestBuilder */ open class func loginUserWithRequestBuilder(username: String, password: String) -> RequestBuilder { - let path = "/user/login" - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + let localVariablePath = "/user/login" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - var urlComponents = URLComponents(string: URLString) - urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ + var localVariableUrlComponents = URLComponents(string: localVariableURLString) + localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ "username": username.encodeToJSON(), "password": password.encodeToJSON(), ]) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -281,7 +285,7 @@ open class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the result */ - open class func logoutUser(apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ result: Swift.Result) -> Void)) { + open class func logoutUser(apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ result: Swift.Result) -> Void)) { logoutUserWithRequestBuilder().execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -298,21 +302,21 @@ open class UserAPI { - returns: RequestBuilder */ open class func logoutUserWithRequestBuilder() -> RequestBuilder { - let path = "/user/logout" - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + let localVariablePath = "/user/logout" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -323,7 +327,7 @@ open class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the result */ - open class func updateUser(username: String, body: User, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ result: Swift.Result) -> Void)) { + open class func updateUser(username: String, body: User, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ result: Swift.Result) -> Void)) { updateUserWithRequestBuilder(username: username, body: body).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -343,24 +347,23 @@ open class UserAPI { - returns: RequestBuilder */ open class func updateUserWithRequestBuilder(username: String, body: User) -> RequestBuilder { - var path = "/user/{username}" + var localVariablePath = "/user/{username}" let usernamePreEscape = "\(APIHelper.mapValueToPathItem(username))" let usernamePostEscape = usernamePreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" - path = path.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + localVariablePath = localVariablePath.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "PUT", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } - } diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Configuration.swift b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Configuration.swift index 18edabbed78..8fb05331889 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Configuration.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Configuration.swift @@ -7,6 +7,7 @@ import Foundation open class Configuration { + // This value is used to configure the date formatter that is used to serialize dates into JSON format. // You must set it prior to encoding any dates, and it will only be read once. @available(*, unavailable, message: "To set a different date format, use CodableHelper.dateFormatter instead.") diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Extensions.swift b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Extensions.swift index 3aef2d1d6c5..e23035dde30 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Extensions.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Extensions.swift @@ -5,7 +5,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif extension Bool: JSONEncodable { func encodeToJSON() -> Any { return self as Any } @@ -184,44 +186,3 @@ extension HTTPURLResponse { return Array(200 ..< 300).contains(statusCode) } } - -extension AnyCodable: Hashable { - public func hash(into hasher: inout Hasher) { - switch value { - case let value as Bool: - hasher.combine(value) - case let value as Int: - hasher.combine(value) - case let value as Int8: - hasher.combine(value) - case let value as Int16: - hasher.combine(value) - case let value as Int32: - hasher.combine(value) - case let value as Int64: - hasher.combine(value) - case let value as UInt: - hasher.combine(value) - case let value as UInt8: - hasher.combine(value) - case let value as UInt16: - hasher.combine(value) - case let value as UInt32: - hasher.combine(value) - case let value as UInt64: - hasher.combine(value) - case let value as Float: - hasher.combine(value) - case let value as Double: - hasher.combine(value) - case let value as String: - hasher.combine(value) - case let value as [String: AnyCodable]: - hasher.combine(value) - case let value as [AnyCodable]: - hasher.combine(value) - default: - hasher.combine(0) - } - } -} \ No newline at end of file diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesClass.swift b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesClass.swift index 75ab9bc8d0a..621afb93561 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesClass.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesClass.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct AdditionalPropertiesClass: Codable, Hashable { @@ -17,6 +19,7 @@ public struct AdditionalPropertiesClass: Codable, Hashable { self.mapString = mapString self.mapMapString = mapMapString } + public enum CodingKeys: String, CodingKey, CaseIterable { case mapString = "map_string" case mapMapString = "map_map_string" @@ -29,7 +32,5 @@ public struct AdditionalPropertiesClass: Codable, Hashable { try container.encodeIfPresent(mapString, forKey: .mapString) try container.encodeIfPresent(mapMapString, forKey: .mapMapString) } - - - } + diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Animal.swift b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Animal.swift index 0f825cf24d0..cdd4f5335b9 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Animal.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Animal.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct Animal: Codable, Hashable { @@ -17,6 +19,7 @@ public struct Animal: Codable, Hashable { self.className = className self.color = color } + public enum CodingKeys: String, CodingKey, CaseIterable { case className case color @@ -29,7 +32,5 @@ public struct Animal: Codable, Hashable { try container.encode(className, forKey: .className) try container.encodeIfPresent(color, forKey: .color) } - - - } + diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/AnimalFarm.swift b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/AnimalFarm.swift index b20b894a1ad..a0b09cb9761 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/AnimalFarm.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/AnimalFarm.swift @@ -6,6 +6,8 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public typealias AnimalFarm = [Animal] diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift index 2b66af2dc94..c365505ab9d 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct ApiResponse: Codable, Hashable { @@ -19,6 +21,7 @@ public struct ApiResponse: Codable, Hashable { self.type = type self.message = message } + public enum CodingKeys: String, CodingKey, CaseIterable { case code case type @@ -33,7 +36,5 @@ public struct ApiResponse: Codable, Hashable { try container.encodeIfPresent(type, forKey: .type) try container.encodeIfPresent(message, forKey: .message) } - - - } + diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfArrayOfNumberOnly.swift b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfArrayOfNumberOnly.swift index 06f0640475c..226f7456181 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfArrayOfNumberOnly.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfArrayOfNumberOnly.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct ArrayOfArrayOfNumberOnly: Codable, Hashable { @@ -15,6 +17,7 @@ public struct ArrayOfArrayOfNumberOnly: Codable, Hashable { public init(arrayArrayNumber: [[Double]]? = nil) { self.arrayArrayNumber = arrayArrayNumber } + public enum CodingKeys: String, CodingKey, CaseIterable { case arrayArrayNumber = "ArrayArrayNumber" } @@ -25,7 +28,5 @@ public struct ArrayOfArrayOfNumberOnly: Codable, Hashable { var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(arrayArrayNumber, forKey: .arrayArrayNumber) } - - - } + diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfNumberOnly.swift b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfNumberOnly.swift index 8c50c7fa1e4..39831127871 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfNumberOnly.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfNumberOnly.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct ArrayOfNumberOnly: Codable, Hashable { @@ -15,6 +17,7 @@ public struct ArrayOfNumberOnly: Codable, Hashable { public init(arrayNumber: [Double]? = nil) { self.arrayNumber = arrayNumber } + public enum CodingKeys: String, CodingKey, CaseIterable { case arrayNumber = "ArrayNumber" } @@ -25,7 +28,5 @@ public struct ArrayOfNumberOnly: Codable, Hashable { var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(arrayNumber, forKey: .arrayNumber) } - - - } + diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayTest.swift b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayTest.swift index 461ec7cd9ac..8865d76bef2 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayTest.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayTest.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct ArrayTest: Codable, Hashable { @@ -19,6 +21,7 @@ public struct ArrayTest: Codable, Hashable { self.arrayArrayOfInteger = arrayArrayOfInteger self.arrayArrayOfModel = arrayArrayOfModel } + public enum CodingKeys: String, CodingKey, CaseIterable { case arrayOfString = "array_of_string" case arrayArrayOfInteger = "array_array_of_integer" @@ -33,7 +36,5 @@ public struct ArrayTest: Codable, Hashable { try container.encodeIfPresent(arrayArrayOfInteger, forKey: .arrayArrayOfInteger) try container.encodeIfPresent(arrayArrayOfModel, forKey: .arrayArrayOfModel) } - - - } + diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Capitalization.swift b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Capitalization.swift index fbe62983d5e..71cd93bce5f 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Capitalization.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Capitalization.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct Capitalization: Codable, Hashable { @@ -26,6 +28,7 @@ public struct Capitalization: Codable, Hashable { self.sCAETHFlowPoints = sCAETHFlowPoints self.ATT_NAME = ATT_NAME } + public enum CodingKeys: String, CodingKey, CaseIterable { case smallCamel case capitalCamel = "CapitalCamel" @@ -46,7 +49,5 @@ public struct Capitalization: Codable, Hashable { try container.encodeIfPresent(sCAETHFlowPoints, forKey: .sCAETHFlowPoints) try container.encodeIfPresent(ATT_NAME, forKey: .ATT_NAME) } - - - } + diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Cat.swift b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Cat.swift index 7f3a86932f1..457e04bd475 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Cat.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Cat.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct Cat: Codable, Hashable { @@ -19,6 +21,7 @@ public struct Cat: Codable, Hashable { self.color = color self.declawed = declawed } + public enum CodingKeys: String, CodingKey, CaseIterable { case className case color @@ -33,7 +36,5 @@ public struct Cat: Codable, Hashable { try container.encodeIfPresent(color, forKey: .color) try container.encodeIfPresent(declawed, forKey: .declawed) } - - - } + diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/CatAllOf.swift b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/CatAllOf.swift index 8df23954832..8caebb1c206 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/CatAllOf.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/CatAllOf.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct CatAllOf: Codable, Hashable { @@ -15,6 +17,7 @@ public struct CatAllOf: Codable, Hashable { public init(declawed: Bool? = nil) { self.declawed = declawed } + public enum CodingKeys: String, CodingKey, CaseIterable { case declawed } @@ -25,7 +28,5 @@ public struct CatAllOf: Codable, Hashable { var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(declawed, forKey: .declawed) } - - - } + diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Category.swift b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Category.swift index 4109db4d1ef..89016ca353d 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Category.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Category.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct Category: Codable, Hashable { @@ -17,6 +19,7 @@ public struct Category: Codable, Hashable { self.id = id self.name = name } + public enum CodingKeys: String, CodingKey, CaseIterable { case id case name @@ -29,7 +32,5 @@ public struct Category: Codable, Hashable { try container.encodeIfPresent(id, forKey: .id) try container.encode(name, forKey: .name) } - - - } + diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/ClassModel.swift b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/ClassModel.swift index 7269ddbef6f..16e69e560bd 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/ClassModel.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/ClassModel.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif /** Model for testing model with \"_class\" property */ public struct ClassModel: Codable, Hashable { @@ -16,6 +18,7 @@ public struct ClassModel: Codable, Hashable { public init(_class: String? = nil) { self._class = _class } + public enum CodingKeys: String, CodingKey, CaseIterable { case _class } @@ -26,7 +29,5 @@ public struct ClassModel: Codable, Hashable { var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(_class, forKey: ._class) } - - - } + diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Client.swift b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Client.swift index 7d6eff2ffe1..60dbc5dc5c1 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Client.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Client.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct Client: Codable, Hashable { @@ -15,6 +17,7 @@ public struct Client: Codable, Hashable { public init(client: String? = nil) { self.client = client } + public enum CodingKeys: String, CodingKey, CaseIterable { case client } @@ -25,7 +28,5 @@ public struct Client: Codable, Hashable { var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(client, forKey: .client) } - - - } + diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Dog.swift b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Dog.swift index b5f2bcea38a..658732a7f36 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Dog.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Dog.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct Dog: Codable, Hashable { @@ -19,6 +21,7 @@ public struct Dog: Codable, Hashable { self.color = color self.breed = breed } + public enum CodingKeys: String, CodingKey, CaseIterable { case className case color @@ -33,7 +36,5 @@ public struct Dog: Codable, Hashable { try container.encodeIfPresent(color, forKey: .color) try container.encodeIfPresent(breed, forKey: .breed) } - - - } + diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/DogAllOf.swift b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/DogAllOf.swift index 1bfa23d7bc6..82b0dedf35b 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/DogAllOf.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/DogAllOf.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct DogAllOf: Codable, Hashable { @@ -15,6 +17,7 @@ public struct DogAllOf: Codable, Hashable { public init(breed: String? = nil) { self.breed = breed } + public enum CodingKeys: String, CodingKey, CaseIterable { case breed } @@ -25,7 +28,5 @@ public struct DogAllOf: Codable, Hashable { var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(breed, forKey: .breed) } - - - } + diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumArrays.swift b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumArrays.swift index 73368c42143..1d8ce99539c 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumArrays.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumArrays.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct EnumArrays: Codable, Hashable { @@ -25,6 +27,7 @@ public struct EnumArrays: Codable, Hashable { self.justSymbol = justSymbol self.arrayEnum = arrayEnum } + public enum CodingKeys: String, CodingKey, CaseIterable { case justSymbol = "just_symbol" case arrayEnum = "array_enum" @@ -37,7 +40,5 @@ public struct EnumArrays: Codable, Hashable { try container.encodeIfPresent(justSymbol, forKey: .justSymbol) try container.encodeIfPresent(arrayEnum, forKey: .arrayEnum) } - - - } + diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumClass.swift b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumClass.swift index ab01cf297f8..6ea2895aee5 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumClass.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumClass.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public enum EnumClass: String, Codable, CaseIterable { case abc = "_abc" diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumTest.swift b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumTest.swift index 60a81bcac77..8c8bca49774 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumTest.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumTest.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct EnumTest: Codable, Hashable { @@ -41,6 +43,7 @@ public struct EnumTest: Codable, Hashable { self.enumNumber = enumNumber self.outerEnum = outerEnum } + public enum CodingKeys: String, CodingKey, CaseIterable { case enumString = "enum_string" case enumStringRequired = "enum_string_required" @@ -59,7 +62,5 @@ public struct EnumTest: Codable, Hashable { try container.encodeIfPresent(enumNumber, forKey: .enumNumber) try container.encodeIfPresent(outerEnum, forKey: .outerEnum) } - - - } + diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/File.swift b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/File.swift index 90283656d1b..05dd5b1a825 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/File.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/File.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif /** Must be named `File` for test. */ public struct File: Codable, Hashable { @@ -17,6 +19,7 @@ public struct File: Codable, Hashable { public init(sourceURI: String? = nil) { self.sourceURI = sourceURI } + public enum CodingKeys: String, CodingKey, CaseIterable { case sourceURI } @@ -27,7 +30,5 @@ public struct File: Codable, Hashable { var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(sourceURI, forKey: .sourceURI) } - - - } + diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/FileSchemaTestClass.swift b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/FileSchemaTestClass.swift index cff92673bbe..3ca66a31359 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/FileSchemaTestClass.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/FileSchemaTestClass.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct FileSchemaTestClass: Codable, Hashable { @@ -17,6 +19,7 @@ public struct FileSchemaTestClass: Codable, Hashable { self.file = file self.files = files } + public enum CodingKeys: String, CodingKey, CaseIterable { case file case files @@ -29,7 +32,5 @@ public struct FileSchemaTestClass: Codable, Hashable { try container.encodeIfPresent(file, forKey: .file) try container.encodeIfPresent(files, forKey: .files) } - - - } + diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/FormatTest.swift b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/FormatTest.swift index fc86676eec3..a7a4b39e720 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/FormatTest.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/FormatTest.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct FormatTest: Codable, Hashable { @@ -39,6 +41,7 @@ public struct FormatTest: Codable, Hashable { self.uuid = uuid self.password = password } + public enum CodingKeys: String, CodingKey, CaseIterable { case integer case int32 @@ -73,7 +76,5 @@ public struct FormatTest: Codable, Hashable { try container.encodeIfPresent(uuid, forKey: .uuid) try container.encode(password, forKey: .password) } - - - } + diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/HasOnlyReadOnly.swift b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/HasOnlyReadOnly.swift index d7960f5c800..54ed8a723c6 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/HasOnlyReadOnly.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/HasOnlyReadOnly.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct HasOnlyReadOnly: Codable, Hashable { @@ -17,6 +19,7 @@ public struct HasOnlyReadOnly: Codable, Hashable { self.bar = bar self.foo = foo } + public enum CodingKeys: String, CodingKey, CaseIterable { case bar case foo @@ -29,7 +32,5 @@ public struct HasOnlyReadOnly: Codable, Hashable { try container.encodeIfPresent(bar, forKey: .bar) try container.encodeIfPresent(foo, forKey: .foo) } - - - } + diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/List.swift b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/List.swift index c5d4f2cae56..67e3048469f 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/List.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/List.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct List: Codable, Hashable { @@ -15,6 +17,7 @@ public struct List: Codable, Hashable { public init(_123list: String? = nil) { self._123list = _123list } + public enum CodingKeys: String, CodingKey, CaseIterable { case _123list = "123-list" } @@ -25,7 +28,5 @@ public struct List: Codable, Hashable { var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(_123list, forKey: ._123list) } - - - } + diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/MapTest.swift b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/MapTest.swift index b54bd01e5dc..1e728fcdf58 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/MapTest.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/MapTest.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct MapTest: Codable, Hashable { @@ -25,6 +27,7 @@ public struct MapTest: Codable, Hashable { self.directMap = directMap self.indirectMap = indirectMap } + public enum CodingKeys: String, CodingKey, CaseIterable { case mapMapOfString = "map_map_of_string" case mapOfEnumString = "map_of_enum_string" @@ -41,7 +44,5 @@ public struct MapTest: Codable, Hashable { try container.encodeIfPresent(directMap, forKey: .directMap) try container.encodeIfPresent(indirectMap, forKey: .indirectMap) } - - - } + diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/MixedPropertiesAndAdditionalPropertiesClass.swift b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/MixedPropertiesAndAdditionalPropertiesClass.swift index c8f639ef43d..c79ca459217 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/MixedPropertiesAndAdditionalPropertiesClass.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/MixedPropertiesAndAdditionalPropertiesClass.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct MixedPropertiesAndAdditionalPropertiesClass: Codable, Hashable { @@ -19,6 +21,7 @@ public struct MixedPropertiesAndAdditionalPropertiesClass: Codable, Hashable { self.dateTime = dateTime self.map = map } + public enum CodingKeys: String, CodingKey, CaseIterable { case uuid case dateTime @@ -33,7 +36,5 @@ public struct MixedPropertiesAndAdditionalPropertiesClass: Codable, Hashable { try container.encodeIfPresent(dateTime, forKey: .dateTime) try container.encodeIfPresent(map, forKey: .map) } - - - } + diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Model200Response.swift b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Model200Response.swift index 5368032f09b..23402143f71 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Model200Response.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Model200Response.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif /** Model for testing model name starting with number */ public struct Model200Response: Codable, Hashable { @@ -18,6 +20,7 @@ public struct Model200Response: Codable, Hashable { self.name = name self._class = _class } + public enum CodingKeys: String, CodingKey, CaseIterable { case name case _class = "class" @@ -30,7 +33,5 @@ public struct Model200Response: Codable, Hashable { try container.encodeIfPresent(name, forKey: .name) try container.encodeIfPresent(_class, forKey: ._class) } - - - } + diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Name.swift b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Name.swift index 84a40e1c101..a28f46a33ce 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Name.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Name.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif /** Model for testing model name same as property name */ public struct Name: Codable, Hashable { @@ -22,6 +24,7 @@ public struct Name: Codable, Hashable { self.property = property self._123number = _123number } + public enum CodingKeys: String, CodingKey, CaseIterable { case name case snakeCase = "snake_case" @@ -38,7 +41,5 @@ public struct Name: Codable, Hashable { try container.encodeIfPresent(property, forKey: .property) try container.encodeIfPresent(_123number, forKey: ._123number) } - - - } + diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/NumberOnly.swift b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/NumberOnly.swift index 710f41648f9..87ceb64bb97 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/NumberOnly.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/NumberOnly.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct NumberOnly: Codable, Hashable { @@ -15,6 +17,7 @@ public struct NumberOnly: Codable, Hashable { public init(justNumber: Double? = nil) { self.justNumber = justNumber } + public enum CodingKeys: String, CodingKey, CaseIterable { case justNumber = "JustNumber" } @@ -25,7 +28,5 @@ public struct NumberOnly: Codable, Hashable { var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(justNumber, forKey: .justNumber) } - - - } + diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Order.swift b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Order.swift index 15726ab16a4..e2eeced4c57 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Order.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Order.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct Order: Codable, Hashable { @@ -31,6 +33,7 @@ public struct Order: Codable, Hashable { self.status = status self.complete = complete } + public enum CodingKeys: String, CodingKey, CaseIterable { case id case petId @@ -51,7 +54,5 @@ public struct Order: Codable, Hashable { try container.encodeIfPresent(status, forKey: .status) try container.encodeIfPresent(complete, forKey: .complete) } - - - } + diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/OuterComposite.swift b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/OuterComposite.swift index 36904afbd50..edeaccaeaa6 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/OuterComposite.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/OuterComposite.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct OuterComposite: Codable, Hashable { @@ -19,6 +21,7 @@ public struct OuterComposite: Codable, Hashable { self.myString = myString self.myBoolean = myBoolean } + public enum CodingKeys: String, CodingKey, CaseIterable { case myNumber = "my_number" case myString = "my_string" @@ -33,7 +36,5 @@ public struct OuterComposite: Codable, Hashable { try container.encodeIfPresent(myString, forKey: .myString) try container.encodeIfPresent(myBoolean, forKey: .myBoolean) } - - - } + diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/OuterEnum.swift b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/OuterEnum.swift index 9bd6f3bef8f..76c34b3c2ce 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/OuterEnum.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/OuterEnum.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public enum OuterEnum: String, Codable, CaseIterable { case placed = "placed" diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Pet.swift b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Pet.swift index 7a1c2826a19..ddd1186b891 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Pet.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Pet.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct Pet: Codable, Hashable { @@ -31,6 +33,7 @@ public struct Pet: Codable, Hashable { self.tags = tags self.status = status } + public enum CodingKeys: String, CodingKey, CaseIterable { case id case category @@ -51,7 +54,5 @@ public struct Pet: Codable, Hashable { try container.encodeIfPresent(tags, forKey: .tags) try container.encodeIfPresent(status, forKey: .status) } - - - } + diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/ReadOnlyFirst.swift b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/ReadOnlyFirst.swift index 38fb57af328..57ba3f577c8 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/ReadOnlyFirst.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/ReadOnlyFirst.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct ReadOnlyFirst: Codable, Hashable { @@ -17,6 +19,7 @@ public struct ReadOnlyFirst: Codable, Hashable { self.bar = bar self.baz = baz } + public enum CodingKeys: String, CodingKey, CaseIterable { case bar case baz @@ -29,7 +32,5 @@ public struct ReadOnlyFirst: Codable, Hashable { try container.encodeIfPresent(bar, forKey: .bar) try container.encodeIfPresent(baz, forKey: .baz) } - - - } + diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Return.swift b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Return.swift index ed7e538a06d..afc2b51f8f3 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Return.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Return.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif /** Model for testing reserved words */ public struct Return: Codable, Hashable { @@ -16,6 +18,7 @@ public struct Return: Codable, Hashable { public init(_return: Int? = nil) { self._return = _return } + public enum CodingKeys: String, CodingKey, CaseIterable { case _return = "return" } @@ -26,7 +29,5 @@ public struct Return: Codable, Hashable { var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(_return, forKey: ._return) } - - - } + diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/SpecialModelName.swift b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/SpecialModelName.swift index 18747e071bc..bfe9723f888 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/SpecialModelName.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/SpecialModelName.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct SpecialModelName: Codable, Hashable { @@ -15,6 +17,7 @@ public struct SpecialModelName: Codable, Hashable { public init(specialPropertyName: Int64? = nil) { self.specialPropertyName = specialPropertyName } + public enum CodingKeys: String, CodingKey, CaseIterable { case specialPropertyName = "$special[property.name]" } @@ -25,7 +28,5 @@ public struct SpecialModelName: Codable, Hashable { var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(specialPropertyName, forKey: .specialPropertyName) } - - - } + diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/StringBooleanMap.swift b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/StringBooleanMap.swift index 0699c25ff7e..126c35c85a6 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/StringBooleanMap.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/StringBooleanMap.swift @@ -6,12 +6,16 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct StringBooleanMap: Codable, Hashable { + public enum CodingKeys: CodingKey, CaseIterable { } + public var additionalProperties: [String: Bool] = [:] public subscript(key: String) -> Bool? { @@ -38,11 +42,11 @@ public struct StringBooleanMap: Codable, Hashable { // Decodable protocol methods public init(from decoder: Decoder) throws { - let container = try decoder.container(keyedBy: String.self) + let container = try decoder.container(keyedBy: CodingKeys.self) var nonAdditionalPropertyKeys = Set() - additionalProperties = try container.decodeMap(Bool.self, excludedKeys: nonAdditionalPropertyKeys) + let additionalPropertiesContainer = try decoder.container(keyedBy: String.self) + additionalProperties = try additionalPropertiesContainer.decodeMap(Bool.self, excludedKeys: nonAdditionalPropertyKeys) } - - } + diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift index 11c5f7a750b..07b826264f3 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct Tag: Codable, Hashable { @@ -17,6 +19,7 @@ public struct Tag: Codable, Hashable { self.id = id self.name = name } + public enum CodingKeys: String, CodingKey, CaseIterable { case id case name @@ -29,7 +32,5 @@ public struct Tag: Codable, Hashable { try container.encodeIfPresent(id, forKey: .id) try container.encodeIfPresent(name, forKey: .name) } - - - } + diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderDefault.swift b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderDefault.swift index 35b1a5833b9..e58eecd960f 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderDefault.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderDefault.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct TypeHolderDefault: Codable, Hashable { @@ -23,6 +25,7 @@ public struct TypeHolderDefault: Codable, Hashable { self.boolItem = boolItem self.arrayItem = arrayItem } + public enum CodingKeys: String, CodingKey, CaseIterable { case stringItem = "string_item" case numberItem = "number_item" @@ -41,7 +44,5 @@ public struct TypeHolderDefault: Codable, Hashable { try container.encode(boolItem, forKey: .boolItem) try container.encode(arrayItem, forKey: .arrayItem) } - - - } + diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderExample.swift b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderExample.swift index 37277a4ac00..6c22fdbae7a 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderExample.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderExample.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct TypeHolderExample: Codable, Hashable { @@ -23,6 +25,7 @@ public struct TypeHolderExample: Codable, Hashable { self.boolItem = boolItem self.arrayItem = arrayItem } + public enum CodingKeys: String, CodingKey, CaseIterable { case stringItem = "string_item" case numberItem = "number_item" @@ -41,7 +44,5 @@ public struct TypeHolderExample: Codable, Hashable { try container.encode(boolItem, forKey: .boolItem) try container.encode(arrayItem, forKey: .arrayItem) } - - - } + diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/User.swift b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/User.swift index 2bbc31806ff..7afe359ae40 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/User.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models/User.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct User: Codable, Hashable { @@ -30,6 +32,7 @@ public struct User: Codable, Hashable { self.phone = phone self.userStatus = userStatus } + public enum CodingKeys: String, CodingKey, CaseIterable { case id case username @@ -54,7 +57,5 @@ public struct User: Codable, Hashable { try container.encodeIfPresent(phone, forKey: .phone) try container.encodeIfPresent(userStatus, forKey: .userStatus) } - - - } + 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 52b2071ec1a..41959190a26 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift @@ -93,14 +93,14 @@ open class URLSessionRequestBuilder: RequestBuilder { return modifiedRequest } - override open func execute(_ apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, _ completion: @escaping (_ result: Swift.Result, Error>) -> Void) { + override open func execute(_ apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, _ completion: @escaping (_ result: Swift.Result, Error>) -> Void) { let urlSessionId = UUID().uuidString // Create a new manager for each request to customize its request header let urlSession = createURLSession() urlSessionStore[urlSessionId] = urlSession guard let xMethod = HTTPMethod(rawValue: method) else { - fatalError("Unsuported Http method - \(method)") + fatalError("Unsupported Http method - \(method)") } let encoding: ParameterEncoding @@ -119,7 +119,7 @@ open class URLSessionRequestBuilder: RequestBuilder { } else if contentType == "application/x-www-form-urlencoded" { encoding = FormURLEncoding() } else { - fatalError("Unsuported Media Type - \(contentType)") + fatalError("Unsupported Media Type - \(contentType)") } } @@ -205,16 +205,18 @@ open class URLSessionRequestBuilder: RequestBuilder { } let fileManager = FileManager.default - let documentsDirectory = fileManager.urls(for: .documentDirectory, in: .userDomainMask)[0] + let cachesDirectory = fileManager.urls(for: .cachesDirectory, in: .userDomainMask)[0] let requestURL = try getURL(from: urlRequest) var requestPath = try getPath(from: requestURL) if let headerFileName = getFileName(fromContentDisposition: httpResponse.allHeaderFields["Content-Disposition"] as? String) { requestPath = requestPath.appending("/\(headerFileName)") + } else { + requestPath = requestPath.appending("/tmp.PetstoreClient.\(UUID().uuidString)") } - let filePath = documentsDirectory.appendingPathComponent(requestPath) + let filePath = cachesDirectory.appendingPathComponent(requestPath) let directoryPath = filePath.deletingLastPathComponent().path try fileManager.createDirectory(atPath: directoryPath, withIntermediateDirectories: true, attributes: nil) @@ -232,6 +234,10 @@ open class URLSessionRequestBuilder: RequestBuilder { completion(.success(Response(response: httpResponse, body: nil))) + case is Data.Type: + + completion(.success(Response(response: httpResponse, body: data as? T))) + default: completion(.success(Response(response: httpResponse, body: data as? T))) @@ -244,7 +250,7 @@ open class URLSessionRequestBuilder: RequestBuilder { for (key, value) in headers { httpHeaders[key] = value } - for (key, value) in PetstoreClientAPI.customHeaders { + for (key, value) in PetstoreClient.customHeaders { httpHeaders[key] = value } return httpHeaders @@ -328,6 +334,43 @@ open class URLSessionDecodableRequestBuilder: URLSessionRequestBui completion(.success(Response(response: httpResponse, body: body as? T))) + case is URL.Type: + do { + + guard error == nil else { + throw DownloadException.responseFailed + } + + guard let data = data else { + throw DownloadException.responseDataMissing + } + + let fileManager = FileManager.default + let cachesDirectory = fileManager.urls(for: .cachesDirectory, in: .userDomainMask)[0] + let requestURL = try getURL(from: urlRequest) + + var requestPath = try getPath(from: requestURL) + + if let headerFileName = getFileName(fromContentDisposition: httpResponse.allHeaderFields["Content-Disposition"] as? String) { + requestPath = requestPath.appending("/\(headerFileName)") + } else { + requestPath = requestPath.appending("/tmp.PetstoreClient.\(UUID().uuidString)") + } + + let filePath = cachesDirectory.appendingPathComponent(requestPath) + let directoryPath = filePath.deletingLastPathComponent().path + + try fileManager.createDirectory(atPath: directoryPath, withIntermediateDirectories: true, attributes: nil) + try data.write(to: filePath, options: .atomic) + + completion(.success(Response(response: httpResponse, body: filePath as? T))) + + } catch let requestParserError as DownloadException { + completion(.failure(ErrorResponse.error(400, data, response, requestParserError))) + } catch { + completion(.failure(ErrorResponse.error(400, data, response, error))) + } + case is Void.Type: completion(.success(Response(response: httpResponse, body: nil))) diff --git a/samples/client/petstore/swift5/resultLibrary/docs/FakeAPI.md b/samples/client/petstore/swift5/resultLibrary/docs/FakeAPI.md index 543869c0d2e..553a46281aa 100644 --- a/samples/client/petstore/swift5/resultLibrary/docs/FakeAPI.md +++ b/samples/client/petstore/swift5/resultLibrary/docs/FakeAPI.md @@ -379,7 +379,7 @@ import PetstoreClient let number = 987 // Double | None let double = 987 // Double | None let patternWithoutDelimiter = "patternWithoutDelimiter_example" // String | None -let byte = 987 // Data | None +let byte = Data([9, 8, 7]) // Data | None let integer = 987 // Int | None (optional) let int32 = 987 // Int | None (optional) let int64 = 987 // Int64 | None (optional) diff --git a/samples/client/petstore/swift5/resultLibrary/project.yml b/samples/client/petstore/swift5/resultLibrary/project.yml index 5528eeee513..0493cf65896 100644 --- a/samples/client/petstore/swift5/resultLibrary/project.yml +++ b/samples/client/petstore/swift5/resultLibrary/project.yml @@ -11,5 +11,5 @@ targets: settings: APPLICATION_EXTENSION_API_ONLY: true scheme: {} - + dependencies: - carthage: AnyCodable diff --git a/samples/client/petstore/swift5/rxswiftLibrary/.gitignore b/samples/client/petstore/swift5/rxswiftLibrary/.gitignore index 5e5d5cebcf4..627d360a903 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/.gitignore +++ b/samples/client/petstore/swift5/rxswiftLibrary/.gitignore @@ -1,12 +1,22 @@ +# Created by https://www.toptal.com/developers/gitignore/api/swift,xcode +# Edit at https://www.toptal.com/developers/gitignore?templates=swift,xcode + +### Swift ### # Xcode # # gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore -## Build generated -build/ -DerivedData +## User settings +xcuserdata/ -## Various settings +## compatibility with Xcode 8 and earlier (ignoring not required starting Xcode 9) +*.xcscmblueprint +*.xccheckout + +## compatibility with Xcode 3 and earlier (ignoring not required starting Xcode 4) +build/ +DerivedData/ +*.moved-aside *.pbxuser !default.pbxuser *.mode1v3 @@ -15,49 +25,81 @@ DerivedData !default.mode2v3 *.perspectivev3 !default.perspectivev3 -xcuserdata - -## Other -*.xccheckout -*.moved-aside -*.xcuserstate -*.xcscmblueprint ## Obj-C/Swift specific *.hmap + +## App packaging *.ipa +*.dSYM.zip +*.dSYM ## Playgrounds timeline.xctimeline playground.xcworkspace # Swift Package Manager -# # Add this line if you want to avoid checking in source code from Swift Package Manager dependencies. # Packages/ +# Package.pins +# Package.resolved +# *.xcodeproj +# Xcode automatically generates this directory with a .xcworkspacedata file and xcuserdata +# hence it is not needed unless you have added a package configuration file to your project +# .swiftpm + .build/ # CocoaPods -# # We recommend against adding the Pods directory to your .gitignore. However # you should judge for yourself, the pros and cons are mentioned at: # https://guides.cocoapods.org/using/using-cocoapods.html#should-i-check-the-pods-directory-into-source-control -# # Pods/ +# Add this line if you want to avoid checking in source code from the Xcode workspace +# *.xcworkspace # Carthage -# # Add this line if you want to avoid checking in source code from Carthage dependencies. # Carthage/Checkouts -Carthage/Build +Carthage/Build/ + +# Add this lines if you are using Accio dependency management (Deprecated since Xcode 12) +# Dependencies/ +# .accio/ # fastlane -# -# It is recommended to not store the screenshots in the git repo. Instead, use fastlane to re-generate the -# screenshots whenever they are needed. +# It is recommended to not store the screenshots in the git repo. +# Instead, use fastlane to re-generate the screenshots whenever they are needed. # For more information about the recommended setup visit: -# https://github.com/fastlane/fastlane/blob/master/docs/Gitignore.md +# https://docs.fastlane.tools/best-practices/source-control/#source-control fastlane/report.xml -fastlane/screenshots +fastlane/Preview.html +fastlane/screenshots/**/*.png +fastlane/test_output + +# Code Injection +# After new code Injection tools there's a generated folder /iOSInjectionProject +# https://github.com/johnno1962/injectionforxcode + +iOSInjectionProject/ + +### Xcode ### +# Xcode +# gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore + + + + +## Gcc Patch +/*.gcno + +### Xcode Patch ### +*.xcodeproj/* +!*.xcodeproj/project.pbxproj +!*.xcodeproj/xcshareddata/ +!*.xcworkspace/contents.xcworkspacedata +**/xcshareddata/WorkspaceSettings.xcsettings + +# End of https://www.toptal.com/developers/gitignore/api/swift,xcode diff --git a/samples/client/petstore/swift5/rxswiftLibrary/.openapi-generator/VERSION b/samples/client/petstore/swift5/rxswiftLibrary/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/.openapi-generator/VERSION +++ b/samples/client/petstore/swift5/rxswiftLibrary/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/client/petstore/swift5/rxswiftLibrary/.swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata b/samples/client/petstore/swift5/rxswiftLibrary/.swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata new file mode 100644 index 00000000000..919434a6254 --- /dev/null +++ b/samples/client/petstore/swift5/rxswiftLibrary/.swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/samples/client/petstore/swift5/rxswiftLibrary/Cartfile b/samples/client/petstore/swift5/rxswiftLibrary/Cartfile index 2fd5cfcce54..a095f11173e 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/Cartfile +++ b/samples/client/petstore/swift5/rxswiftLibrary/Cartfile @@ -1,3 +1,3 @@ -github "ReactiveX/RxSwift" ~> 5.1.1 -github "Flight-School/AnyCodable" ~> 0.4.0 +github "ReactiveX/RxSwift" ~> 6.2.0 +github "Flight-School/AnyCodable" ~> 0.6.1 diff --git a/samples/client/petstore/swift5/rxswiftLibrary/Package.resolved b/samples/client/petstore/swift5/rxswiftLibrary/Package.resolved index e3afef806b8..638fc4cc35b 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/Package.resolved +++ b/samples/client/petstore/swift5/rxswiftLibrary/Package.resolved @@ -2,12 +2,21 @@ "object": { "pins": [ { - "package": "RxSwift", - "repositoryURL": "https://github.com/ReactiveX/RxSwift.git", + "package": "AnyCodable", + "repositoryURL": "https://github.com/Flight-School/AnyCodable", "state": { "branch": null, - "revision": "b3e888b4972d9bc76495dd74d30a8c7fad4b9395", - "version": "5.0.1" + "revision": "69261f239f0fffaf51495dadc4f8483fbfe97025", + "version": "0.6.1" + } + }, + { + "package": "RxSwift", + "repositoryURL": "https://github.com/ReactiveX/RxSwift", + "state": { + "branch": null, + "revision": "7c17a6ccca06b5c107cfa4284e634562ddaf5951", + "version": "6.2.0" } } ] diff --git a/samples/client/petstore/swift5/rxswiftLibrary/Package.swift b/samples/client/petstore/swift5/rxswiftLibrary/Package.swift index f3bcac26bb0..c70e60a1a8b 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/Package.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/Package.swift @@ -19,8 +19,8 @@ let package = Package( ], dependencies: [ // Dependencies declare other packages that this package depends on. - .package(url: "https://github.com/Flight-School/AnyCodable", .exact("0.4.0")), - .package(url: "https://github.com/ReactiveX/RxSwift.git", from: "5.0.0"), + .package(url: "https://github.com/Flight-School/AnyCodable", from: "0.6.1"), + .package(url: "https://github.com/ReactiveX/RxSwift", from: "6.2.0"), ], targets: [ // Targets are the basic building blocks of a package. A target can define a module or a test suite. diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient.podspec b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient.podspec index 2cd68666098..12688d5c28d 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient.podspec +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient.podspec @@ -11,6 +11,6 @@ Pod::Spec.new do |s| s.homepage = 'https://github.com/openapitools/openapi-generator' s.summary = 'PetstoreClient' s.source_files = 'PetstoreClient/Classes/**/*.swift' - s.dependency 'RxSwift', '~> 5.1.1' - s.dependency 'AnyCodable-FlightSchool', '~> 0.4.0' + s.dependency 'RxSwift', '~> 6.2.0' + s.dependency 'AnyCodable-FlightSchool', '~> 0.6.1' end diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs.swift b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs.swift index dbdab491ff7..941c61b713a 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs.swift @@ -6,10 +6,13 @@ import Foundation -open class PetstoreClientAPI { +@available(*, deprecated, renamed: "PetstoreClient") +public typealias PetstoreClientAPI = PetstoreClient + +open class PetstoreClient { public static var basePath = "http://petstore.swagger.io:80/v2" - public static var credential: URLCredential? public static var customHeaders: [String: String] = [:] + public static var credential: URLCredential? public static var requestBuilderFactory: RequestBuilderFactory = URLSessionRequestBuilderFactory() public static var apiResponseQueue: DispatchQueue = .main } @@ -32,7 +35,7 @@ open class RequestBuilder { self.parameters = parameters self.headers = headers - addHeaders(PetstoreClientAPI.customHeaders) + addHeaders(PetstoreClient.customHeaders) } open func addHeaders(_ aHeaders: [String: String]) { @@ -41,7 +44,7 @@ open class RequestBuilder { } } - open func execute(_ apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, _ completion: @escaping (_ result: Swift.Result, Error>) -> Void) { } + open func execute(_ apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, _ completion: @escaping (_ result: Swift.Result, Error>) -> Void) { } public func addHeader(name: String, value: String) -> Self { if !value.isEmpty { @@ -51,7 +54,7 @@ open class RequestBuilder { } open func addCredential() -> Self { - credential = PetstoreClientAPI.credential + credential = PetstoreClient.credential return self } } 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 12e7760ec2c..120be970deb 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 @@ -7,8 +7,12 @@ import Foundation import RxSwift +#if canImport(AnyCodable) +import AnyCodable +#endif open class AnotherFakeAPI { + /** To test special tags @@ -16,7 +20,7 @@ open class AnotherFakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Observable */ - open class func call123testSpecialTags(body: Client, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Observable { + open class func call123testSpecialTags(body: Client, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> Observable { return Observable.create { observer -> Disposable in call123testSpecialTagsWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { @@ -39,21 +43,20 @@ open class AnotherFakeAPI { - returns: RequestBuilder */ open class func call123testSpecialTagsWithRequestBuilder(body: Client) -> RequestBuilder { - let path = "/another-fake/dummy" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/another-fake/dummy" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "PATCH", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "PATCH", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } - } 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 06b88c2a71f..ea76a5a7ba1 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 @@ -7,15 +7,19 @@ import Foundation import RxSwift +#if canImport(AnyCodable) +import AnyCodable +#endif open class FakeAPI { + /** - parameter body: (body) Input boolean as post body (optional) - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Observable */ - open class func fakeOuterBooleanSerialize(body: Bool? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Observable { + open class func fakeOuterBooleanSerialize(body: Bool? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> Observable { return Observable.create { observer -> Disposable in fakeOuterBooleanSerializeWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { @@ -37,21 +41,21 @@ open class FakeAPI { - returns: RequestBuilder */ open class func fakeOuterBooleanSerializeWithRequestBuilder(body: Bool? = nil) -> RequestBuilder { - let path = "/fake/outer/boolean" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/fake/outer/boolean" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -60,7 +64,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Observable */ - open class func fakeOuterCompositeSerialize(body: OuterComposite? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Observable { + open class func fakeOuterCompositeSerialize(body: OuterComposite? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> Observable { return Observable.create { observer -> Disposable in fakeOuterCompositeSerializeWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { @@ -82,21 +86,21 @@ open class FakeAPI { - returns: RequestBuilder */ open class func fakeOuterCompositeSerializeWithRequestBuilder(body: OuterComposite? = nil) -> RequestBuilder { - let path = "/fake/outer/composite" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/fake/outer/composite" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -105,7 +109,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Observable */ - open class func fakeOuterNumberSerialize(body: Double? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Observable { + open class func fakeOuterNumberSerialize(body: Double? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> Observable { return Observable.create { observer -> Disposable in fakeOuterNumberSerializeWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { @@ -127,21 +131,21 @@ open class FakeAPI { - returns: RequestBuilder */ open class func fakeOuterNumberSerializeWithRequestBuilder(body: Double? = nil) -> RequestBuilder { - let path = "/fake/outer/number" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/fake/outer/number" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -150,7 +154,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Observable */ - open class func fakeOuterStringSerialize(body: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Observable { + open class func fakeOuterStringSerialize(body: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> Observable { return Observable.create { observer -> Disposable in fakeOuterStringSerializeWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { @@ -172,21 +176,21 @@ open class FakeAPI { - returns: RequestBuilder */ open class func fakeOuterStringSerializeWithRequestBuilder(body: String? = nil) -> RequestBuilder { - let path = "/fake/outer/string" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/fake/outer/string" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -195,7 +199,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Observable */ - open class func testBodyWithFileSchema(body: FileSchemaTestClass, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Observable { + open class func testBodyWithFileSchema(body: FileSchemaTestClass, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> Observable { return Observable.create { observer -> Disposable in testBodyWithFileSchemaWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { @@ -217,21 +221,21 @@ open class FakeAPI { - returns: RequestBuilder */ open class func testBodyWithFileSchemaWithRequestBuilder(body: FileSchemaTestClass) -> RequestBuilder { - let path = "/fake/body-with-file-schema" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/fake/body-with-file-schema" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "PUT", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -241,7 +245,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Observable */ - open class func testBodyWithQueryParams(query: String, body: User, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Observable { + open class func testBodyWithQueryParams(query: String, body: User, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> Observable { return Observable.create { observer -> Disposable in testBodyWithQueryParamsWithRequestBuilder(query: query, body: body).execute(apiResponseQueue) { result -> Void in switch result { @@ -263,24 +267,24 @@ open class FakeAPI { - returns: RequestBuilder */ open class func testBodyWithQueryParamsWithRequestBuilder(query: String, body: User) -> RequestBuilder { - let path = "/fake/body-with-query-params" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/fake/body-with-query-params" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - var urlComponents = URLComponents(string: URLString) - urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ + var localVariableUrlComponents = URLComponents(string: localVariableURLString) + localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ "query": query.encodeToJSON(), ]) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "PUT", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -290,7 +294,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Observable */ - open class func testClientModel(body: Client, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Observable { + open class func testClientModel(body: Client, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> Observable { return Observable.create { observer -> Disposable in testClientModelWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { @@ -313,21 +317,21 @@ open class FakeAPI { - returns: RequestBuilder */ open class func testClientModelWithRequestBuilder(body: Client) -> RequestBuilder { - let path = "/fake" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/fake" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "PATCH", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "PATCH", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -350,7 +354,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Observable */ - open class func testEndpointParameters(number: Double, double: Double, patternWithoutDelimiter: String, byte: Data, integer: Int? = nil, int32: Int? = nil, int64: Int64? = nil, float: Float? = nil, string: String? = nil, binary: URL? = nil, date: Date? = nil, dateTime: Date? = nil, password: String? = nil, callback: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Observable { + open class func testEndpointParameters(number: Double, double: Double, patternWithoutDelimiter: String, byte: Data, integer: Int? = nil, int32: Int? = nil, int64: Int64? = nil, float: Float? = nil, string: String? = nil, binary: URL? = nil, date: Date? = nil, dateTime: Date? = nil, password: String? = nil, callback: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> Observable { return Observable.create { observer -> Disposable in testEndpointParametersWithRequestBuilder(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(apiResponseQueue) { result -> Void in switch result { @@ -389,9 +393,9 @@ open class FakeAPI { - returns: RequestBuilder */ open class func testEndpointParametersWithRequestBuilder(number: Double, double: Double, patternWithoutDelimiter: String, byte: Data, integer: Int? = nil, int32: Int? = nil, int64: Int64? = nil, float: Float? = nil, string: String? = nil, binary: URL? = nil, date: Date? = nil, dateTime: Date? = nil, password: String? = nil, callback: String? = nil) -> RequestBuilder { - let path = "/fake" - let URLString = PetstoreClientAPI.basePath + path - let formParams: [String: Any?] = [ + let localVariablePath = "/fake" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableFormParams: [String: Any?] = [ "integer": integer?.encodeToJSON(), "int32": int32?.encodeToJSON(), "int64": int64?.encodeToJSON(), @@ -408,20 +412,20 @@ open class FakeAPI { "callback": callback?.encodeToJSON(), ] - let nonNullParameters = APIHelper.rejectNil(formParams) - let parameters = APIHelper.convertBoolToString(nonNullParameters) + let localVariableNonNullParameters = APIHelper.rejectNil(localVariableFormParams) + let localVariableParameters = APIHelper.convertBoolToString(localVariableNonNullParameters) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ "Content-Type": "application/x-www-form-urlencoded", ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -505,7 +509,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Observable */ - open class func testEnumParameters(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Observable { + open class func testEnumParameters(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> Observable { return Observable.create { observer -> Disposable in testEnumParametersWithRequestBuilder(enumHeaderStringArray: enumHeaderStringArray, enumHeaderString: enumHeaderString, enumQueryStringArray: enumQueryStringArray, enumQueryString: enumQueryString, enumQueryInteger: enumQueryInteger, enumQueryDouble: enumQueryDouble, enumFormStringArray: enumFormStringArray, enumFormString: enumFormString).execute(apiResponseQueue) { result -> Void in switch result { @@ -535,35 +539,35 @@ open class FakeAPI { - returns: RequestBuilder */ open class func testEnumParametersWithRequestBuilder(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil) -> RequestBuilder { - let path = "/fake" - let URLString = PetstoreClientAPI.basePath + path - let formParams: [String: Any?] = [ + let localVariablePath = "/fake" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableFormParams: [String: Any?] = [ "enum_form_string_array": enumFormStringArray?.encodeToJSON(), "enum_form_string": enumFormString?.encodeToJSON(), ] - let nonNullParameters = APIHelper.rejectNil(formParams) - let parameters = APIHelper.convertBoolToString(nonNullParameters) + let localVariableNonNullParameters = APIHelper.rejectNil(localVariableFormParams) + let localVariableParameters = APIHelper.convertBoolToString(localVariableNonNullParameters) - var urlComponents = URLComponents(string: URLString) - urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ + var localVariableUrlComponents = URLComponents(string: localVariableURLString) + localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ "enum_query_string_array": enumQueryStringArray?.encodeToJSON(), "enum_query_string": enumQueryString?.encodeToJSON(), "enum_query_integer": enumQueryInteger?.encodeToJSON(), "enum_query_double": enumQueryDouble?.encodeToJSON(), ]) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ "Content-Type": "application/x-www-form-urlencoded", "enum_header_string_array": enumHeaderStringArray?.encodeToJSON(), "enum_header_string": enumHeaderString?.encodeToJSON(), ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -578,7 +582,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Observable */ - open class func testGroupParameters(requiredStringGroup: Int, requiredBooleanGroup: Bool, requiredInt64Group: Int64, stringGroup: Int? = nil, booleanGroup: Bool? = nil, int64Group: Int64? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Observable { + open class func testGroupParameters(requiredStringGroup: Int, requiredBooleanGroup: Bool, requiredInt64Group: Int64, stringGroup: Int? = nil, booleanGroup: Bool? = nil, int64Group: Int64? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> Observable { return Observable.create { observer -> Disposable in testGroupParametersWithRequestBuilder(requiredStringGroup: requiredStringGroup, requiredBooleanGroup: requiredBooleanGroup, requiredInt64Group: requiredInt64Group, stringGroup: stringGroup, booleanGroup: booleanGroup, int64Group: int64Group).execute(apiResponseQueue) { result -> Void in switch result { @@ -606,28 +610,28 @@ open class FakeAPI { - returns: RequestBuilder */ open class func testGroupParametersWithRequestBuilder(requiredStringGroup: Int, requiredBooleanGroup: Bool, requiredInt64Group: Int64, stringGroup: Int? = nil, booleanGroup: Bool? = nil, int64Group: Int64? = nil) -> RequestBuilder { - let path = "/fake" - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + let localVariablePath = "/fake" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - var urlComponents = URLComponents(string: URLString) - urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ + var localVariableUrlComponents = URLComponents(string: localVariableURLString) + localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ "required_string_group": requiredStringGroup.encodeToJSON(), "required_int64_group": requiredInt64Group.encodeToJSON(), "string_group": stringGroup?.encodeToJSON(), "int64_group": int64Group?.encodeToJSON(), ]) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ "required_boolean_group": requiredBooleanGroup.encodeToJSON(), "boolean_group": booleanGroup?.encodeToJSON(), ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "DELETE", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -637,7 +641,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Observable */ - open class func testInlineAdditionalProperties(param: [String: String], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Observable { + open class func testInlineAdditionalProperties(param: [String: String], apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> Observable { return Observable.create { observer -> Disposable in testInlineAdditionalPropertiesWithRequestBuilder(param: param).execute(apiResponseQueue) { result -> Void in switch result { @@ -659,21 +663,21 @@ open class FakeAPI { - returns: RequestBuilder */ open class func testInlineAdditionalPropertiesWithRequestBuilder(param: [String: String]) -> RequestBuilder { - let path = "/fake/inline-additionalProperties" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: param) + let localVariablePath = "/fake/inline-additionalProperties" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: param) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -684,7 +688,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Observable */ - open class func testJsonFormData(param: String, param2: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Observable { + open class func testJsonFormData(param: String, param2: String, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> Observable { return Observable.create { observer -> Disposable in testJsonFormDataWithRequestBuilder(param: param, param2: param2).execute(apiResponseQueue) { result -> Void in switch result { @@ -707,27 +711,26 @@ open class FakeAPI { - returns: RequestBuilder */ open class func testJsonFormDataWithRequestBuilder(param: String, param2: String) -> RequestBuilder { - let path = "/fake/jsonFormData" - let URLString = PetstoreClientAPI.basePath + path - let formParams: [String: Any?] = [ + let localVariablePath = "/fake/jsonFormData" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableFormParams: [String: Any?] = [ "param": param.encodeToJSON(), "param2": param2.encodeToJSON(), ] - let nonNullParameters = APIHelper.rejectNil(formParams) - let parameters = APIHelper.convertBoolToString(nonNullParameters) + let localVariableNonNullParameters = APIHelper.rejectNil(localVariableFormParams) + let localVariableParameters = APIHelper.convertBoolToString(localVariableNonNullParameters) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ "Content-Type": "application/x-www-form-urlencoded", ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } - } 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 a0f65c5269e..5cdfe3663d1 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 @@ -7,8 +7,12 @@ import Foundation import RxSwift +#if canImport(AnyCodable) +import AnyCodable +#endif open class FakeClassnameTags123API { + /** To test class name in snake case @@ -16,7 +20,7 @@ open class FakeClassnameTags123API { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Observable */ - open class func testClassname(body: Client, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Observable { + open class func testClassname(body: Client, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> Observable { return Observable.create { observer -> Disposable in testClassnameWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { @@ -42,21 +46,20 @@ open class FakeClassnameTags123API { - returns: RequestBuilder */ open class func testClassnameWithRequestBuilder(body: Client) -> RequestBuilder { - let path = "/fake_classname_test" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/fake_classname_test" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "PATCH", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "PATCH", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } - } 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 bb299e77d8c..024c54a2b2e 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 @@ -7,8 +7,12 @@ import Foundation import RxSwift +#if canImport(AnyCodable) +import AnyCodable +#endif open class PetAPI { + /** Add a new pet to the store @@ -16,7 +20,7 @@ open class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Observable */ - open class func addPet(body: Pet, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Observable { + open class func addPet(body: Pet, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> Observable { return Observable.create { observer -> Disposable in addPetWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { @@ -41,21 +45,21 @@ open class PetAPI { - returns: RequestBuilder */ open class func addPetWithRequestBuilder(body: Pet) -> RequestBuilder { - let path = "/pet" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/pet" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -66,7 +70,7 @@ open class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Observable */ - open class func deletePet(petId: Int64, apiKey: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Observable { + open class func deletePet(petId: Int64, apiKey: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> Observable { return Observable.create { observer -> Disposable in deletePetWithRequestBuilder(petId: petId, apiKey: apiKey).execute(apiResponseQueue) { result -> Void in switch result { @@ -92,24 +96,24 @@ open class PetAPI { - returns: RequestBuilder */ open class func deletePetWithRequestBuilder(petId: Int64, apiKey: String? = nil) -> RequestBuilder { - var path = "/pet/{petId}" + var localVariablePath = "/pet/{petId}" let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))" let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" - path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + localVariablePath = localVariablePath.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ "api_key": apiKey?.encodeToJSON(), ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "DELETE", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -128,7 +132,7 @@ open class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Observable<[Pet]> */ - open class func findPetsByStatus(status: [String], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Observable<[Pet]> { + open class func findPetsByStatus(status: [String], apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> Observable<[Pet]> { return Observable.create { observer -> Disposable in findPetsByStatusWithRequestBuilder(status: status).execute(apiResponseQueue) { result -> Void in switch result { @@ -154,24 +158,24 @@ open class PetAPI { - returns: RequestBuilder<[Pet]> */ open class func findPetsByStatusWithRequestBuilder(status: [String]) -> RequestBuilder<[Pet]> { - let path = "/pet/findByStatus" - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + let localVariablePath = "/pet/findByStatus" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - var urlComponents = URLComponents(string: URLString) - urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ + var localVariableUrlComponents = URLComponents(string: localVariableURLString) + localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ "status": status.encodeToJSON(), ]) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -182,7 +186,7 @@ open class PetAPI { - returns: Observable<[Pet]> */ @available(*, deprecated, message: "This operation is deprecated.") - open class func findPetsByTags(tags: [String], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Observable<[Pet]> { + open class func findPetsByTags(tags: [String], apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> Observable<[Pet]> { return Observable.create { observer -> Disposable in findPetsByTagsWithRequestBuilder(tags: tags).execute(apiResponseQueue) { result -> Void in switch result { @@ -209,24 +213,24 @@ open class PetAPI { */ @available(*, deprecated, message: "This operation is deprecated.") open class func findPetsByTagsWithRequestBuilder(tags: [String]) -> RequestBuilder<[Pet]> { - let path = "/pet/findByTags" - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + let localVariablePath = "/pet/findByTags" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - var urlComponents = URLComponents(string: URLString) - urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ + var localVariableUrlComponents = URLComponents(string: localVariableURLString) + localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ "tags": tags.encodeToJSON(), ]) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -236,7 +240,7 @@ open class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Observable */ - open class func getPetById(petId: Int64, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Observable { + open class func getPetById(petId: Int64, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> Observable { return Observable.create { observer -> Disposable in getPetByIdWithRequestBuilder(petId: petId).execute(apiResponseQueue) { result -> Void in switch result { @@ -262,24 +266,24 @@ open class PetAPI { - returns: RequestBuilder */ open class func getPetByIdWithRequestBuilder(petId: Int64) -> RequestBuilder { - var path = "/pet/{petId}" + var localVariablePath = "/pet/{petId}" let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))" let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" - path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + localVariablePath = localVariablePath.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -289,7 +293,7 @@ open class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Observable */ - open class func updatePet(body: Pet, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Observable { + open class func updatePet(body: Pet, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> Observable { return Observable.create { observer -> Disposable in updatePetWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { @@ -314,21 +318,21 @@ open class PetAPI { - returns: RequestBuilder */ open class func updatePetWithRequestBuilder(body: Pet) -> RequestBuilder { - let path = "/pet" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/pet" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "PUT", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -340,7 +344,7 @@ open class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Observable */ - open class func updatePetWithForm(petId: Int64, name: String? = nil, status: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Observable { + open class func updatePetWithForm(petId: Int64, name: String? = nil, status: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> Observable { return Observable.create { observer -> Disposable in updatePetWithFormWithRequestBuilder(petId: petId, name: name, status: status).execute(apiResponseQueue) { result -> Void in switch result { @@ -367,30 +371,30 @@ open class PetAPI { - returns: RequestBuilder */ open class func updatePetWithFormWithRequestBuilder(petId: Int64, name: String? = nil, status: String? = nil) -> RequestBuilder { - var path = "/pet/{petId}" + var localVariablePath = "/pet/{petId}" let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))" let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" - path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path - let formParams: [String: Any?] = [ + localVariablePath = localVariablePath.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableFormParams: [String: Any?] = [ "name": name?.encodeToJSON(), "status": status?.encodeToJSON(), ] - let nonNullParameters = APIHelper.rejectNil(formParams) - let parameters = APIHelper.convertBoolToString(nonNullParameters) + let localVariableNonNullParameters = APIHelper.rejectNil(localVariableFormParams) + let localVariableParameters = APIHelper.convertBoolToString(localVariableNonNullParameters) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ "Content-Type": "application/x-www-form-urlencoded", ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -402,7 +406,7 @@ open class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Observable */ - open class func uploadFile(petId: Int64, additionalMetadata: String? = nil, file: URL? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Observable { + open class func uploadFile(petId: Int64, additionalMetadata: String? = nil, file: URL? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> Observable { return Observable.create { observer -> Disposable in uploadFileWithRequestBuilder(petId: petId, additionalMetadata: additionalMetadata, file: file).execute(apiResponseQueue) { result -> Void in switch result { @@ -429,30 +433,30 @@ open class PetAPI { - returns: RequestBuilder */ open class func uploadFileWithRequestBuilder(petId: Int64, additionalMetadata: String? = nil, file: URL? = nil) -> RequestBuilder { - var path = "/pet/{petId}/uploadImage" + var localVariablePath = "/pet/{petId}/uploadImage" let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))" let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" - path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path - let formParams: [String: Any?] = [ + localVariablePath = localVariablePath.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableFormParams: [String: Any?] = [ "additionalMetadata": additionalMetadata?.encodeToJSON(), "file": file?.encodeToJSON(), ] - let nonNullParameters = APIHelper.rejectNil(formParams) - let parameters = APIHelper.convertBoolToString(nonNullParameters) + let localVariableNonNullParameters = APIHelper.rejectNil(localVariableFormParams) + let localVariableParameters = APIHelper.convertBoolToString(localVariableNonNullParameters) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ "Content-Type": "multipart/form-data", ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -464,7 +468,7 @@ open class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Observable */ - open class func uploadFileWithRequiredFile(petId: Int64, requiredFile: URL, additionalMetadata: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Observable { + open class func uploadFileWithRequiredFile(petId: Int64, requiredFile: URL, additionalMetadata: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> Observable { return Observable.create { observer -> Disposable in uploadFileWithRequiredFileWithRequestBuilder(petId: petId, requiredFile: requiredFile, additionalMetadata: additionalMetadata).execute(apiResponseQueue) { result -> Void in switch result { @@ -491,30 +495,29 @@ open class PetAPI { - returns: RequestBuilder */ open class func uploadFileWithRequiredFileWithRequestBuilder(petId: Int64, requiredFile: URL, additionalMetadata: String? = nil) -> RequestBuilder { - var path = "/fake/{petId}/uploadImageWithRequiredFile" + var localVariablePath = "/fake/{petId}/uploadImageWithRequiredFile" let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))" let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" - path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path - let formParams: [String: Any?] = [ + localVariablePath = localVariablePath.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableFormParams: [String: Any?] = [ "additionalMetadata": additionalMetadata?.encodeToJSON(), "requiredFile": requiredFile.encodeToJSON(), ] - let nonNullParameters = APIHelper.rejectNil(formParams) - let parameters = APIHelper.convertBoolToString(nonNullParameters) + let localVariableNonNullParameters = APIHelper.rejectNil(localVariableFormParams) + let localVariableParameters = APIHelper.convertBoolToString(localVariableNonNullParameters) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ "Content-Type": "multipart/form-data", ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } - } diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift index 0f1e6023e17..e7f0482ec73 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift @@ -7,8 +7,12 @@ import Foundation import RxSwift +#if canImport(AnyCodable) +import AnyCodable +#endif open class StoreAPI { + /** Delete purchase order by ID @@ -16,7 +20,7 @@ open class StoreAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Observable */ - open class func deleteOrder(orderId: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Observable { + open class func deleteOrder(orderId: String, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> Observable { return Observable.create { observer -> Disposable in deleteOrderWithRequestBuilder(orderId: orderId).execute(apiResponseQueue) { result -> Void in switch result { @@ -39,24 +43,24 @@ open class StoreAPI { - returns: RequestBuilder */ open class func deleteOrderWithRequestBuilder(orderId: String) -> RequestBuilder { - var path = "/store/order/{order_id}" + var localVariablePath = "/store/order/{order_id}" let orderIdPreEscape = "\(APIHelper.mapValueToPathItem(orderId))" let orderIdPostEscape = orderIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" - path = path.replacingOccurrences(of: "{order_id}", with: orderIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + localVariablePath = localVariablePath.replacingOccurrences(of: "{order_id}", with: orderIdPostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "DELETE", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -65,7 +69,7 @@ open class StoreAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Observable<[String: Int]> */ - open class func getInventory(apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Observable<[String: Int]> { + open class func getInventory(apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> Observable<[String: Int]> { return Observable.create { observer -> Disposable in getInventoryWithRequestBuilder().execute(apiResponseQueue) { result -> Void in switch result { @@ -90,21 +94,21 @@ open class StoreAPI { - returns: RequestBuilder<[String: Int]> */ open class func getInventoryWithRequestBuilder() -> RequestBuilder<[String: Int]> { - let path = "/store/inventory" - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + let localVariablePath = "/store/inventory" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder<[String: Int]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder<[String: Int]>.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -114,7 +118,7 @@ open class StoreAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Observable */ - open class func getOrderById(orderId: Int64, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Observable { + open class func getOrderById(orderId: Int64, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> Observable { return Observable.create { observer -> Disposable in getOrderByIdWithRequestBuilder(orderId: orderId).execute(apiResponseQueue) { result -> Void in switch result { @@ -137,24 +141,24 @@ open class StoreAPI { - returns: RequestBuilder */ open class func getOrderByIdWithRequestBuilder(orderId: Int64) -> RequestBuilder { - var path = "/store/order/{order_id}" + var localVariablePath = "/store/order/{order_id}" let orderIdPreEscape = "\(APIHelper.mapValueToPathItem(orderId))" let orderIdPostEscape = orderIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" - path = path.replacingOccurrences(of: "{order_id}", with: orderIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + localVariablePath = localVariablePath.replacingOccurrences(of: "{order_id}", with: orderIdPostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -164,7 +168,7 @@ open class StoreAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Observable */ - open class func placeOrder(body: Order, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Observable { + open class func placeOrder(body: Order, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> Observable { return Observable.create { observer -> Disposable in placeOrderWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { @@ -186,21 +190,20 @@ open class StoreAPI { - returns: RequestBuilder */ open class func placeOrderWithRequestBuilder(body: Order) -> RequestBuilder { - let path = "/store/order" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/store/order" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } - } diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift index 18bf71fc41c..8df7e2e839f 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift @@ -7,8 +7,12 @@ import Foundation import RxSwift +#if canImport(AnyCodable) +import AnyCodable +#endif open class UserAPI { + /** Create user @@ -16,7 +20,7 @@ open class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Observable */ - open class func createUser(body: User, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Observable { + open class func createUser(body: User, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> Observable { return Observable.create { observer -> Disposable in createUserWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { @@ -39,21 +43,21 @@ open class UserAPI { - returns: RequestBuilder */ open class func createUserWithRequestBuilder(body: User) -> RequestBuilder { - let path = "/user" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/user" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -63,7 +67,7 @@ open class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Observable */ - open class func createUsersWithArrayInput(body: [User], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Observable { + open class func createUsersWithArrayInput(body: [User], apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> Observable { return Observable.create { observer -> Disposable in createUsersWithArrayInputWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { @@ -85,21 +89,21 @@ open class UserAPI { - returns: RequestBuilder */ open class func createUsersWithArrayInputWithRequestBuilder(body: [User]) -> RequestBuilder { - let path = "/user/createWithArray" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/user/createWithArray" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -109,7 +113,7 @@ open class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Observable */ - open class func createUsersWithListInput(body: [User], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Observable { + open class func createUsersWithListInput(body: [User], apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> Observable { return Observable.create { observer -> Disposable in createUsersWithListInputWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { @@ -131,21 +135,21 @@ open class UserAPI { - returns: RequestBuilder */ open class func createUsersWithListInputWithRequestBuilder(body: [User]) -> RequestBuilder { - let path = "/user/createWithList" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/user/createWithList" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -155,7 +159,7 @@ open class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Observable */ - open class func deleteUser(username: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Observable { + open class func deleteUser(username: String, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> Observable { return Observable.create { observer -> Disposable in deleteUserWithRequestBuilder(username: username).execute(apiResponseQueue) { result -> Void in switch result { @@ -178,24 +182,24 @@ open class UserAPI { - returns: RequestBuilder */ open class func deleteUserWithRequestBuilder(username: String) -> RequestBuilder { - var path = "/user/{username}" + var localVariablePath = "/user/{username}" let usernamePreEscape = "\(APIHelper.mapValueToPathItem(username))" let usernamePostEscape = usernamePreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" - path = path.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + localVariablePath = localVariablePath.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "DELETE", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -205,7 +209,7 @@ open class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Observable */ - open class func getUserByName(username: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Observable { + open class func getUserByName(username: String, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> Observable { return Observable.create { observer -> Disposable in getUserByNameWithRequestBuilder(username: username).execute(apiResponseQueue) { result -> Void in switch result { @@ -227,24 +231,24 @@ open class UserAPI { - returns: RequestBuilder */ open class func getUserByNameWithRequestBuilder(username: String) -> RequestBuilder { - var path = "/user/{username}" + var localVariablePath = "/user/{username}" let usernamePreEscape = "\(APIHelper.mapValueToPathItem(username))" let usernamePostEscape = usernamePreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" - path = path.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + localVariablePath = localVariablePath.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -255,7 +259,7 @@ open class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Observable */ - open class func loginUser(username: String, password: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Observable { + open class func loginUser(username: String, password: String, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> Observable { return Observable.create { observer -> Disposable in loginUserWithRequestBuilder(username: username, password: password).execute(apiResponseQueue) { result -> Void in switch result { @@ -279,25 +283,25 @@ open class UserAPI { - returns: RequestBuilder */ open class func loginUserWithRequestBuilder(username: String, password: String) -> RequestBuilder { - let path = "/user/login" - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + let localVariablePath = "/user/login" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - var urlComponents = URLComponents(string: URLString) - urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ + var localVariableUrlComponents = URLComponents(string: localVariableURLString) + localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ "username": username.encodeToJSON(), "password": password.encodeToJSON(), ]) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -306,7 +310,7 @@ open class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Observable */ - open class func logoutUser(apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Observable { + open class func logoutUser(apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> Observable { return Observable.create { observer -> Disposable in logoutUserWithRequestBuilder().execute(apiResponseQueue) { result -> Void in switch result { @@ -327,21 +331,21 @@ open class UserAPI { - returns: RequestBuilder */ open class func logoutUserWithRequestBuilder() -> RequestBuilder { - let path = "/user/logout" - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + let localVariablePath = "/user/logout" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -352,7 +356,7 @@ open class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Observable */ - open class func updateUser(username: String, body: User, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Observable { + open class func updateUser(username: String, body: User, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue) -> Observable { return Observable.create { observer -> Disposable in updateUserWithRequestBuilder(username: username, body: body).execute(apiResponseQueue) { result -> Void in switch result { @@ -376,24 +380,23 @@ open class UserAPI { - returns: RequestBuilder */ open class func updateUserWithRequestBuilder(username: String, body: User) -> RequestBuilder { - var path = "/user/{username}" + var localVariablePath = "/user/{username}" let usernamePreEscape = "\(APIHelper.mapValueToPathItem(username))" let usernamePostEscape = usernamePreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" - path = path.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + localVariablePath = localVariablePath.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "PUT", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } - } diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Configuration.swift b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Configuration.swift index 18edabbed78..8fb05331889 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Configuration.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Configuration.swift @@ -7,6 +7,7 @@ import Foundation open class Configuration { + // This value is used to configure the date formatter that is used to serialize dates into JSON format. // You must set it prior to encoding any dates, and it will only be read once. @available(*, unavailable, message: "To set a different date format, use CodableHelper.dateFormatter instead.") diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Extensions.swift b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Extensions.swift index 3aef2d1d6c5..dc0913d093f 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Extensions.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Extensions.swift @@ -5,7 +5,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif extension Bool: JSONEncodable { func encodeToJSON() -> Any { return self as Any } @@ -93,135 +95,8 @@ extension UUID: JSONEncodable { } } -extension String: CodingKey { - - public var stringValue: String { - return self - } - - public init?(stringValue: String) { - self.init(stringLiteral: stringValue) - } - - public var intValue: Int? { - return nil - } - - public init?(intValue: Int) { - return nil - } - -} - -extension KeyedEncodingContainerProtocol { - - public mutating func encodeArray(_ values: [T], forKey key: Self.Key) throws where T: Encodable { - var arrayContainer = nestedUnkeyedContainer(forKey: key) - try arrayContainer.encode(contentsOf: values) - } - - public mutating func encodeArrayIfPresent(_ values: [T]?, forKey key: Self.Key) throws where T: Encodable { - if let values = values { - try encodeArray(values, forKey: key) - } - } - - public mutating func encodeMap(_ pairs: [Self.Key: T]) throws where T: Encodable { - for (key, value) in pairs { - try encode(value, forKey: key) - } - } - - public mutating func encodeMapIfPresent(_ pairs: [Self.Key: T]?) throws where T: Encodable { - if let pairs = pairs { - try encodeMap(pairs) - } - } - -} - -extension KeyedDecodingContainerProtocol { - - public func decodeArray(_ type: T.Type, forKey key: Self.Key) throws -> [T] where T: Decodable { - var tmpArray = [T]() - - var nestedContainer = try nestedUnkeyedContainer(forKey: key) - while !nestedContainer.isAtEnd { - let arrayValue = try nestedContainer.decode(T.self) - tmpArray.append(arrayValue) - } - - return tmpArray - } - - public func decodeArrayIfPresent(_ type: T.Type, forKey key: Self.Key) throws -> [T]? where T: Decodable { - var tmpArray: [T]? - - if contains(key) { - tmpArray = try decodeArray(T.self, forKey: key) - } - - return tmpArray - } - - public func decodeMap(_ type: T.Type, excludedKeys: Set) throws -> [Self.Key: T] where T: Decodable { - var map: [Self.Key: T] = [:] - - for key in allKeys { - if !excludedKeys.contains(key) { - let value = try decode(T.self, forKey: key) - map[key] = value - } - } - - return map - } - -} - extension HTTPURLResponse { var isStatusCodeSuccessful: Bool { return Array(200 ..< 300).contains(statusCode) } } - -extension AnyCodable: Hashable { - public func hash(into hasher: inout Hasher) { - switch value { - case let value as Bool: - hasher.combine(value) - case let value as Int: - hasher.combine(value) - case let value as Int8: - hasher.combine(value) - case let value as Int16: - hasher.combine(value) - case let value as Int32: - hasher.combine(value) - case let value as Int64: - hasher.combine(value) - case let value as UInt: - hasher.combine(value) - case let value as UInt8: - hasher.combine(value) - case let value as UInt16: - hasher.combine(value) - case let value as UInt32: - hasher.combine(value) - case let value as UInt64: - hasher.combine(value) - case let value as Float: - hasher.combine(value) - case let value as Double: - hasher.combine(value) - case let value as String: - hasher.combine(value) - case let value as [String: AnyCodable]: - hasher.combine(value) - case let value as [AnyCodable]: - hasher.combine(value) - default: - hasher.combine(0) - } - } -} \ No newline at end of file diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesClass.swift b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesClass.swift index 75ab9bc8d0a..621afb93561 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesClass.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesClass.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct AdditionalPropertiesClass: Codable, Hashable { @@ -17,6 +19,7 @@ public struct AdditionalPropertiesClass: Codable, Hashable { self.mapString = mapString self.mapMapString = mapMapString } + public enum CodingKeys: String, CodingKey, CaseIterable { case mapString = "map_string" case mapMapString = "map_map_string" @@ -29,7 +32,5 @@ public struct AdditionalPropertiesClass: Codable, Hashable { try container.encodeIfPresent(mapString, forKey: .mapString) try container.encodeIfPresent(mapMapString, forKey: .mapMapString) } - - - } + diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Animal.swift b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Animal.swift index 0f825cf24d0..cdd4f5335b9 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Animal.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Animal.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct Animal: Codable, Hashable { @@ -17,6 +19,7 @@ public struct Animal: Codable, Hashable { self.className = className self.color = color } + public enum CodingKeys: String, CodingKey, CaseIterable { case className case color @@ -29,7 +32,5 @@ public struct Animal: Codable, Hashable { try container.encode(className, forKey: .className) try container.encodeIfPresent(color, forKey: .color) } - - - } + diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/AnimalFarm.swift b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/AnimalFarm.swift index b20b894a1ad..a0b09cb9761 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/AnimalFarm.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/AnimalFarm.swift @@ -6,6 +6,8 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public typealias AnimalFarm = [Animal] diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift index 2b66af2dc94..c365505ab9d 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct ApiResponse: Codable, Hashable { @@ -19,6 +21,7 @@ public struct ApiResponse: Codable, Hashable { self.type = type self.message = message } + public enum CodingKeys: String, CodingKey, CaseIterable { case code case type @@ -33,7 +36,5 @@ public struct ApiResponse: Codable, Hashable { try container.encodeIfPresent(type, forKey: .type) try container.encodeIfPresent(message, forKey: .message) } - - - } + diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfArrayOfNumberOnly.swift b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfArrayOfNumberOnly.swift index 06f0640475c..226f7456181 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfArrayOfNumberOnly.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfArrayOfNumberOnly.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct ArrayOfArrayOfNumberOnly: Codable, Hashable { @@ -15,6 +17,7 @@ public struct ArrayOfArrayOfNumberOnly: Codable, Hashable { public init(arrayArrayNumber: [[Double]]? = nil) { self.arrayArrayNumber = arrayArrayNumber } + public enum CodingKeys: String, CodingKey, CaseIterable { case arrayArrayNumber = "ArrayArrayNumber" } @@ -25,7 +28,5 @@ public struct ArrayOfArrayOfNumberOnly: Codable, Hashable { var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(arrayArrayNumber, forKey: .arrayArrayNumber) } - - - } + diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfNumberOnly.swift b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfNumberOnly.swift index 8c50c7fa1e4..39831127871 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfNumberOnly.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfNumberOnly.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct ArrayOfNumberOnly: Codable, Hashable { @@ -15,6 +17,7 @@ public struct ArrayOfNumberOnly: Codable, Hashable { public init(arrayNumber: [Double]? = nil) { self.arrayNumber = arrayNumber } + public enum CodingKeys: String, CodingKey, CaseIterable { case arrayNumber = "ArrayNumber" } @@ -25,7 +28,5 @@ public struct ArrayOfNumberOnly: Codable, Hashable { var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(arrayNumber, forKey: .arrayNumber) } - - - } + diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayTest.swift b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayTest.swift index 461ec7cd9ac..8865d76bef2 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayTest.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayTest.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct ArrayTest: Codable, Hashable { @@ -19,6 +21,7 @@ public struct ArrayTest: Codable, Hashable { self.arrayArrayOfInteger = arrayArrayOfInteger self.arrayArrayOfModel = arrayArrayOfModel } + public enum CodingKeys: String, CodingKey, CaseIterable { case arrayOfString = "array_of_string" case arrayArrayOfInteger = "array_array_of_integer" @@ -33,7 +36,5 @@ public struct ArrayTest: Codable, Hashable { try container.encodeIfPresent(arrayArrayOfInteger, forKey: .arrayArrayOfInteger) try container.encodeIfPresent(arrayArrayOfModel, forKey: .arrayArrayOfModel) } - - - } + diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Capitalization.swift b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Capitalization.swift index fbe62983d5e..71cd93bce5f 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Capitalization.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Capitalization.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct Capitalization: Codable, Hashable { @@ -26,6 +28,7 @@ public struct Capitalization: Codable, Hashable { self.sCAETHFlowPoints = sCAETHFlowPoints self.ATT_NAME = ATT_NAME } + public enum CodingKeys: String, CodingKey, CaseIterable { case smallCamel case capitalCamel = "CapitalCamel" @@ -46,7 +49,5 @@ public struct Capitalization: Codable, Hashable { try container.encodeIfPresent(sCAETHFlowPoints, forKey: .sCAETHFlowPoints) try container.encodeIfPresent(ATT_NAME, forKey: .ATT_NAME) } - - - } + diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Cat.swift b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Cat.swift index 7f3a86932f1..457e04bd475 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Cat.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Cat.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct Cat: Codable, Hashable { @@ -19,6 +21,7 @@ public struct Cat: Codable, Hashable { self.color = color self.declawed = declawed } + public enum CodingKeys: String, CodingKey, CaseIterable { case className case color @@ -33,7 +36,5 @@ public struct Cat: Codable, Hashable { try container.encodeIfPresent(color, forKey: .color) try container.encodeIfPresent(declawed, forKey: .declawed) } - - - } + diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/CatAllOf.swift b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/CatAllOf.swift index 8df23954832..8caebb1c206 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/CatAllOf.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/CatAllOf.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct CatAllOf: Codable, Hashable { @@ -15,6 +17,7 @@ public struct CatAllOf: Codable, Hashable { public init(declawed: Bool? = nil) { self.declawed = declawed } + public enum CodingKeys: String, CodingKey, CaseIterable { case declawed } @@ -25,7 +28,5 @@ public struct CatAllOf: Codable, Hashable { var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(declawed, forKey: .declawed) } - - - } + diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Category.swift b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Category.swift index 4109db4d1ef..89016ca353d 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Category.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Category.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct Category: Codable, Hashable { @@ -17,6 +19,7 @@ public struct Category: Codable, Hashable { self.id = id self.name = name } + public enum CodingKeys: String, CodingKey, CaseIterable { case id case name @@ -29,7 +32,5 @@ public struct Category: Codable, Hashable { try container.encodeIfPresent(id, forKey: .id) try container.encode(name, forKey: .name) } - - - } + diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/ClassModel.swift b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/ClassModel.swift index 44ac733f2c5..6a72957b687 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/ClassModel.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/ClassModel.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif /** Model for testing model with \"_class\" property */ public struct ClassModel: Codable, Hashable { @@ -16,6 +18,7 @@ public struct ClassModel: Codable, Hashable { public init(`class`: String? = nil) { self.`class` = `class` } + public enum CodingKeys: String, CodingKey, CaseIterable { case `class` = "_class" } @@ -26,7 +29,5 @@ public struct ClassModel: Codable, Hashable { var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(`class`, forKey: .`class`) } - - - } + diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Client.swift b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Client.swift index 7d6eff2ffe1..60dbc5dc5c1 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Client.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Client.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct Client: Codable, Hashable { @@ -15,6 +17,7 @@ public struct Client: Codable, Hashable { public init(client: String? = nil) { self.client = client } + public enum CodingKeys: String, CodingKey, CaseIterable { case client } @@ -25,7 +28,5 @@ public struct Client: Codable, Hashable { var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(client, forKey: .client) } - - - } + diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Dog.swift b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Dog.swift index b5f2bcea38a..658732a7f36 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Dog.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Dog.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct Dog: Codable, Hashable { @@ -19,6 +21,7 @@ public struct Dog: Codable, Hashable { self.color = color self.breed = breed } + public enum CodingKeys: String, CodingKey, CaseIterable { case className case color @@ -33,7 +36,5 @@ public struct Dog: Codable, Hashable { try container.encodeIfPresent(color, forKey: .color) try container.encodeIfPresent(breed, forKey: .breed) } - - - } + diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/DogAllOf.swift b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/DogAllOf.swift index 1bfa23d7bc6..82b0dedf35b 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/DogAllOf.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/DogAllOf.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct DogAllOf: Codable, Hashable { @@ -15,6 +17,7 @@ public struct DogAllOf: Codable, Hashable { public init(breed: String? = nil) { self.breed = breed } + public enum CodingKeys: String, CodingKey, CaseIterable { case breed } @@ -25,7 +28,5 @@ public struct DogAllOf: Codable, Hashable { var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(breed, forKey: .breed) } - - - } + diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumArrays.swift b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumArrays.swift index 73368c42143..1d8ce99539c 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumArrays.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumArrays.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct EnumArrays: Codable, Hashable { @@ -25,6 +27,7 @@ public struct EnumArrays: Codable, Hashable { self.justSymbol = justSymbol self.arrayEnum = arrayEnum } + public enum CodingKeys: String, CodingKey, CaseIterable { case justSymbol = "just_symbol" case arrayEnum = "array_enum" @@ -37,7 +40,5 @@ public struct EnumArrays: Codable, Hashable { try container.encodeIfPresent(justSymbol, forKey: .justSymbol) try container.encodeIfPresent(arrayEnum, forKey: .arrayEnum) } - - - } + diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumClass.swift b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumClass.swift index ab01cf297f8..6ea2895aee5 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumClass.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumClass.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public enum EnumClass: String, Codable, CaseIterable { case abc = "_abc" diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumTest.swift b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumTest.swift index 60a81bcac77..8c8bca49774 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumTest.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumTest.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct EnumTest: Codable, Hashable { @@ -41,6 +43,7 @@ public struct EnumTest: Codable, Hashable { self.enumNumber = enumNumber self.outerEnum = outerEnum } + public enum CodingKeys: String, CodingKey, CaseIterable { case enumString = "enum_string" case enumStringRequired = "enum_string_required" @@ -59,7 +62,5 @@ public struct EnumTest: Codable, Hashable { try container.encodeIfPresent(enumNumber, forKey: .enumNumber) try container.encodeIfPresent(outerEnum, forKey: .outerEnum) } - - - } + diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/File.swift b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/File.swift index 90283656d1b..05dd5b1a825 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/File.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/File.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif /** Must be named `File` for test. */ public struct File: Codable, Hashable { @@ -17,6 +19,7 @@ public struct File: Codable, Hashable { public init(sourceURI: String? = nil) { self.sourceURI = sourceURI } + public enum CodingKeys: String, CodingKey, CaseIterable { case sourceURI } @@ -27,7 +30,5 @@ public struct File: Codable, Hashable { var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(sourceURI, forKey: .sourceURI) } - - - } + diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/FileSchemaTestClass.swift b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/FileSchemaTestClass.swift index cff92673bbe..3ca66a31359 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/FileSchemaTestClass.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/FileSchemaTestClass.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct FileSchemaTestClass: Codable, Hashable { @@ -17,6 +19,7 @@ public struct FileSchemaTestClass: Codable, Hashable { self.file = file self.files = files } + public enum CodingKeys: String, CodingKey, CaseIterable { case file case files @@ -29,7 +32,5 @@ public struct FileSchemaTestClass: Codable, Hashable { try container.encodeIfPresent(file, forKey: .file) try container.encodeIfPresent(files, forKey: .files) } - - - } + diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/FormatTest.swift b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/FormatTest.swift index fc86676eec3..a7a4b39e720 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/FormatTest.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/FormatTest.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct FormatTest: Codable, Hashable { @@ -39,6 +41,7 @@ public struct FormatTest: Codable, Hashable { self.uuid = uuid self.password = password } + public enum CodingKeys: String, CodingKey, CaseIterable { case integer case int32 @@ -73,7 +76,5 @@ public struct FormatTest: Codable, Hashable { try container.encodeIfPresent(uuid, forKey: .uuid) try container.encode(password, forKey: .password) } - - - } + diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/HasOnlyReadOnly.swift b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/HasOnlyReadOnly.swift index d7960f5c800..54ed8a723c6 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/HasOnlyReadOnly.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/HasOnlyReadOnly.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct HasOnlyReadOnly: Codable, Hashable { @@ -17,6 +19,7 @@ public struct HasOnlyReadOnly: Codable, Hashable { self.bar = bar self.foo = foo } + public enum CodingKeys: String, CodingKey, CaseIterable { case bar case foo @@ -29,7 +32,5 @@ public struct HasOnlyReadOnly: Codable, Hashable { try container.encodeIfPresent(bar, forKey: .bar) try container.encodeIfPresent(foo, forKey: .foo) } - - - } + diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/List.swift b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/List.swift index c5d4f2cae56..67e3048469f 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/List.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/List.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct List: Codable, Hashable { @@ -15,6 +17,7 @@ public struct List: Codable, Hashable { public init(_123list: String? = nil) { self._123list = _123list } + public enum CodingKeys: String, CodingKey, CaseIterable { case _123list = "123-list" } @@ -25,7 +28,5 @@ public struct List: Codable, Hashable { var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(_123list, forKey: ._123list) } - - - } + diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/MapTest.swift b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/MapTest.swift index b54bd01e5dc..1e728fcdf58 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/MapTest.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/MapTest.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct MapTest: Codable, Hashable { @@ -25,6 +27,7 @@ public struct MapTest: Codable, Hashable { self.directMap = directMap self.indirectMap = indirectMap } + public enum CodingKeys: String, CodingKey, CaseIterable { case mapMapOfString = "map_map_of_string" case mapOfEnumString = "map_of_enum_string" @@ -41,7 +44,5 @@ public struct MapTest: Codable, Hashable { try container.encodeIfPresent(directMap, forKey: .directMap) try container.encodeIfPresent(indirectMap, forKey: .indirectMap) } - - - } + diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/MixedPropertiesAndAdditionalPropertiesClass.swift b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/MixedPropertiesAndAdditionalPropertiesClass.swift index c8f639ef43d..c79ca459217 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/MixedPropertiesAndAdditionalPropertiesClass.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/MixedPropertiesAndAdditionalPropertiesClass.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct MixedPropertiesAndAdditionalPropertiesClass: Codable, Hashable { @@ -19,6 +21,7 @@ public struct MixedPropertiesAndAdditionalPropertiesClass: Codable, Hashable { self.dateTime = dateTime self.map = map } + public enum CodingKeys: String, CodingKey, CaseIterable { case uuid case dateTime @@ -33,7 +36,5 @@ public struct MixedPropertiesAndAdditionalPropertiesClass: Codable, Hashable { try container.encodeIfPresent(dateTime, forKey: .dateTime) try container.encodeIfPresent(map, forKey: .map) } - - - } + diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Model200Response.swift b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Model200Response.swift index 9b7e3c46d8c..7d15d45c21a 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Model200Response.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Model200Response.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif /** Model for testing model name starting with number */ public struct Model200Response: Codable, Hashable { @@ -18,6 +20,7 @@ public struct Model200Response: Codable, Hashable { self.name = name self.`class` = `class` } + public enum CodingKeys: String, CodingKey, CaseIterable { case name case `class` = "class" @@ -30,7 +33,5 @@ public struct Model200Response: Codable, Hashable { try container.encodeIfPresent(name, forKey: .name) try container.encodeIfPresent(`class`, forKey: .`class`) } - - - } + diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Name.swift b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Name.swift index 84a40e1c101..a28f46a33ce 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Name.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Name.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif /** Model for testing model name same as property name */ public struct Name: Codable, Hashable { @@ -22,6 +24,7 @@ public struct Name: Codable, Hashable { self.property = property self._123number = _123number } + public enum CodingKeys: String, CodingKey, CaseIterable { case name case snakeCase = "snake_case" @@ -38,7 +41,5 @@ public struct Name: Codable, Hashable { try container.encodeIfPresent(property, forKey: .property) try container.encodeIfPresent(_123number, forKey: ._123number) } - - - } + diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/NumberOnly.swift b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/NumberOnly.swift index 710f41648f9..87ceb64bb97 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/NumberOnly.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/NumberOnly.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct NumberOnly: Codable, Hashable { @@ -15,6 +17,7 @@ public struct NumberOnly: Codable, Hashable { public init(justNumber: Double? = nil) { self.justNumber = justNumber } + public enum CodingKeys: String, CodingKey, CaseIterable { case justNumber = "JustNumber" } @@ -25,7 +28,5 @@ public struct NumberOnly: Codable, Hashable { var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(justNumber, forKey: .justNumber) } - - - } + diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Order.swift b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Order.swift index 15726ab16a4..e2eeced4c57 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Order.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Order.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct Order: Codable, Hashable { @@ -31,6 +33,7 @@ public struct Order: Codable, Hashable { self.status = status self.complete = complete } + public enum CodingKeys: String, CodingKey, CaseIterable { case id case petId @@ -51,7 +54,5 @@ public struct Order: Codable, Hashable { try container.encodeIfPresent(status, forKey: .status) try container.encodeIfPresent(complete, forKey: .complete) } - - - } + diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/OuterComposite.swift b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/OuterComposite.swift index 36904afbd50..edeaccaeaa6 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/OuterComposite.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/OuterComposite.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct OuterComposite: Codable, Hashable { @@ -19,6 +21,7 @@ public struct OuterComposite: Codable, Hashable { self.myString = myString self.myBoolean = myBoolean } + public enum CodingKeys: String, CodingKey, CaseIterable { case myNumber = "my_number" case myString = "my_string" @@ -33,7 +36,5 @@ public struct OuterComposite: Codable, Hashable { try container.encodeIfPresent(myString, forKey: .myString) try container.encodeIfPresent(myBoolean, forKey: .myBoolean) } - - - } + diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/OuterEnum.swift b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/OuterEnum.swift index 9bd6f3bef8f..76c34b3c2ce 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/OuterEnum.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/OuterEnum.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public enum OuterEnum: String, Codable, CaseIterable { case placed = "placed" diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Pet.swift b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Pet.swift index 7a1c2826a19..ddd1186b891 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Pet.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Pet.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct Pet: Codable, Hashable { @@ -31,6 +33,7 @@ public struct Pet: Codable, Hashable { self.tags = tags self.status = status } + public enum CodingKeys: String, CodingKey, CaseIterable { case id case category @@ -51,7 +54,5 @@ public struct Pet: Codable, Hashable { try container.encodeIfPresent(tags, forKey: .tags) try container.encodeIfPresent(status, forKey: .status) } - - - } + diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/ReadOnlyFirst.swift b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/ReadOnlyFirst.swift index 38fb57af328..57ba3f577c8 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/ReadOnlyFirst.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/ReadOnlyFirst.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct ReadOnlyFirst: Codable, Hashable { @@ -17,6 +19,7 @@ public struct ReadOnlyFirst: Codable, Hashable { self.bar = bar self.baz = baz } + public enum CodingKeys: String, CodingKey, CaseIterable { case bar case baz @@ -29,7 +32,5 @@ public struct ReadOnlyFirst: Codable, Hashable { try container.encodeIfPresent(bar, forKey: .bar) try container.encodeIfPresent(baz, forKey: .baz) } - - - } + diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Return.swift b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Return.swift index 91d2d536a7b..bda0c791d83 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Return.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Return.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif /** Model for testing reserved words */ public struct Return: Codable, Hashable { @@ -16,6 +18,7 @@ public struct Return: Codable, Hashable { public init(`return`: Int? = nil) { self.`return` = `return` } + public enum CodingKeys: String, CodingKey, CaseIterable { case `return` = "return" } @@ -26,7 +29,5 @@ public struct Return: Codable, Hashable { var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(`return`, forKey: .`return`) } - - - } + diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/SpecialModelName.swift b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/SpecialModelName.swift index 18747e071bc..bfe9723f888 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/SpecialModelName.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/SpecialModelName.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct SpecialModelName: Codable, Hashable { @@ -15,6 +17,7 @@ public struct SpecialModelName: Codable, Hashable { public init(specialPropertyName: Int64? = nil) { self.specialPropertyName = specialPropertyName } + public enum CodingKeys: String, CodingKey, CaseIterable { case specialPropertyName = "$special[property.name]" } @@ -25,7 +28,5 @@ public struct SpecialModelName: Codable, Hashable { var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(specialPropertyName, forKey: .specialPropertyName) } - - - } + diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/StringBooleanMap.swift b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/StringBooleanMap.swift index 0699c25ff7e..2edf881a8f0 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/StringBooleanMap.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/StringBooleanMap.swift @@ -6,43 +6,20 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct StringBooleanMap: Codable, Hashable { + public enum CodingKeys: CodingKey, CaseIterable { } - public var additionalProperties: [String: Bool] = [:] - - public subscript(key: String) -> Bool? { - get { - if let value = additionalProperties[key] { - return value - } - return nil - } - - set { - additionalProperties[key] = newValue - } - } // Encodable protocol methods public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) - var additionalPropertiesContainer = encoder.container(keyedBy: String.self) - try additionalPropertiesContainer.encodeMap(additionalProperties) } - - // Decodable protocol methods - - public init(from decoder: Decoder) throws { - let container = try decoder.container(keyedBy: String.self) - - var nonAdditionalPropertyKeys = Set() - additionalProperties = try container.decodeMap(Bool.self, excludedKeys: nonAdditionalPropertyKeys) - } - - } + diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift index 11c5f7a750b..07b826264f3 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct Tag: Codable, Hashable { @@ -17,6 +19,7 @@ public struct Tag: Codable, Hashable { self.id = id self.name = name } + public enum CodingKeys: String, CodingKey, CaseIterable { case id case name @@ -29,7 +32,5 @@ public struct Tag: Codable, Hashable { try container.encodeIfPresent(id, forKey: .id) try container.encodeIfPresent(name, forKey: .name) } - - - } + diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderDefault.swift b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderDefault.swift index 35b1a5833b9..e58eecd960f 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderDefault.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderDefault.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct TypeHolderDefault: Codable, Hashable { @@ -23,6 +25,7 @@ public struct TypeHolderDefault: Codable, Hashable { self.boolItem = boolItem self.arrayItem = arrayItem } + public enum CodingKeys: String, CodingKey, CaseIterable { case stringItem = "string_item" case numberItem = "number_item" @@ -41,7 +44,5 @@ public struct TypeHolderDefault: Codable, Hashable { try container.encode(boolItem, forKey: .boolItem) try container.encode(arrayItem, forKey: .arrayItem) } - - - } + diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderExample.swift b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderExample.swift index 37277a4ac00..6c22fdbae7a 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderExample.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderExample.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct TypeHolderExample: Codable, Hashable { @@ -23,6 +25,7 @@ public struct TypeHolderExample: Codable, Hashable { self.boolItem = boolItem self.arrayItem = arrayItem } + public enum CodingKeys: String, CodingKey, CaseIterable { case stringItem = "string_item" case numberItem = "number_item" @@ -41,7 +44,5 @@ public struct TypeHolderExample: Codable, Hashable { try container.encode(boolItem, forKey: .boolItem) try container.encode(arrayItem, forKey: .arrayItem) } - - - } + diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/User.swift b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/User.swift index 2bbc31806ff..7afe359ae40 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/User.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models/User.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public struct User: Codable, Hashable { @@ -30,6 +32,7 @@ public struct User: Codable, Hashable { self.phone = phone self.userStatus = userStatus } + public enum CodingKeys: String, CodingKey, CaseIterable { case id case username @@ -54,7 +57,5 @@ public struct User: Codable, Hashable { try container.encodeIfPresent(phone, forKey: .phone) try container.encodeIfPresent(userStatus, forKey: .userStatus) } - - - } + 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 52b2071ec1a..41959190a26 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift @@ -93,14 +93,14 @@ open class URLSessionRequestBuilder: RequestBuilder { return modifiedRequest } - override open func execute(_ apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, _ completion: @escaping (_ result: Swift.Result, Error>) -> Void) { + override open func execute(_ apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, _ completion: @escaping (_ result: Swift.Result, Error>) -> Void) { let urlSessionId = UUID().uuidString // Create a new manager for each request to customize its request header let urlSession = createURLSession() urlSessionStore[urlSessionId] = urlSession guard let xMethod = HTTPMethod(rawValue: method) else { - fatalError("Unsuported Http method - \(method)") + fatalError("Unsupported Http method - \(method)") } let encoding: ParameterEncoding @@ -119,7 +119,7 @@ open class URLSessionRequestBuilder: RequestBuilder { } else if contentType == "application/x-www-form-urlencoded" { encoding = FormURLEncoding() } else { - fatalError("Unsuported Media Type - \(contentType)") + fatalError("Unsupported Media Type - \(contentType)") } } @@ -205,16 +205,18 @@ open class URLSessionRequestBuilder: RequestBuilder { } let fileManager = FileManager.default - let documentsDirectory = fileManager.urls(for: .documentDirectory, in: .userDomainMask)[0] + let cachesDirectory = fileManager.urls(for: .cachesDirectory, in: .userDomainMask)[0] let requestURL = try getURL(from: urlRequest) var requestPath = try getPath(from: requestURL) if let headerFileName = getFileName(fromContentDisposition: httpResponse.allHeaderFields["Content-Disposition"] as? String) { requestPath = requestPath.appending("/\(headerFileName)") + } else { + requestPath = requestPath.appending("/tmp.PetstoreClient.\(UUID().uuidString)") } - let filePath = documentsDirectory.appendingPathComponent(requestPath) + let filePath = cachesDirectory.appendingPathComponent(requestPath) let directoryPath = filePath.deletingLastPathComponent().path try fileManager.createDirectory(atPath: directoryPath, withIntermediateDirectories: true, attributes: nil) @@ -232,6 +234,10 @@ open class URLSessionRequestBuilder: RequestBuilder { completion(.success(Response(response: httpResponse, body: nil))) + case is Data.Type: + + completion(.success(Response(response: httpResponse, body: data as? T))) + default: completion(.success(Response(response: httpResponse, body: data as? T))) @@ -244,7 +250,7 @@ open class URLSessionRequestBuilder: RequestBuilder { for (key, value) in headers { httpHeaders[key] = value } - for (key, value) in PetstoreClientAPI.customHeaders { + for (key, value) in PetstoreClient.customHeaders { httpHeaders[key] = value } return httpHeaders @@ -328,6 +334,43 @@ open class URLSessionDecodableRequestBuilder: URLSessionRequestBui completion(.success(Response(response: httpResponse, body: body as? T))) + case is URL.Type: + do { + + guard error == nil else { + throw DownloadException.responseFailed + } + + guard let data = data else { + throw DownloadException.responseDataMissing + } + + let fileManager = FileManager.default + let cachesDirectory = fileManager.urls(for: .cachesDirectory, in: .userDomainMask)[0] + let requestURL = try getURL(from: urlRequest) + + var requestPath = try getPath(from: requestURL) + + if let headerFileName = getFileName(fromContentDisposition: httpResponse.allHeaderFields["Content-Disposition"] as? String) { + requestPath = requestPath.appending("/\(headerFileName)") + } else { + requestPath = requestPath.appending("/tmp.PetstoreClient.\(UUID().uuidString)") + } + + let filePath = cachesDirectory.appendingPathComponent(requestPath) + let directoryPath = filePath.deletingLastPathComponent().path + + try fileManager.createDirectory(atPath: directoryPath, withIntermediateDirectories: true, attributes: nil) + try data.write(to: filePath, options: .atomic) + + completion(.success(Response(response: httpResponse, body: filePath as? T))) + + } catch let requestParserError as DownloadException { + completion(.failure(ErrorResponse.error(400, data, response, requestParserError))) + } catch { + completion(.failure(ErrorResponse.error(400, data, response, error))) + } + case is Void.Type: completion(.success(Response(response: httpResponse, body: nil))) diff --git a/samples/client/petstore/swift5/rxswiftLibrary/SwaggerClientTests/.gitignore b/samples/client/petstore/swift5/rxswiftLibrary/SwaggerClientTests/.gitignore index 0269c2f56db..22029d2f644 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/SwaggerClientTests/.gitignore +++ b/samples/client/petstore/swift5/rxswiftLibrary/SwaggerClientTests/.gitignore @@ -1,14 +1,22 @@ -### https://raw.github.com/github/gitignore/7792e50daeaa6c07460484704671d1dc9f0045a7/Swift.gitignore +# Created by https://www.toptal.com/developers/gitignore/api/swift,xcode +# Edit at https://www.toptal.com/developers/gitignore?templates=swift,xcode +### Swift ### # Xcode # # gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore -## Build generated +## User settings +xcuserdata/ + +## compatibility with Xcode 8 and earlier (ignoring not required starting Xcode 9) +*.xcscmblueprint +*.xccheckout + +## compatibility with Xcode 3 and earlier (ignoring not required starting Xcode 4) build/ DerivedData/ - -## Various settings +*.moved-aside *.pbxuser !default.pbxuser *.mode1v3 @@ -17,15 +25,11 @@ DerivedData/ !default.mode2v3 *.perspectivev3 !default.perspectivev3 -xcuserdata/ - -## Other -*.moved-aside -*.xccheckout -*.xcscmblueprint ## Obj-C/Swift specific *.hmap + +## App packaging *.ipa *.dSYM.zip *.dSYM @@ -35,38 +39,67 @@ timeline.xctimeline playground.xcworkspace # Swift Package Manager -# # Add this line if you want to avoid checking in source code from Swift Package Manager dependencies. # Packages/ # Package.pins # Package.resolved +# *.xcodeproj +# Xcode automatically generates this directory with a .xcworkspacedata file and xcuserdata +# hence it is not needed unless you have added a package configuration file to your project +# .swiftpm + .build/ # CocoaPods -# # We recommend against adding the Pods directory to your .gitignore. However # you should judge for yourself, the pros and cons are mentioned at: # https://guides.cocoapods.org/using/using-cocoapods.html#should-i-check-the-pods-directory-into-source-control -# -Pods/ +# Pods/ +# Add this line if you want to avoid checking in source code from the Xcode workspace +# *.xcworkspace # Carthage -# # Add this line if you want to avoid checking in source code from Carthage dependencies. -Carthage/Checkouts +# Carthage/Checkouts -Carthage/Build +Carthage/Build/ + +# Add this lines if you are using Accio dependency management (Deprecated since Xcode 12) +# Dependencies/ +# .accio/ # fastlane -# -# It is recommended to not store the screenshots in the git repo. Instead, use fastlane to re-generate the -# screenshots whenever they are needed. +# It is recommended to not store the screenshots in the git repo. +# Instead, use fastlane to re-generate the screenshots whenever they are needed. # For more information about the recommended setup visit: # https://docs.fastlane.tools/best-practices/source-control/#source-control fastlane/report.xml fastlane/Preview.html -fastlane/screenshots +fastlane/screenshots/**/*.png fastlane/test_output +# Code Injection +# After new code Injection tools there's a generated folder /iOSInjectionProject +# https://github.com/johnno1962/injectionforxcode +iOSInjectionProject/ + +### Xcode ### +# Xcode +# gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore + + + + +## Gcc Patch +/*.gcno + +### Xcode Patch ### +*.xcodeproj/* +!*.xcodeproj/project.pbxproj +!*.xcodeproj/xcshareddata/ +!*.xcworkspace/contents.xcworkspacedata +**/xcshareddata/WorkspaceSettings.xcsettings + +# End of https://www.toptal.com/developers/gitignore/api/swift,xcode \ No newline at end of file diff --git a/samples/client/petstore/swift5/rxswiftLibrary/SwaggerClientTests/Podfile b/samples/client/petstore/swift5/rxswiftLibrary/SwaggerClientTests/Podfile deleted file mode 100644 index 77432f9eee9..00000000000 --- a/samples/client/petstore/swift5/rxswiftLibrary/SwaggerClientTests/Podfile +++ /dev/null @@ -1,13 +0,0 @@ -platform :ios, '9.0' - -source 'https://cdn.cocoapods.org/' - -use_frameworks! - -target 'SwaggerClient' do - pod "PetstoreClient", :path => "../" - - target 'SwaggerClientTests' do - inherit! :search_paths - end -end diff --git a/samples/client/petstore/swift5/rxswiftLibrary/SwaggerClientTests/Podfile.lock b/samples/client/petstore/swift5/rxswiftLibrary/SwaggerClientTests/Podfile.lock deleted file mode 100644 index be3757ec1f4..00000000000 --- a/samples/client/petstore/swift5/rxswiftLibrary/SwaggerClientTests/Podfile.lock +++ /dev/null @@ -1,23 +0,0 @@ -PODS: - - PetstoreClient (1.0.0): - - RxSwift (~> 5.1.1) - - RxSwift (5.1.1) - -DEPENDENCIES: - - PetstoreClient (from `../`) - -SPEC REPOS: - trunk: - - RxSwift - -EXTERNAL SOURCES: - PetstoreClient: - :path: "../" - -SPEC CHECKSUMS: - PetstoreClient: f3d073d9543d90440a155feec649c16b98d84c31 - RxSwift: 81470a2074fa8780320ea5fe4102807cb7118178 - -PODFILE CHECKSUM: 509bec696cc1d8641751b52e4fe4bef04ac4542c - -COCOAPODS: 1.10.0 diff --git a/samples/client/petstore/swift5/rxswiftLibrary/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj b/samples/client/petstore/swift5/rxswiftLibrary/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj index f04b8be9b6a..a9c4af1c818 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj +++ b/samples/client/petstore/swift5/rxswiftLibrary/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj @@ -3,14 +3,13 @@ archiveVersion = 1; classes = { }; - objectVersion = 46; + objectVersion = 52; objects = { /* Begin PBXBuildFile section */ + A5782C702664FA2300CAA106 /* PetstoreClient in Frameworks */ = {isa = PBXBuildFile; productRef = A5782C6F2664FA2300CAA106 /* PetstoreClient */; }; A5EA1260241941BE00E30FC3 /* FileUtils.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5EA125E241941BE00E30FC3 /* FileUtils.swift */; }; A5EA1261241941BE00E30FC3 /* UIImage+Extras.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5EA125F241941BE00E30FC3 /* UIImage+Extras.swift */; }; - B024164FBFF71BF644D4419A /* Pods_SwaggerClient.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 177A58DD5CF63F2989335DCC /* Pods_SwaggerClient.framework */; }; - B1D0246C8960F47A60098F37 /* Pods_SwaggerClientTests.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 6F96A0131101344CC5406CB3 /* Pods_SwaggerClientTests.framework */; }; B596E4BD205657A500B46F03 /* APIHelperTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = B596E4BC205657A500B46F03 /* APIHelperTests.swift */; }; EAEC0BC21D4E30CE00C908A3 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = EAEC0BC11D4E30CE00C908A3 /* AppDelegate.swift */; }; EAEC0BC41D4E30CE00C908A3 /* ViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = EAEC0BC31D4E30CE00C908A3 /* ViewController.swift */; }; @@ -33,11 +32,6 @@ /* End PBXContainerItemProxy section */ /* Begin PBXFileReference section */ - 177A58DD5CF63F2989335DCC /* Pods_SwaggerClient.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_SwaggerClient.framework; sourceTree = BUILT_PRODUCTS_DIR; }; - 2DEFA8828BD4E38FA5262F53 /* Pods-SwaggerClient.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-SwaggerClient.release.xcconfig"; path = "Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient.release.xcconfig"; sourceTree = ""; }; - 4EF2021609D112A6F5AE0F55 /* Pods-SwaggerClientTests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-SwaggerClientTests.debug.xcconfig"; path = "Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests.debug.xcconfig"; sourceTree = ""; }; - 6F96A0131101344CC5406CB3 /* Pods_SwaggerClientTests.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_SwaggerClientTests.framework; sourceTree = BUILT_PRODUCTS_DIR; }; - 8D99518E8E05FD856A952698 /* Pods-SwaggerClient.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-SwaggerClient.debug.xcconfig"; path = "Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient.debug.xcconfig"; sourceTree = ""; }; A5EA125E241941BE00E30FC3 /* FileUtils.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FileUtils.swift; sourceTree = ""; }; A5EA125F241941BE00E30FC3 /* UIImage+Extras.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "UIImage+Extras.swift"; sourceTree = ""; }; B596E4BC205657A500B46F03 /* APIHelperTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = APIHelperTests.swift; sourceTree = ""; }; @@ -53,7 +47,6 @@ EAEC0BE31D4E330700C908A3 /* PetAPITests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PetAPITests.swift; sourceTree = ""; }; EAEC0BE51D4E379000C908A3 /* StoreAPITests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StoreAPITests.swift; sourceTree = ""; }; EAEC0BE71D4E38CB00C908A3 /* UserAPITests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = UserAPITests.swift; sourceTree = ""; }; - EFD8AB05F53C74985527D117 /* Pods-SwaggerClientTests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-SwaggerClientTests.release.xcconfig"; path = "Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests.release.xcconfig"; sourceTree = ""; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ @@ -61,7 +54,7 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( - B024164FBFF71BF644D4419A /* Pods_SwaggerClient.framework in Frameworks */, + A5782C702664FA2300CAA106 /* PetstoreClient in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -69,41 +62,26 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( - B1D0246C8960F47A60098F37 /* Pods_SwaggerClientTests.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */ - 55DC454FF5FFEF8A9CBC1CA3 /* Frameworks */ = { + A5782C6E2664FA2300CAA106 /* Frameworks */ = { isa = PBXGroup; children = ( - 177A58DD5CF63F2989335DCC /* Pods_SwaggerClient.framework */, - 6F96A0131101344CC5406CB3 /* Pods_SwaggerClientTests.framework */, ); name = Frameworks; sourceTree = ""; }; - CB19142D951AB5DD885404A8 /* Pods */ = { - isa = PBXGroup; - children = ( - 8D99518E8E05FD856A952698 /* Pods-SwaggerClient.debug.xcconfig */, - 2DEFA8828BD4E38FA5262F53 /* Pods-SwaggerClient.release.xcconfig */, - 4EF2021609D112A6F5AE0F55 /* Pods-SwaggerClientTests.debug.xcconfig */, - EFD8AB05F53C74985527D117 /* Pods-SwaggerClientTests.release.xcconfig */, - ); - name = Pods; - sourceTree = ""; - }; EAEC0BB51D4E30CE00C908A3 = { isa = PBXGroup; children = ( EAEC0BC01D4E30CE00C908A3 /* SwaggerClient */, EAEC0BD51D4E30CE00C908A3 /* SwaggerClientTests */, EAEC0BBF1D4E30CE00C908A3 /* Products */, - CB19142D951AB5DD885404A8 /* Pods */, - 55DC454FF5FFEF8A9CBC1CA3 /* Frameworks */, + A5782C6E2664FA2300CAA106 /* Frameworks */, ); sourceTree = ""; }; @@ -150,17 +128,18 @@ isa = PBXNativeTarget; buildConfigurationList = EAEC0BDB1D4E30CE00C908A3 /* Build configuration list for PBXNativeTarget "SwaggerClient" */; buildPhases = ( - 898E536ECC2C4811DDDF67C1 /* [CP] Check Pods Manifest.lock */, EAEC0BBA1D4E30CE00C908A3 /* Sources */, EAEC0BBB1D4E30CE00C908A3 /* Frameworks */, EAEC0BBC1D4E30CE00C908A3 /* Resources */, - 8A7961360961F06AADAF17C9 /* [CP] Embed Pods Frameworks */, ); buildRules = ( ); dependencies = ( ); name = SwaggerClient; + packageProductDependencies = ( + A5782C6F2664FA2300CAA106 /* PetstoreClient */, + ); productName = SwaggerClient; productReference = EAEC0BBE1D4E30CE00C908A3 /* SwaggerClient.app */; productType = "com.apple.product-type.application"; @@ -169,7 +148,6 @@ isa = PBXNativeTarget; buildConfigurationList = EAEC0BDE1D4E30CE00C908A3 /* Build configuration list for PBXNativeTarget "SwaggerClientTests" */; buildPhases = ( - 82CB35D52E274C6177DAC0DD /* [CP] Check Pods Manifest.lock */, EAEC0BCE1D4E30CE00C908A3 /* Sources */, EAEC0BCF1D4E30CE00C908A3 /* Frameworks */, EAEC0BD01D4E30CE00C908A3 /* Resources */, @@ -244,65 +222,6 @@ }; /* End PBXResourcesBuildPhase section */ -/* Begin PBXShellScriptBuildPhase section */ - 82CB35D52E274C6177DAC0DD /* [CP] Check Pods Manifest.lock */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputPaths = ( - "${PODS_PODFILE_DIR_PATH}/Podfile.lock", - "${PODS_ROOT}/Manifest.lock", - ); - name = "[CP] Check Pods Manifest.lock"; - outputPaths = ( - "$(DERIVED_FILE_DIR)/Pods-SwaggerClientTests-checkManifestLockResult.txt", - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; - showEnvVarsInLog = 0; - }; - 898E536ECC2C4811DDDF67C1 /* [CP] Check Pods Manifest.lock */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputPaths = ( - "${PODS_PODFILE_DIR_PATH}/Podfile.lock", - "${PODS_ROOT}/Manifest.lock", - ); - name = "[CP] Check Pods Manifest.lock"; - outputPaths = ( - "$(DERIVED_FILE_DIR)/Pods-SwaggerClient-checkManifestLockResult.txt", - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; - showEnvVarsInLog = 0; - }; - 8A7961360961F06AADAF17C9 /* [CP] Embed Pods Frameworks */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputPaths = ( - "${PODS_ROOT}/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-frameworks.sh", - "${BUILT_PRODUCTS_DIR}/PetstoreClient/PetstoreClient.framework", - "${BUILT_PRODUCTS_DIR}/RxSwift/RxSwift.framework", - ); - name = "[CP] Embed Pods Frameworks"; - outputPaths = ( - "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/PetstoreClient.framework", - "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/RxSwift.framework", - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-frameworks.sh\"\n"; - showEnvVarsInLog = 0; - }; -/* End PBXShellScriptBuildPhase section */ - /* Begin PBXSourcesBuildPhase section */ EAEC0BBA1D4E30CE00C908A3 /* Sources */ = { isa = PBXSourcesBuildPhase; @@ -458,7 +377,8 @@ IPHONEOS_DEPLOYMENT_TARGET = 9.3; MTL_ENABLE_DEBUG_INFO = NO; SDKROOT = iphoneos; - SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; SWIFT_VERSION = 4.2; VALIDATE_PRODUCT = YES; }; @@ -466,11 +386,13 @@ }; EAEC0BDC1D4E30CE00C908A3 /* Debug */ = { isa = XCBuildConfiguration; - baseConfigurationReference = 8D99518E8E05FD856A952698 /* Pods-SwaggerClient.debug.xcconfig */; buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; INFOPLIST_FILE = SwaggerClient/Info.plist; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); PRODUCT_BUNDLE_IDENTIFIER = com.swagger.SwaggerClient; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_VERSION = 5.0; @@ -480,11 +402,13 @@ }; EAEC0BDD1D4E30CE00C908A3 /* Release */ = { isa = XCBuildConfiguration; - baseConfigurationReference = 2DEFA8828BD4E38FA5262F53 /* Pods-SwaggerClient.release.xcconfig */; buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; INFOPLIST_FILE = SwaggerClient/Info.plist; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); PRODUCT_BUNDLE_IDENTIFIER = com.swagger.SwaggerClient; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_VERSION = 5.0; @@ -494,12 +418,15 @@ }; EAEC0BDF1D4E30CE00C908A3 /* Debug */ = { isa = XCBuildConfiguration; - baseConfigurationReference = 4EF2021609D112A6F5AE0F55 /* Pods-SwaggerClientTests.debug.xcconfig */; buildSettings = { BUNDLE_LOADER = "$(TEST_HOST)"; CLANG_ENABLE_MODULES = YES; INFOPLIST_FILE = SwaggerClientTests/Info.plist; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); PRODUCT_BUNDLE_IDENTIFIER = com.swagger.SwaggerClientTests; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_OPTIMIZATION_LEVEL = "-Onone"; @@ -510,12 +437,15 @@ }; EAEC0BE01D4E30CE00C908A3 /* Release */ = { isa = XCBuildConfiguration; - baseConfigurationReference = EFD8AB05F53C74985527D117 /* Pods-SwaggerClientTests.release.xcconfig */; buildSettings = { BUNDLE_LOADER = "$(TEST_HOST)"; CLANG_ENABLE_MODULES = YES; INFOPLIST_FILE = SwaggerClientTests/Info.plist; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); PRODUCT_BUNDLE_IDENTIFIER = com.swagger.SwaggerClientTests; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_VERSION = 5.0; @@ -554,6 +484,13 @@ defaultConfigurationName = Release; }; /* End XCConfigurationList section */ + +/* Begin XCSwiftPackageProductDependency section */ + A5782C6F2664FA2300CAA106 /* PetstoreClient */ = { + isa = XCSwiftPackageProductDependency; + productName = PetstoreClient; + }; +/* End XCSwiftPackageProductDependency section */ }; rootObject = EAEC0BB61D4E30CE00C908A3 /* Project object */; } diff --git a/samples/client/petstore/swift5/rxswiftLibrary/SwaggerClientTests/SwaggerClient.xcworkspace/contents.xcworkspacedata b/samples/client/petstore/swift5/rxswiftLibrary/SwaggerClientTests/SwaggerClient.xcworkspace/contents.xcworkspacedata index 9b3fa18954f..00ec9b53a7f 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/SwaggerClientTests/SwaggerClient.xcworkspace/contents.xcworkspacedata +++ b/samples/client/petstore/swift5/rxswiftLibrary/SwaggerClientTests/SwaggerClient.xcworkspace/contents.xcworkspacedata @@ -2,9 +2,9 @@ + location = "group:.."> + location = "group:SwaggerClient.xcodeproj"> diff --git a/samples/client/petstore/swift5/rxswiftLibrary/SwaggerClientTests/SwaggerClient.xcworkspace/xcshareddata/swiftpm/Package.resolved b/samples/client/petstore/swift5/rxswiftLibrary/SwaggerClientTests/SwaggerClient.xcworkspace/xcshareddata/swiftpm/Package.resolved new file mode 100644 index 00000000000..231d8536967 --- /dev/null +++ b/samples/client/petstore/swift5/rxswiftLibrary/SwaggerClientTests/SwaggerClient.xcworkspace/xcshareddata/swiftpm/Package.resolved @@ -0,0 +1,25 @@ +{ + "object": { + "pins": [ + { + "package": "AnyCodable", + "repositoryURL": "https://github.com/Flight-School/AnyCodable", + "state": { + "branch": null, + "revision": "876d162385e9862ae8b3c8d65dc301312b040005", + "version": "0.6.0" + } + }, + { + "package": "RxSwift", + "repositoryURL": "https://github.com/ReactiveX/RxSwift.git", + "state": { + "branch": null, + "revision": "7c17a6ccca06b5c107cfa4284e634562ddaf5951", + "version": "6.2.0" + } + } + ] + }, + "version": 1 +} diff --git a/samples/client/petstore/swift5/rxswiftLibrary/SwaggerClientTests/SwaggerClientTests/PetAPITests.swift b/samples/client/petstore/swift5/rxswiftLibrary/SwaggerClientTests/SwaggerClientTests/PetAPITests.swift index fb68168b697..db7609caf07 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/SwaggerClientTests/SwaggerClientTests/PetAPITests.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/SwaggerClientTests/SwaggerClientTests/PetAPITests.swift @@ -62,7 +62,7 @@ class PetAPITests: XCTestCase { expectation.fulfill() }, onError: { _ in XCTFail("error getting pet") - }).disposed(by: disposeBag) + }).disposed(by: disposeBag) self.waitForExpectations(timeout: testTimeout, handler: nil) } diff --git a/samples/client/petstore/swift5/rxswiftLibrary/docs/FakeAPI.md b/samples/client/petstore/swift5/rxswiftLibrary/docs/FakeAPI.md index 9ca07180e07..76acf726217 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/docs/FakeAPI.md +++ b/samples/client/petstore/swift5/rxswiftLibrary/docs/FakeAPI.md @@ -315,7 +315,7 @@ import PetstoreClient let number = 987 // Double | None let double = 987 // Double | None let patternWithoutDelimiter = "patternWithoutDelimiter_example" // String | None -let byte = 987 // Data | None +let byte = Data([9, 8, 7]) // Data | None let integer = 987 // Int | None (optional) let int32 = 987 // Int | None (optional) let int64 = 987 // Int64 | None (optional) diff --git a/samples/client/petstore/swift5/rxswiftLibrary/project.yml b/samples/client/petstore/swift5/rxswiftLibrary/project.yml index 7f6334fda43..5471ac0bc64 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/project.yml +++ b/samples/client/petstore/swift5/rxswiftLibrary/project.yml @@ -12,5 +12,5 @@ targets: APPLICATION_EXTENSION_API_ONLY: true scheme: {} dependencies: - - carthage: RxSwift - carthage: AnyCodable + - carthage: RxSwift diff --git a/samples/client/petstore/swift5/swift5_test_all.sh b/samples/client/petstore/swift5/swift5_test_all.sh index 153b5cfbc07..0b5ef4780b5 100755 --- a/samples/client/petstore/swift5/swift5_test_all.sh +++ b/samples/client/petstore/swift5/swift5_test_all.sh @@ -6,21 +6,25 @@ DIRECTORY=`dirname $0` # example project with unit tests # temporarily commment them because they are flaky +# mvn -f $DIRECTORY/alamofireLibrary/SwaggerClientTests/pom.xml integration-test +# mvn -f $DIRECTORY/combineLibrary/SwaggerClientTests/pom.xml integration-test # mvn -f $DIRECTORY/default/SwaggerClientTests/pom.xml integration-test # mvn -f $DIRECTORY/promisekitLibrary/SwaggerClientTests/pom.xml integration-test # mvn -f $DIRECTORY/rxswiftLibrary/SwaggerClientTests/pom.xml integration-test # mvn -f $DIRECTORY/urlsessionLibrary/SwaggerClientTests/pom.xml integration-test -# mvn -f $DIRECTORY/alamofireLibrary/SwaggerClientTests/pom.xml integration-test -# mvn -f $DIRECTORY/combineLibrary/SwaggerClientTests/pom.xml integration-test # spm build +mvn -f $DIRECTORY/alamofireLibrary/pom.xml integration-test +mvn -f $DIRECTORY/combineLibrary/pom.xml integration-test mvn -f $DIRECTORY/default/pom.xml integration-test +mvn -f $DIRECTORY/deprecated/pom.xml integration-test mvn -f $DIRECTORY/nonPublicApi/pom.xml integration-test mvn -f $DIRECTORY/objcCompatible/pom.xml integration-test +mvn -f $DIRECTORY/oneOf/pom.xml integration-test mvn -f $DIRECTORY/promisekitLibrary/pom.xml integration-test +mvn -f $DIRECTORY/readonlyProperties/pom.xml integration-test mvn -f $DIRECTORY/resultLibrary/pom.xml integration-test mvn -f $DIRECTORY/rxswiftLibrary/pom.xml integration-test mvn -f $DIRECTORY/urlsessionLibrary/pom.xml integration-test -mvn -f $DIRECTORY/alamofireLibrary/pom.xml integration-test -mvn -f $DIRECTORY/combineLibrary/pom.xml integration-test -mvn -f $DIRECTORY/deprecated/pom.xml integration-test +mvn -f $DIRECTORY/vaporLibrary/pom.xml integration-test +mvn -f $DIRECTORY/x-swift-hashable/pom.xml integration-test diff --git a/samples/client/petstore/swift5/urlsessionLibrary/.gitignore b/samples/client/petstore/swift5/urlsessionLibrary/.gitignore index 5e5d5cebcf4..627d360a903 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/.gitignore +++ b/samples/client/petstore/swift5/urlsessionLibrary/.gitignore @@ -1,12 +1,22 @@ +# Created by https://www.toptal.com/developers/gitignore/api/swift,xcode +# Edit at https://www.toptal.com/developers/gitignore?templates=swift,xcode + +### Swift ### # Xcode # # gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore -## Build generated -build/ -DerivedData +## User settings +xcuserdata/ -## Various settings +## compatibility with Xcode 8 and earlier (ignoring not required starting Xcode 9) +*.xcscmblueprint +*.xccheckout + +## compatibility with Xcode 3 and earlier (ignoring not required starting Xcode 4) +build/ +DerivedData/ +*.moved-aside *.pbxuser !default.pbxuser *.mode1v3 @@ -15,49 +25,81 @@ DerivedData !default.mode2v3 *.perspectivev3 !default.perspectivev3 -xcuserdata - -## Other -*.xccheckout -*.moved-aside -*.xcuserstate -*.xcscmblueprint ## Obj-C/Swift specific *.hmap + +## App packaging *.ipa +*.dSYM.zip +*.dSYM ## Playgrounds timeline.xctimeline playground.xcworkspace # Swift Package Manager -# # Add this line if you want to avoid checking in source code from Swift Package Manager dependencies. # Packages/ +# Package.pins +# Package.resolved +# *.xcodeproj +# Xcode automatically generates this directory with a .xcworkspacedata file and xcuserdata +# hence it is not needed unless you have added a package configuration file to your project +# .swiftpm + .build/ # CocoaPods -# # We recommend against adding the Pods directory to your .gitignore. However # you should judge for yourself, the pros and cons are mentioned at: # https://guides.cocoapods.org/using/using-cocoapods.html#should-i-check-the-pods-directory-into-source-control -# # Pods/ +# Add this line if you want to avoid checking in source code from the Xcode workspace +# *.xcworkspace # Carthage -# # Add this line if you want to avoid checking in source code from Carthage dependencies. # Carthage/Checkouts -Carthage/Build +Carthage/Build/ + +# Add this lines if you are using Accio dependency management (Deprecated since Xcode 12) +# Dependencies/ +# .accio/ # fastlane -# -# It is recommended to not store the screenshots in the git repo. Instead, use fastlane to re-generate the -# screenshots whenever they are needed. +# It is recommended to not store the screenshots in the git repo. +# Instead, use fastlane to re-generate the screenshots whenever they are needed. # For more information about the recommended setup visit: -# https://github.com/fastlane/fastlane/blob/master/docs/Gitignore.md +# https://docs.fastlane.tools/best-practices/source-control/#source-control fastlane/report.xml -fastlane/screenshots +fastlane/Preview.html +fastlane/screenshots/**/*.png +fastlane/test_output + +# Code Injection +# After new code Injection tools there's a generated folder /iOSInjectionProject +# https://github.com/johnno1962/injectionforxcode + +iOSInjectionProject/ + +### Xcode ### +# Xcode +# gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore + + + + +## Gcc Patch +/*.gcno + +### Xcode Patch ### +*.xcodeproj/* +!*.xcodeproj/project.pbxproj +!*.xcodeproj/xcshareddata/ +!*.xcworkspace/contents.xcworkspacedata +**/xcshareddata/WorkspaceSettings.xcsettings + +# End of https://www.toptal.com/developers/gitignore/api/swift,xcode diff --git a/samples/client/petstore/swift5/urlsessionLibrary/.openapi-generator/VERSION b/samples/client/petstore/swift5/urlsessionLibrary/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/.openapi-generator/VERSION +++ b/samples/client/petstore/swift5/urlsessionLibrary/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/client/petstore/swift5/urlsessionLibrary/.swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata b/samples/client/petstore/swift5/urlsessionLibrary/.swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata new file mode 100644 index 00000000000..919434a6254 --- /dev/null +++ b/samples/client/petstore/swift5/urlsessionLibrary/.swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Cartfile b/samples/client/petstore/swift5/urlsessionLibrary/Cartfile index 84aaa61ef2d..a6a6bcacb1d 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/Cartfile +++ b/samples/client/petstore/swift5/urlsessionLibrary/Cartfile @@ -1,2 +1,2 @@ -github "Flight-School/AnyCodable" ~> 0.4.0 +github "Flight-School/AnyCodable" ~> 0.6.1 diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Package.resolved b/samples/client/petstore/swift5/urlsessionLibrary/Package.resolved new file mode 100644 index 00000000000..79610c3b3b3 --- /dev/null +++ b/samples/client/petstore/swift5/urlsessionLibrary/Package.resolved @@ -0,0 +1,16 @@ +{ + "object": { + "pins": [ + { + "package": "AnyCodable", + "repositoryURL": "https://github.com/Flight-School/AnyCodable", + "state": { + "branch": null, + "revision": "69261f239f0fffaf51495dadc4f8483fbfe97025", + "version": "0.6.1" + } + } + ] + }, + "version": 1 +} diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Package.swift b/samples/client/petstore/swift5/urlsessionLibrary/Package.swift index 99e2642257a..300e7414279 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/Package.swift +++ b/samples/client/petstore/swift5/urlsessionLibrary/Package.swift @@ -19,7 +19,7 @@ let package = Package( ], dependencies: [ // Dependencies declare other packages that this package depends on. - .package(url: "https://github.com/Flight-School/AnyCodable", .exact("0.4.0")), + .package(url: "https://github.com/Flight-School/AnyCodable", from: "0.6.1"), ], targets: [ // Targets are the basic building blocks of a package. A target can define a module or a test suite. diff --git a/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient.podspec b/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient.podspec index 66ef37061f8..571e1d8a518 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient.podspec +++ b/samples/client/petstore/swift5/urlsessionLibrary/PetstoreClient.podspec @@ -11,5 +11,5 @@ Pod::Spec.new do |s| s.homepage = 'https://github.com/openapitools/openapi-generator' s.summary = 'PetstoreClient' s.source_files = 'Sources/PetstoreClient/**/*.swift' - s.dependency 'AnyCodable-FlightSchool', '~> 0.4.0' + s.dependency 'AnyCodable-FlightSchool', '~> 0.6.1' end diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/Models/ClassModel.swift b/samples/client/petstore/swift5/urlsessionLibrary/Sources/Models/ClassModel.swift deleted file mode 100644 index 1b54393ed9f..00000000000 --- a/samples/client/petstore/swift5/urlsessionLibrary/Sources/Models/ClassModel.swift +++ /dev/null @@ -1,23 +0,0 @@ -// -// ClassModel.swift -// -// Generated by openapi-generator -// https://openapi-generator.tech -// - -import Foundation - -/** Model for testing model with \"_class\" property */ -public struct ClassModel: Codable, Hashable { - - public var `class`: String? - - public init(`class`: String? = nil) { - self.`class` = `class` - } - - public enum CodingKeys: String, CodingKey, CaseIterable { - case `class` = "_class" - } - -} diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/Models/Model200Response.swift b/samples/client/petstore/swift5/urlsessionLibrary/Sources/Models/Model200Response.swift deleted file mode 100644 index 034d4d2979b..00000000000 --- a/samples/client/petstore/swift5/urlsessionLibrary/Sources/Models/Model200Response.swift +++ /dev/null @@ -1,26 +0,0 @@ -// -// Model200Response.swift -// -// Generated by openapi-generator -// https://openapi-generator.tech -// - -import Foundation - -/** Model for testing model name starting with number */ -public struct Model200Response: Codable, Hashable { - - public var name: Int? - public var `class`: String? - - public init(name: Int? = nil, `class`: String? = nil) { - self.name = name - self.`class` = `class` - } - - public enum CodingKeys: String, CodingKey, CaseIterable { - case name - case `class` = "class" - } - -} diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/Models/Return.swift b/samples/client/petstore/swift5/urlsessionLibrary/Sources/Models/Return.swift deleted file mode 100644 index 2831cd656be..00000000000 --- a/samples/client/petstore/swift5/urlsessionLibrary/Sources/Models/Return.swift +++ /dev/null @@ -1,23 +0,0 @@ -// -// Return.swift -// -// Generated by openapi-generator -// https://openapi-generator.tech -// - -import Foundation - -/** Model for testing reserved words */ -public struct Return: Codable, Hashable { - - public var `return`: Int? - - public init(`return`: Int? = nil) { - self.`return` = `return` - } - - public enum CodingKeys: String, CodingKey, CaseIterable { - case `return` = "return" - } - -} diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/APIs.swift b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/APIs.swift index dbdab491ff7..941c61b713a 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/APIs.swift +++ b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/APIs.swift @@ -6,10 +6,13 @@ import Foundation -open class PetstoreClientAPI { +@available(*, deprecated, renamed: "PetstoreClient") +public typealias PetstoreClientAPI = PetstoreClient + +open class PetstoreClient { public static var basePath = "http://petstore.swagger.io:80/v2" - public static var credential: URLCredential? public static var customHeaders: [String: String] = [:] + public static var credential: URLCredential? public static var requestBuilderFactory: RequestBuilderFactory = URLSessionRequestBuilderFactory() public static var apiResponseQueue: DispatchQueue = .main } @@ -32,7 +35,7 @@ open class RequestBuilder { self.parameters = parameters self.headers = headers - addHeaders(PetstoreClientAPI.customHeaders) + addHeaders(PetstoreClient.customHeaders) } open func addHeaders(_ aHeaders: [String: String]) { @@ -41,7 +44,7 @@ open class RequestBuilder { } } - open func execute(_ apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, _ completion: @escaping (_ result: Swift.Result, Error>) -> Void) { } + open func execute(_ apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, _ completion: @escaping (_ result: Swift.Result, Error>) -> Void) { } public func addHeader(name: String, value: String) -> Self { if !value.isEmpty { @@ -51,7 +54,7 @@ open class RequestBuilder { } open func addCredential() -> Self { - credential = PetstoreClientAPI.credential + credential = PetstoreClient.credential return self } } 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 72b89640eeb..72f79eaf23d 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/APIs/AnotherFakeAPI.swift +++ b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/APIs/AnotherFakeAPI.swift @@ -6,8 +6,15 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +extension PetstoreClient { + open class AnotherFakeAPI { + /** To test special tags @@ -15,7 +22,7 @@ open class AnotherFakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func call123testSpecialTags(body: Client, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Client?, _ error: Error?) -> Void)) { + open class func call123testSpecialTags(body: Client, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Client?, _ error: Error?) -> Void)) { call123testSpecialTagsWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -34,21 +41,21 @@ open class AnotherFakeAPI { - returns: RequestBuilder */ open class func call123testSpecialTagsWithRequestBuilder(body: Client) -> RequestBuilder { - let path = "/another-fake/dummy" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/another-fake/dummy" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "PATCH", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "PATCH", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } - +} } 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 cf92424d9cc..63e6c322351 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/APIs/FakeAPI.swift +++ b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/APIs/FakeAPI.swift @@ -6,15 +6,22 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +extension PetstoreClient { + open class FakeAPI { + /** - parameter body: (body) Input boolean as post body (optional) - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func fakeOuterBooleanSerialize(body: Bool? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Bool?, _ error: Error?) -> Void)) { + open class func fakeOuterBooleanSerialize(body: Bool? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Bool?, _ error: Error?) -> Void)) { fakeOuterBooleanSerializeWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -32,21 +39,21 @@ open class FakeAPI { - returns: RequestBuilder */ open class func fakeOuterBooleanSerializeWithRequestBuilder(body: Bool? = nil) -> RequestBuilder { - let path = "/fake/outer/boolean" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/fake/outer/boolean" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -55,7 +62,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func fakeOuterCompositeSerialize(body: OuterComposite? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: OuterComposite?, _ error: Error?) -> Void)) { + open class func fakeOuterCompositeSerialize(body: OuterComposite? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: OuterComposite?, _ error: Error?) -> Void)) { fakeOuterCompositeSerializeWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -73,21 +80,21 @@ open class FakeAPI { - returns: RequestBuilder */ open class func fakeOuterCompositeSerializeWithRequestBuilder(body: OuterComposite? = nil) -> RequestBuilder { - let path = "/fake/outer/composite" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/fake/outer/composite" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -96,7 +103,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func fakeOuterNumberSerialize(body: Double? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Double?, _ error: Error?) -> Void)) { + open class func fakeOuterNumberSerialize(body: Double? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Double?, _ error: Error?) -> Void)) { fakeOuterNumberSerializeWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -114,21 +121,21 @@ open class FakeAPI { - returns: RequestBuilder */ open class func fakeOuterNumberSerializeWithRequestBuilder(body: Double? = nil) -> RequestBuilder { - let path = "/fake/outer/number" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/fake/outer/number" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -137,7 +144,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func fakeOuterStringSerialize(body: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: String?, _ error: Error?) -> Void)) { + open class func fakeOuterStringSerialize(body: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: String?, _ error: Error?) -> Void)) { fakeOuterStringSerializeWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -155,21 +162,21 @@ open class FakeAPI { - returns: RequestBuilder */ open class func fakeOuterStringSerializeWithRequestBuilder(body: String? = nil) -> RequestBuilder { - let path = "/fake/outer/string" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/fake/outer/string" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -178,7 +185,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func testBodyWithFileSchema(body: FileSchemaTestClass, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func testBodyWithFileSchema(body: FileSchemaTestClass, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { testBodyWithFileSchemaWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -196,21 +203,21 @@ open class FakeAPI { - returns: RequestBuilder */ open class func testBodyWithFileSchemaWithRequestBuilder(body: FileSchemaTestClass) -> RequestBuilder { - let path = "/fake/body-with-file-schema" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/fake/body-with-file-schema" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "PUT", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -220,7 +227,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func testBodyWithQueryParams(query: String, body: User, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func testBodyWithQueryParams(query: String, body: User, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { testBodyWithQueryParamsWithRequestBuilder(query: query, body: body).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -238,24 +245,24 @@ open class FakeAPI { - returns: RequestBuilder */ open class func testBodyWithQueryParamsWithRequestBuilder(query: String, body: User) -> RequestBuilder { - let path = "/fake/body-with-query-params" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/fake/body-with-query-params" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - var urlComponents = URLComponents(string: URLString) - urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ + var localVariableUrlComponents = URLComponents(string: localVariableURLString) + localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ "query": query.encodeToJSON(), ]) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "PUT", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -265,7 +272,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func testClientModel(body: Client, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Client?, _ error: Error?) -> Void)) { + open class func testClientModel(body: Client, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Client?, _ error: Error?) -> Void)) { testClientModelWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -284,21 +291,21 @@ open class FakeAPI { - returns: RequestBuilder */ open class func testClientModelWithRequestBuilder(body: Client) -> RequestBuilder { - let path = "/fake" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/fake" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "PATCH", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "PATCH", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -321,7 +328,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func testEndpointParameters(number: Double, double: Double, patternWithoutDelimiter: String, byte: Data, integer: Int? = nil, int32: Int? = nil, int64: Int64? = nil, float: Float? = nil, string: String? = nil, binary: URL? = nil, date: Date? = nil, dateTime: Date? = nil, password: String? = nil, callback: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func testEndpointParameters(number: Double, double: Double, patternWithoutDelimiter: String, byte: Data, integer: Int? = nil, int32: Int? = nil, int64: Int64? = nil, float: Float? = nil, string: String? = nil, binary: URL? = nil, date: Date? = nil, dateTime: Date? = nil, password: String? = nil, callback: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { testEndpointParametersWithRequestBuilder(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(apiResponseQueue) { result -> Void in switch result { case .success: @@ -356,9 +363,9 @@ open class FakeAPI { - returns: RequestBuilder */ open class func testEndpointParametersWithRequestBuilder(number: Double, double: Double, patternWithoutDelimiter: String, byte: Data, integer: Int? = nil, int32: Int? = nil, int64: Int64? = nil, float: Float? = nil, string: String? = nil, binary: URL? = nil, date: Date? = nil, dateTime: Date? = nil, password: String? = nil, callback: String? = nil) -> RequestBuilder { - let path = "/fake" - let URLString = PetstoreClientAPI.basePath + path - let formParams: [String: Any?] = [ + let localVariablePath = "/fake" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableFormParams: [String: Any?] = [ "integer": integer?.encodeToJSON(), "int32": int32?.encodeToJSON(), "int64": int64?.encodeToJSON(), @@ -375,20 +382,20 @@ open class FakeAPI { "callback": callback?.encodeToJSON(), ] - let nonNullParameters = APIHelper.rejectNil(formParams) - let parameters = APIHelper.convertBoolToString(nonNullParameters) + let localVariableNonNullParameters = APIHelper.rejectNil(localVariableFormParams) + let localVariableParameters = APIHelper.convertBoolToString(localVariableNonNullParameters) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ "Content-Type": "application/x-www-form-urlencoded", ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -472,7 +479,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func testEnumParameters(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func testEnumParameters(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { testEnumParametersWithRequestBuilder(enumHeaderStringArray: enumHeaderStringArray, enumHeaderString: enumHeaderString, enumQueryStringArray: enumQueryStringArray, enumQueryString: enumQueryString, enumQueryInteger: enumQueryInteger, enumQueryDouble: enumQueryDouble, enumFormStringArray: enumFormStringArray, enumFormString: enumFormString).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -498,35 +505,35 @@ open class FakeAPI { - returns: RequestBuilder */ open class func testEnumParametersWithRequestBuilder(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil) -> RequestBuilder { - let path = "/fake" - let URLString = PetstoreClientAPI.basePath + path - let formParams: [String: Any?] = [ + let localVariablePath = "/fake" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableFormParams: [String: Any?] = [ "enum_form_string_array": enumFormStringArray?.encodeToJSON(), "enum_form_string": enumFormString?.encodeToJSON(), ] - let nonNullParameters = APIHelper.rejectNil(formParams) - let parameters = APIHelper.convertBoolToString(nonNullParameters) + let localVariableNonNullParameters = APIHelper.rejectNil(localVariableFormParams) + let localVariableParameters = APIHelper.convertBoolToString(localVariableNonNullParameters) - var urlComponents = URLComponents(string: URLString) - urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ + var localVariableUrlComponents = URLComponents(string: localVariableURLString) + localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ "enum_query_string_array": enumQueryStringArray?.encodeToJSON(), "enum_query_string": enumQueryString?.encodeToJSON(), "enum_query_integer": enumQueryInteger?.encodeToJSON(), "enum_query_double": enumQueryDouble?.encodeToJSON(), ]) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ "Content-Type": "application/x-www-form-urlencoded", "enum_header_string_array": enumHeaderStringArray?.encodeToJSON(), "enum_header_string": enumHeaderString?.encodeToJSON(), ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -541,7 +548,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func testGroupParameters(requiredStringGroup: Int, requiredBooleanGroup: Bool, requiredInt64Group: Int64, stringGroup: Int? = nil, booleanGroup: Bool? = nil, int64Group: Int64? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func testGroupParameters(requiredStringGroup: Int, requiredBooleanGroup: Bool, requiredInt64Group: Int64, stringGroup: Int? = nil, booleanGroup: Bool? = nil, int64Group: Int64? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { testGroupParametersWithRequestBuilder(requiredStringGroup: requiredStringGroup, requiredBooleanGroup: requiredBooleanGroup, requiredInt64Group: requiredInt64Group, stringGroup: stringGroup, booleanGroup: booleanGroup, int64Group: int64Group).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -565,28 +572,28 @@ open class FakeAPI { - returns: RequestBuilder */ open class func testGroupParametersWithRequestBuilder(requiredStringGroup: Int, requiredBooleanGroup: Bool, requiredInt64Group: Int64, stringGroup: Int? = nil, booleanGroup: Bool? = nil, int64Group: Int64? = nil) -> RequestBuilder { - let path = "/fake" - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + let localVariablePath = "/fake" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - var urlComponents = URLComponents(string: URLString) - urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ + var localVariableUrlComponents = URLComponents(string: localVariableURLString) + localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ "required_string_group": requiredStringGroup.encodeToJSON(), "required_int64_group": requiredInt64Group.encodeToJSON(), "string_group": stringGroup?.encodeToJSON(), "int64_group": int64Group?.encodeToJSON(), ]) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ "required_boolean_group": requiredBooleanGroup.encodeToJSON(), "boolean_group": booleanGroup?.encodeToJSON(), ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "DELETE", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -596,7 +603,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func testInlineAdditionalProperties(param: [String: String], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func testInlineAdditionalProperties(param: [String: String], apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { testInlineAdditionalPropertiesWithRequestBuilder(param: param).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -614,21 +621,21 @@ open class FakeAPI { - returns: RequestBuilder */ open class func testInlineAdditionalPropertiesWithRequestBuilder(param: [String: String]) -> RequestBuilder { - let path = "/fake/inline-additionalProperties" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: param) + let localVariablePath = "/fake/inline-additionalProperties" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: param) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -639,7 +646,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func testJsonFormData(param: String, param2: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func testJsonFormData(param: String, param2: String, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { testJsonFormDataWithRequestBuilder(param: param, param2: param2).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -658,27 +665,27 @@ open class FakeAPI { - returns: RequestBuilder */ open class func testJsonFormDataWithRequestBuilder(param: String, param2: String) -> RequestBuilder { - let path = "/fake/jsonFormData" - let URLString = PetstoreClientAPI.basePath + path - let formParams: [String: Any?] = [ + let localVariablePath = "/fake/jsonFormData" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableFormParams: [String: Any?] = [ "param": param.encodeToJSON(), "param2": param2.encodeToJSON(), ] - let nonNullParameters = APIHelper.rejectNil(formParams) - let parameters = APIHelper.convertBoolToString(nonNullParameters) + let localVariableNonNullParameters = APIHelper.rejectNil(localVariableFormParams) + let localVariableParameters = APIHelper.convertBoolToString(localVariableNonNullParameters) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ "Content-Type": "application/x-www-form-urlencoded", ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } - +} } 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 d4d65166496..41e062ea4c2 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/APIs/FakeClassnameTags123API.swift +++ b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/APIs/FakeClassnameTags123API.swift @@ -6,8 +6,15 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +extension PetstoreClient { + open class FakeClassnameTags123API { + /** To test class name in snake case @@ -15,7 +22,7 @@ open class FakeClassnameTags123API { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func testClassname(body: Client, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Client?, _ error: Error?) -> Void)) { + open class func testClassname(body: Client, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Client?, _ error: Error?) -> Void)) { testClassnameWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -37,21 +44,21 @@ open class FakeClassnameTags123API { - returns: RequestBuilder */ open class func testClassnameWithRequestBuilder(body: Client) -> RequestBuilder { - let path = "/fake_classname_test" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/fake_classname_test" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "PATCH", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "PATCH", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } - +} } 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 a1fe0d12b1d..fda9d86850f 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/APIs/PetAPI.swift +++ b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/APIs/PetAPI.swift @@ -6,8 +6,15 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +extension PetstoreClient { + open class PetAPI { + /** Add a new pet to the store @@ -15,7 +22,7 @@ open class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func addPet(body: Pet, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func addPet(body: Pet, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { addPetWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -36,21 +43,21 @@ open class PetAPI { - returns: RequestBuilder */ open class func addPetWithRequestBuilder(body: Pet) -> RequestBuilder { - let path = "/pet" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/pet" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -61,7 +68,7 @@ open class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func deletePet(petId: Int64, apiKey: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func deletePet(petId: Int64, apiKey: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { deletePetWithRequestBuilder(petId: petId, apiKey: apiKey).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -83,24 +90,24 @@ open class PetAPI { - returns: RequestBuilder */ open class func deletePetWithRequestBuilder(petId: Int64, apiKey: String? = nil) -> RequestBuilder { - var path = "/pet/{petId}" + var localVariablePath = "/pet/{petId}" let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))" let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" - path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + localVariablePath = localVariablePath.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ "api_key": apiKey?.encodeToJSON(), ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "DELETE", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -119,7 +126,7 @@ open class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func findPetsByStatus(status: [String], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: [Pet]?, _ error: Error?) -> Void)) { + open class func findPetsByStatus(status: [String], apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: [Pet]?, _ error: Error?) -> Void)) { findPetsByStatusWithRequestBuilder(status: status).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -141,24 +148,24 @@ open class PetAPI { - returns: RequestBuilder<[Pet]> */ open class func findPetsByStatusWithRequestBuilder(status: [String]) -> RequestBuilder<[Pet]> { - let path = "/pet/findByStatus" - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + let localVariablePath = "/pet/findByStatus" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - var urlComponents = URLComponents(string: URLString) - urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ + var localVariableUrlComponents = URLComponents(string: localVariableURLString) + localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ "status": status.encodeToJSON(), ]) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -169,7 +176,7 @@ open class PetAPI { - parameter completion: completion handler to receive the data and the error objects */ @available(*, deprecated, message: "This operation is deprecated.") - open class func findPetsByTags(tags: [String], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: [Pet]?, _ error: Error?) -> Void)) { + open class func findPetsByTags(tags: [String], apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: [Pet]?, _ error: Error?) -> Void)) { findPetsByTagsWithRequestBuilder(tags: tags).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -192,24 +199,24 @@ open class PetAPI { */ @available(*, deprecated, message: "This operation is deprecated.") open class func findPetsByTagsWithRequestBuilder(tags: [String]) -> RequestBuilder<[Pet]> { - let path = "/pet/findByTags" - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + let localVariablePath = "/pet/findByTags" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - var urlComponents = URLComponents(string: URLString) - urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ + var localVariableUrlComponents = URLComponents(string: localVariableURLString) + localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ "tags": tags.encodeToJSON(), ]) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -219,7 +226,7 @@ open class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func getPetById(petId: Int64, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Pet?, _ error: Error?) -> Void)) { + open class func getPetById(petId: Int64, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Pet?, _ error: Error?) -> Void)) { getPetByIdWithRequestBuilder(petId: petId).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -241,24 +248,24 @@ open class PetAPI { - returns: RequestBuilder */ open class func getPetByIdWithRequestBuilder(petId: Int64) -> RequestBuilder { - var path = "/pet/{petId}" + var localVariablePath = "/pet/{petId}" let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))" let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" - path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + localVariablePath = localVariablePath.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -268,7 +275,7 @@ open class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func updatePet(body: Pet, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func updatePet(body: Pet, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { updatePetWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -289,21 +296,21 @@ open class PetAPI { - returns: RequestBuilder */ open class func updatePetWithRequestBuilder(body: Pet) -> RequestBuilder { - let path = "/pet" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/pet" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "PUT", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -315,7 +322,7 @@ open class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func updatePetWithForm(petId: Int64, name: String? = nil, status: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func updatePetWithForm(petId: Int64, name: String? = nil, status: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { updatePetWithFormWithRequestBuilder(petId: petId, name: name, status: status).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -338,30 +345,30 @@ open class PetAPI { - returns: RequestBuilder */ open class func updatePetWithFormWithRequestBuilder(petId: Int64, name: String? = nil, status: String? = nil) -> RequestBuilder { - var path = "/pet/{petId}" + var localVariablePath = "/pet/{petId}" let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))" let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" - path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path - let formParams: [String: Any?] = [ + localVariablePath = localVariablePath.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableFormParams: [String: Any?] = [ "name": name?.encodeToJSON(), "status": status?.encodeToJSON(), ] - let nonNullParameters = APIHelper.rejectNil(formParams) - let parameters = APIHelper.convertBoolToString(nonNullParameters) + let localVariableNonNullParameters = APIHelper.rejectNil(localVariableFormParams) + let localVariableParameters = APIHelper.convertBoolToString(localVariableNonNullParameters) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ "Content-Type": "application/x-www-form-urlencoded", ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -373,7 +380,7 @@ open class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func uploadFile(petId: Int64, additionalMetadata: String? = nil, file: URL? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: ApiResponse?, _ error: Error?) -> Void)) { + open class func uploadFile(petId: Int64, additionalMetadata: String? = nil, file: URL? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: ApiResponse?, _ error: Error?) -> Void)) { uploadFileWithRequestBuilder(petId: petId, additionalMetadata: additionalMetadata, file: file).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -396,30 +403,30 @@ open class PetAPI { - returns: RequestBuilder */ open class func uploadFileWithRequestBuilder(petId: Int64, additionalMetadata: String? = nil, file: URL? = nil) -> RequestBuilder { - var path = "/pet/{petId}/uploadImage" + var localVariablePath = "/pet/{petId}/uploadImage" let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))" let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" - path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path - let formParams: [String: Any?] = [ + localVariablePath = localVariablePath.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableFormParams: [String: Any?] = [ "additionalMetadata": additionalMetadata?.encodeToJSON(), "file": file?.encodeToJSON(), ] - let nonNullParameters = APIHelper.rejectNil(formParams) - let parameters = APIHelper.convertBoolToString(nonNullParameters) + let localVariableNonNullParameters = APIHelper.rejectNil(localVariableFormParams) + let localVariableParameters = APIHelper.convertBoolToString(localVariableNonNullParameters) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ "Content-Type": "multipart/form-data", ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -431,7 +438,7 @@ open class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func uploadFileWithRequiredFile(petId: Int64, requiredFile: URL, additionalMetadata: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: ApiResponse?, _ error: Error?) -> Void)) { + open class func uploadFileWithRequiredFile(petId: Int64, requiredFile: URL, additionalMetadata: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: ApiResponse?, _ error: Error?) -> Void)) { uploadFileWithRequiredFileWithRequestBuilder(petId: petId, requiredFile: requiredFile, additionalMetadata: additionalMetadata).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -454,30 +461,30 @@ open class PetAPI { - returns: RequestBuilder */ open class func uploadFileWithRequiredFileWithRequestBuilder(petId: Int64, requiredFile: URL, additionalMetadata: String? = nil) -> RequestBuilder { - var path = "/fake/{petId}/uploadImageWithRequiredFile" + var localVariablePath = "/fake/{petId}/uploadImageWithRequiredFile" let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))" let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" - path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path - let formParams: [String: Any?] = [ + localVariablePath = localVariablePath.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableFormParams: [String: Any?] = [ "additionalMetadata": additionalMetadata?.encodeToJSON(), "requiredFile": requiredFile.encodeToJSON(), ] - let nonNullParameters = APIHelper.rejectNil(formParams) - let parameters = APIHelper.convertBoolToString(nonNullParameters) + let localVariableNonNullParameters = APIHelper.rejectNil(localVariableFormParams) + let localVariableParameters = APIHelper.convertBoolToString(localVariableNonNullParameters) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ "Content-Type": "multipart/form-data", ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } - +} } diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/APIs/StoreAPI.swift b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/APIs/StoreAPI.swift index 501f11f5f21..eb39c79cb6b 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/APIs/StoreAPI.swift +++ b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/APIs/StoreAPI.swift @@ -6,8 +6,15 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +extension PetstoreClient { + open class StoreAPI { + /** Delete purchase order by ID @@ -15,7 +22,7 @@ open class StoreAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func deleteOrder(orderId: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func deleteOrder(orderId: String, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { deleteOrderWithRequestBuilder(orderId: orderId).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -34,24 +41,24 @@ open class StoreAPI { - returns: RequestBuilder */ open class func deleteOrderWithRequestBuilder(orderId: String) -> RequestBuilder { - var path = "/store/order/{order_id}" + var localVariablePath = "/store/order/{order_id}" let orderIdPreEscape = "\(APIHelper.mapValueToPathItem(orderId))" let orderIdPostEscape = orderIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" - path = path.replacingOccurrences(of: "{order_id}", with: orderIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + localVariablePath = localVariablePath.replacingOccurrences(of: "{order_id}", with: orderIdPostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "DELETE", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -60,7 +67,7 @@ open class StoreAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func getInventory(apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: [String: Int]?, _ error: Error?) -> Void)) { + open class func getInventory(apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: [String: Int]?, _ error: Error?) -> Void)) { getInventoryWithRequestBuilder().execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -81,21 +88,21 @@ open class StoreAPI { - returns: RequestBuilder<[String: Int]> */ open class func getInventoryWithRequestBuilder() -> RequestBuilder<[String: Int]> { - let path = "/store/inventory" - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + let localVariablePath = "/store/inventory" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder<[String: Int]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder<[String: Int]>.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -105,7 +112,7 @@ open class StoreAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func getOrderById(orderId: Int64, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Order?, _ error: Error?) -> Void)) { + open class func getOrderById(orderId: Int64, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Order?, _ error: Error?) -> Void)) { getOrderByIdWithRequestBuilder(orderId: orderId).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -124,24 +131,24 @@ open class StoreAPI { - returns: RequestBuilder */ open class func getOrderByIdWithRequestBuilder(orderId: Int64) -> RequestBuilder { - var path = "/store/order/{order_id}" + var localVariablePath = "/store/order/{order_id}" let orderIdPreEscape = "\(APIHelper.mapValueToPathItem(orderId))" let orderIdPostEscape = orderIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" - path = path.replacingOccurrences(of: "{order_id}", with: orderIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + localVariablePath = localVariablePath.replacingOccurrences(of: "{order_id}", with: orderIdPostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -151,7 +158,7 @@ open class StoreAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func placeOrder(body: Order, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Order?, _ error: Error?) -> Void)) { + open class func placeOrder(body: Order, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Order?, _ error: Error?) -> Void)) { placeOrderWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -169,21 +176,21 @@ open class StoreAPI { - returns: RequestBuilder */ open class func placeOrderWithRequestBuilder(body: Order) -> RequestBuilder { - let path = "/store/order" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/store/order" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } - +} } diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/APIs/UserAPI.swift b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/APIs/UserAPI.swift index 254474014d3..9a97c60cca7 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/APIs/UserAPI.swift +++ b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/APIs/UserAPI.swift @@ -6,8 +6,15 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +extension PetstoreClient { + open class UserAPI { + /** Create user @@ -15,7 +22,7 @@ open class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func createUser(body: User, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func createUser(body: User, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { createUserWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -34,21 +41,21 @@ open class UserAPI { - returns: RequestBuilder */ open class func createUserWithRequestBuilder(body: User) -> RequestBuilder { - let path = "/user" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/user" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -58,7 +65,7 @@ open class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func createUsersWithArrayInput(body: [User], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func createUsersWithArrayInput(body: [User], apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { createUsersWithArrayInputWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -76,21 +83,21 @@ open class UserAPI { - returns: RequestBuilder */ open class func createUsersWithArrayInputWithRequestBuilder(body: [User]) -> RequestBuilder { - let path = "/user/createWithArray" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/user/createWithArray" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -100,7 +107,7 @@ open class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func createUsersWithListInput(body: [User], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func createUsersWithListInput(body: [User], apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { createUsersWithListInputWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -118,21 +125,21 @@ open class UserAPI { - returns: RequestBuilder */ open class func createUsersWithListInputWithRequestBuilder(body: [User]) -> RequestBuilder { - let path = "/user/createWithList" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/user/createWithList" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -142,7 +149,7 @@ open class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func deleteUser(username: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func deleteUser(username: String, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { deleteUserWithRequestBuilder(username: username).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -161,24 +168,24 @@ open class UserAPI { - returns: RequestBuilder */ open class func deleteUserWithRequestBuilder(username: String) -> RequestBuilder { - var path = "/user/{username}" + var localVariablePath = "/user/{username}" let usernamePreEscape = "\(APIHelper.mapValueToPathItem(username))" let usernamePostEscape = usernamePreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" - path = path.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + localVariablePath = localVariablePath.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "DELETE", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -188,7 +195,7 @@ open class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func getUserByName(username: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: User?, _ error: Error?) -> Void)) { + open class func getUserByName(username: String, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: User?, _ error: Error?) -> Void)) { getUserByNameWithRequestBuilder(username: username).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -206,24 +213,24 @@ open class UserAPI { - returns: RequestBuilder */ open class func getUserByNameWithRequestBuilder(username: String) -> RequestBuilder { - var path = "/user/{username}" + var localVariablePath = "/user/{username}" let usernamePreEscape = "\(APIHelper.mapValueToPathItem(username))" let usernamePostEscape = usernamePreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" - path = path.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + localVariablePath = localVariablePath.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -234,7 +241,7 @@ open class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func loginUser(username: String, password: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: String?, _ error: Error?) -> Void)) { + open class func loginUser(username: String, password: String, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: String?, _ error: Error?) -> Void)) { loginUserWithRequestBuilder(username: username, password: password).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -254,25 +261,25 @@ open class UserAPI { - returns: RequestBuilder */ open class func loginUserWithRequestBuilder(username: String, password: String) -> RequestBuilder { - let path = "/user/login" - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + let localVariablePath = "/user/login" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - var urlComponents = URLComponents(string: URLString) - urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ + var localVariableUrlComponents = URLComponents(string: localVariableURLString) + localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ "username": username.encodeToJSON(), "password": password.encodeToJSON(), ]) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -281,7 +288,7 @@ open class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func logoutUser(apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func logoutUser(apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { logoutUserWithRequestBuilder().execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -298,21 +305,21 @@ open class UserAPI { - returns: RequestBuilder */ open class func logoutUserWithRequestBuilder() -> RequestBuilder { - let path = "/user/logout" - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + let localVariablePath = "/user/logout" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -323,7 +330,7 @@ open class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func updateUser(username: String, body: User, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func updateUser(username: String, body: User, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { updateUserWithRequestBuilder(username: username, body: body).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -343,24 +350,24 @@ open class UserAPI { - returns: RequestBuilder */ open class func updateUserWithRequestBuilder(username: String, body: User) -> RequestBuilder { - var path = "/user/{username}" + var localVariablePath = "/user/{username}" let usernamePreEscape = "\(APIHelper.mapValueToPathItem(username))" let usernamePostEscape = usernamePreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" - path = path.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + localVariablePath = localVariablePath.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "PUT", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } - +} } diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Configuration.swift b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Configuration.swift index 18edabbed78..410882590eb 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Configuration.swift +++ b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Configuration.swift @@ -6,9 +6,16 @@ import Foundation +@available(*, deprecated, renamed: "PetstoreClient.Configuration") +public typealias Configuration = PetstoreClient.Configuration + +extension PetstoreClient { open class Configuration { + // This value is used to configure the date formatter that is used to serialize dates into JSON format. // You must set it prior to encoding any dates, and it will only be read once. @available(*, unavailable, message: "To set a different date format, use CodableHelper.dateFormatter instead.") public static var dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ" } +} + diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Extensions.swift b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Extensions.swift index 3aef2d1d6c5..e23035dde30 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Extensions.swift +++ b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Extensions.swift @@ -5,7 +5,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif extension Bool: JSONEncodable { func encodeToJSON() -> Any { return self as Any } @@ -184,44 +186,3 @@ extension HTTPURLResponse { return Array(200 ..< 300).contains(statusCode) } } - -extension AnyCodable: Hashable { - public func hash(into hasher: inout Hasher) { - switch value { - case let value as Bool: - hasher.combine(value) - case let value as Int: - hasher.combine(value) - case let value as Int8: - hasher.combine(value) - case let value as Int16: - hasher.combine(value) - case let value as Int32: - hasher.combine(value) - case let value as Int64: - hasher.combine(value) - case let value as UInt: - hasher.combine(value) - case let value as UInt8: - hasher.combine(value) - case let value as UInt16: - hasher.combine(value) - case let value as UInt32: - hasher.combine(value) - case let value as UInt64: - hasher.combine(value) - case let value as Float: - hasher.combine(value) - case let value as Double: - hasher.combine(value) - case let value as String: - hasher.combine(value) - case let value as [String: AnyCodable]: - hasher.combine(value) - case let value as [AnyCodable]: - hasher.combine(value) - default: - hasher.combine(0) - } - } -} \ No newline at end of file diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/AdditionalPropertiesClass.swift b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/AdditionalPropertiesClass.swift index 5c3e8279143..7f5b6a45ade 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/AdditionalPropertiesClass.swift +++ b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/AdditionalPropertiesClass.swift @@ -6,7 +6,14 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif + +@available(*, deprecated, renamed: "PetstoreClient.AdditionalPropertiesClass") +public typealias AdditionalPropertiesClass = PetstoreClient.AdditionalPropertiesClass + +extension PetstoreClient { public final class AdditionalPropertiesClass: Codable, Hashable { @@ -17,6 +24,7 @@ public final class AdditionalPropertiesClass: Codable, Hashable { self.mapString = mapString self.mapMapString = mapMapString } + public enum CodingKeys: String, CodingKey, CaseIterable { case mapString = "map_string" case mapMapString = "map_map_string" @@ -30,8 +38,6 @@ public final class AdditionalPropertiesClass: Codable, Hashable { try container.encodeIfPresent(mapMapString, forKey: .mapMapString) } - - public static func == (lhs: AdditionalPropertiesClass, rhs: AdditionalPropertiesClass) -> Bool { lhs.mapString == rhs.mapString && lhs.mapMapString == rhs.mapMapString @@ -43,5 +49,6 @@ public final class AdditionalPropertiesClass: Codable, Hashable { hasher.combine(mapMapString?.hashValue) } +} } diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/Animal.swift b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/Animal.swift index 6bae9f2d0ec..24b111486de 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/Animal.swift +++ b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/Animal.swift @@ -6,7 +6,14 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif + +@available(*, deprecated, renamed: "PetstoreClient.Animal") +public typealias Animal = PetstoreClient.Animal + +extension PetstoreClient { public final class Animal: Codable, Hashable { @@ -17,6 +24,7 @@ public final class Animal: Codable, Hashable { self.className = className self.color = color } + public enum CodingKeys: String, CodingKey, CaseIterable { case className case color @@ -30,8 +38,6 @@ public final class Animal: Codable, Hashable { try container.encodeIfPresent(color, forKey: .color) } - - public static func == (lhs: Animal, rhs: Animal) -> Bool { lhs.className == rhs.className && lhs.color == rhs.color @@ -43,5 +49,6 @@ public final class Animal: Codable, Hashable { hasher.combine(color?.hashValue) } +} } diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/AnimalFarm.swift b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/AnimalFarm.swift index b20b894a1ad..ef664c5e452 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/AnimalFarm.swift +++ b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/AnimalFarm.swift @@ -6,6 +6,14 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif + +@available(*, deprecated, renamed: "PetstoreClient.AnimalFarm") +public typealias AnimalFarm = PetstoreClient.AnimalFarm + +extension PetstoreClient { public typealias AnimalFarm = [Animal] +} diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/ApiResponse.swift b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/ApiResponse.swift index a0f3a24a8ee..d6e874cad6c 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/ApiResponse.swift +++ b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/ApiResponse.swift @@ -6,7 +6,14 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif + +@available(*, deprecated, renamed: "PetstoreClient.ApiResponse") +public typealias ApiResponse = PetstoreClient.ApiResponse + +extension PetstoreClient { public final class ApiResponse: Codable, Hashable { @@ -19,6 +26,7 @@ public final class ApiResponse: Codable, Hashable { self.type = type self.message = message } + public enum CodingKeys: String, CodingKey, CaseIterable { case code case type @@ -34,8 +42,6 @@ public final class ApiResponse: Codable, Hashable { try container.encodeIfPresent(message, forKey: .message) } - - public static func == (lhs: ApiResponse, rhs: ApiResponse) -> Bool { lhs.code == rhs.code && lhs.type == rhs.type && @@ -49,5 +55,6 @@ public final class ApiResponse: Codable, Hashable { hasher.combine(message?.hashValue) } +} } diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/ArrayOfArrayOfNumberOnly.swift b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/ArrayOfArrayOfNumberOnly.swift index b4b66b37be5..46175c0b05e 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/ArrayOfArrayOfNumberOnly.swift +++ b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/ArrayOfArrayOfNumberOnly.swift @@ -6,7 +6,14 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif + +@available(*, deprecated, renamed: "PetstoreClient.ArrayOfArrayOfNumberOnly") +public typealias ArrayOfArrayOfNumberOnly = PetstoreClient.ArrayOfArrayOfNumberOnly + +extension PetstoreClient { public final class ArrayOfArrayOfNumberOnly: Codable, Hashable { @@ -15,6 +22,7 @@ public final class ArrayOfArrayOfNumberOnly: Codable, Hashable { public init(arrayArrayNumber: [[Double]]? = nil) { self.arrayArrayNumber = arrayArrayNumber } + public enum CodingKeys: String, CodingKey, CaseIterable { case arrayArrayNumber = "ArrayArrayNumber" } @@ -26,8 +34,6 @@ public final class ArrayOfArrayOfNumberOnly: Codable, Hashable { try container.encodeIfPresent(arrayArrayNumber, forKey: .arrayArrayNumber) } - - public static func == (lhs: ArrayOfArrayOfNumberOnly, rhs: ArrayOfArrayOfNumberOnly) -> Bool { lhs.arrayArrayNumber == rhs.arrayArrayNumber @@ -37,5 +43,6 @@ public final class ArrayOfArrayOfNumberOnly: Codable, Hashable { hasher.combine(arrayArrayNumber?.hashValue) } +} } diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/ArrayOfNumberOnly.swift b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/ArrayOfNumberOnly.swift index 1efbc2aa9e4..240989ed68e 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/ArrayOfNumberOnly.swift +++ b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/ArrayOfNumberOnly.swift @@ -6,7 +6,14 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif + +@available(*, deprecated, renamed: "PetstoreClient.ArrayOfNumberOnly") +public typealias ArrayOfNumberOnly = PetstoreClient.ArrayOfNumberOnly + +extension PetstoreClient { public final class ArrayOfNumberOnly: Codable, Hashable { @@ -15,6 +22,7 @@ public final class ArrayOfNumberOnly: Codable, Hashable { public init(arrayNumber: [Double]? = nil) { self.arrayNumber = arrayNumber } + public enum CodingKeys: String, CodingKey, CaseIterable { case arrayNumber = "ArrayNumber" } @@ -26,8 +34,6 @@ public final class ArrayOfNumberOnly: Codable, Hashable { try container.encodeIfPresent(arrayNumber, forKey: .arrayNumber) } - - public static func == (lhs: ArrayOfNumberOnly, rhs: ArrayOfNumberOnly) -> Bool { lhs.arrayNumber == rhs.arrayNumber @@ -37,5 +43,6 @@ public final class ArrayOfNumberOnly: Codable, Hashable { hasher.combine(arrayNumber?.hashValue) } +} } diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/ArrayTest.swift b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/ArrayTest.swift index 6ca479263d3..fc774738102 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/ArrayTest.swift +++ b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/ArrayTest.swift @@ -6,7 +6,14 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif + +@available(*, deprecated, renamed: "PetstoreClient.ArrayTest") +public typealias ArrayTest = PetstoreClient.ArrayTest + +extension PetstoreClient { public final class ArrayTest: Codable, Hashable { @@ -19,6 +26,7 @@ public final class ArrayTest: Codable, Hashable { self.arrayArrayOfInteger = arrayArrayOfInteger self.arrayArrayOfModel = arrayArrayOfModel } + public enum CodingKeys: String, CodingKey, CaseIterable { case arrayOfString = "array_of_string" case arrayArrayOfInteger = "array_array_of_integer" @@ -34,8 +42,6 @@ public final class ArrayTest: Codable, Hashable { try container.encodeIfPresent(arrayArrayOfModel, forKey: .arrayArrayOfModel) } - - public static func == (lhs: ArrayTest, rhs: ArrayTest) -> Bool { lhs.arrayOfString == rhs.arrayOfString && lhs.arrayArrayOfInteger == rhs.arrayArrayOfInteger && @@ -49,5 +55,6 @@ public final class ArrayTest: Codable, Hashable { hasher.combine(arrayArrayOfModel?.hashValue) } +} } diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/Capitalization.swift b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/Capitalization.swift index fd148a09d29..2c3e64811a3 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/Capitalization.swift +++ b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/Capitalization.swift @@ -6,7 +6,14 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif + +@available(*, deprecated, renamed: "PetstoreClient.Capitalization") +public typealias Capitalization = PetstoreClient.Capitalization + +extension PetstoreClient { public final class Capitalization: Codable, Hashable { @@ -26,6 +33,7 @@ public final class Capitalization: Codable, Hashable { self.sCAETHFlowPoints = sCAETHFlowPoints self.ATT_NAME = ATT_NAME } + public enum CodingKeys: String, CodingKey, CaseIterable { case smallCamel case capitalCamel = "CapitalCamel" @@ -47,8 +55,6 @@ public final class Capitalization: Codable, Hashable { try container.encodeIfPresent(ATT_NAME, forKey: .ATT_NAME) } - - public static func == (lhs: Capitalization, rhs: Capitalization) -> Bool { lhs.smallCamel == rhs.smallCamel && lhs.capitalCamel == rhs.capitalCamel && @@ -68,5 +74,6 @@ public final class Capitalization: Codable, Hashable { hasher.combine(ATT_NAME?.hashValue) } +} } diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/Cat.swift b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/Cat.swift index 54b81364f35..16834ea68f4 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/Cat.swift +++ b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/Cat.swift @@ -6,7 +6,14 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif + +@available(*, deprecated, renamed: "PetstoreClient.Cat") +public typealias Cat = PetstoreClient.Cat + +extension PetstoreClient { public final class Cat: Codable, Hashable { @@ -19,6 +26,7 @@ public final class Cat: Codable, Hashable { self.color = color self.declawed = declawed } + public enum CodingKeys: String, CodingKey, CaseIterable { case className case color @@ -34,8 +42,6 @@ public final class Cat: Codable, Hashable { try container.encodeIfPresent(declawed, forKey: .declawed) } - - public static func == (lhs: Cat, rhs: Cat) -> Bool { lhs.className == rhs.className && lhs.color == rhs.color && @@ -49,5 +55,6 @@ public final class Cat: Codable, Hashable { hasher.combine(declawed?.hashValue) } +} } diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/CatAllOf.swift b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/CatAllOf.swift index 5074d59cb5d..15b96135e89 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/CatAllOf.swift +++ b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/CatAllOf.swift @@ -6,7 +6,14 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif + +@available(*, deprecated, renamed: "PetstoreClient.CatAllOf") +public typealias CatAllOf = PetstoreClient.CatAllOf + +extension PetstoreClient { public final class CatAllOf: Codable, Hashable { @@ -15,6 +22,7 @@ public final class CatAllOf: Codable, Hashable { public init(declawed: Bool? = nil) { self.declawed = declawed } + public enum CodingKeys: String, CodingKey, CaseIterable { case declawed } @@ -26,8 +34,6 @@ public final class CatAllOf: Codable, Hashable { try container.encodeIfPresent(declawed, forKey: .declawed) } - - public static func == (lhs: CatAllOf, rhs: CatAllOf) -> Bool { lhs.declawed == rhs.declawed @@ -37,5 +43,6 @@ public final class CatAllOf: Codable, Hashable { hasher.combine(declawed?.hashValue) } +} } diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/Category.swift b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/Category.swift index 242fc578d45..f0427d76d28 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/Category.swift +++ b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/Category.swift @@ -6,7 +6,14 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif + +@available(*, deprecated, renamed: "PetstoreClient.Category") +public typealias Category = PetstoreClient.Category + +extension PetstoreClient { public final class Category: Codable, Hashable { @@ -17,6 +24,7 @@ public final class Category: Codable, Hashable { self.id = id self.name = name } + public enum CodingKeys: String, CodingKey, CaseIterable { case id case name @@ -30,8 +38,6 @@ public final class Category: Codable, Hashable { try container.encode(name, forKey: .name) } - - public static func == (lhs: Category, rhs: Category) -> Bool { lhs.id == rhs.id && lhs.name == rhs.name @@ -43,5 +49,6 @@ public final class Category: Codable, Hashable { hasher.combine(name.hashValue) } +} } diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/ClassModel.swift b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/ClassModel.swift index ba363df9d14..ff0539ba0b5 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/ClassModel.swift +++ b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/ClassModel.swift @@ -6,7 +6,14 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif + +@available(*, deprecated, renamed: "PetstoreClient.ClassModel") +public typealias ClassModel = PetstoreClient.ClassModel + +extension PetstoreClient { /** Model for testing model with \"_class\" property */ public final class ClassModel: Codable, Hashable { @@ -16,6 +23,7 @@ public final class ClassModel: Codable, Hashable { public init(_class: String? = nil) { self._class = _class } + public enum CodingKeys: String, CodingKey, CaseIterable { case _class } @@ -27,8 +35,6 @@ public final class ClassModel: Codable, Hashable { try container.encodeIfPresent(_class, forKey: ._class) } - - public static func == (lhs: ClassModel, rhs: ClassModel) -> Bool { lhs._class == rhs._class @@ -38,5 +44,6 @@ public final class ClassModel: Codable, Hashable { hasher.combine(_class?.hashValue) } +} } diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/Client.swift b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/Client.swift index 323ab20082d..effc6525144 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/Client.swift +++ b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/Client.swift @@ -6,7 +6,14 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif + +@available(*, deprecated, renamed: "PetstoreClient.Client") +public typealias Client = PetstoreClient.Client + +extension PetstoreClient { public final class Client: Codable, Hashable { @@ -15,6 +22,7 @@ public final class Client: Codable, Hashable { public init(client: String? = nil) { self.client = client } + public enum CodingKeys: String, CodingKey, CaseIterable { case client } @@ -26,8 +34,6 @@ public final class Client: Codable, Hashable { try container.encodeIfPresent(client, forKey: .client) } - - public static func == (lhs: Client, rhs: Client) -> Bool { lhs.client == rhs.client @@ -37,5 +43,6 @@ public final class Client: Codable, Hashable { hasher.combine(client?.hashValue) } +} } diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/Dog.swift b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/Dog.swift index ec8a6748035..ccab17d0209 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/Dog.swift +++ b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/Dog.swift @@ -6,7 +6,14 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif + +@available(*, deprecated, renamed: "PetstoreClient.Dog") +public typealias Dog = PetstoreClient.Dog + +extension PetstoreClient { public final class Dog: Codable, Hashable { @@ -19,6 +26,7 @@ public final class Dog: Codable, Hashable { self.color = color self.breed = breed } + public enum CodingKeys: String, CodingKey, CaseIterable { case className case color @@ -34,8 +42,6 @@ public final class Dog: Codable, Hashable { try container.encodeIfPresent(breed, forKey: .breed) } - - public static func == (lhs: Dog, rhs: Dog) -> Bool { lhs.className == rhs.className && lhs.color == rhs.color && @@ -49,5 +55,6 @@ public final class Dog: Codable, Hashable { hasher.combine(breed?.hashValue) } +} } diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/DogAllOf.swift b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/DogAllOf.swift index 82d185f1a42..20b02ab06b7 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/DogAllOf.swift +++ b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/DogAllOf.swift @@ -6,7 +6,14 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif + +@available(*, deprecated, renamed: "PetstoreClient.DogAllOf") +public typealias DogAllOf = PetstoreClient.DogAllOf + +extension PetstoreClient { public final class DogAllOf: Codable, Hashable { @@ -15,6 +22,7 @@ public final class DogAllOf: Codable, Hashable { public init(breed: String? = nil) { self.breed = breed } + public enum CodingKeys: String, CodingKey, CaseIterable { case breed } @@ -26,8 +34,6 @@ public final class DogAllOf: Codable, Hashable { try container.encodeIfPresent(breed, forKey: .breed) } - - public static func == (lhs: DogAllOf, rhs: DogAllOf) -> Bool { lhs.breed == rhs.breed @@ -37,5 +43,6 @@ public final class DogAllOf: Codable, Hashable { hasher.combine(breed?.hashValue) } +} } diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/EnumArrays.swift b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/EnumArrays.swift index 573cb86e1ba..a1eb07aa955 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/EnumArrays.swift +++ b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/EnumArrays.swift @@ -6,7 +6,14 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif + +@available(*, deprecated, renamed: "PetstoreClient.EnumArrays") +public typealias EnumArrays = PetstoreClient.EnumArrays + +extension PetstoreClient { public final class EnumArrays: Codable, Hashable { @@ -25,6 +32,7 @@ public final class EnumArrays: Codable, Hashable { self.justSymbol = justSymbol self.arrayEnum = arrayEnum } + public enum CodingKeys: String, CodingKey, CaseIterable { case justSymbol = "just_symbol" case arrayEnum = "array_enum" @@ -38,8 +46,6 @@ public final class EnumArrays: Codable, Hashable { try container.encodeIfPresent(arrayEnum, forKey: .arrayEnum) } - - public static func == (lhs: EnumArrays, rhs: EnumArrays) -> Bool { lhs.justSymbol == rhs.justSymbol && lhs.arrayEnum == rhs.arrayEnum @@ -51,5 +57,6 @@ public final class EnumArrays: Codable, Hashable { hasher.combine(arrayEnum?.hashValue) } +} } diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/EnumClass.swift b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/EnumClass.swift index ab01cf297f8..37984373236 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/EnumClass.swift +++ b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/EnumClass.swift @@ -6,10 +6,18 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif + +@available(*, deprecated, renamed: "PetstoreClient.EnumClass") +public typealias EnumClass = PetstoreClient.EnumClass + +extension PetstoreClient { public enum EnumClass: String, Codable, CaseIterable { case abc = "_abc" case efg = "-efg" case xyz = "(xyz)" } +} diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/EnumTest.swift b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/EnumTest.swift index ca04771171b..4b39f2161f1 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/EnumTest.swift +++ b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/EnumTest.swift @@ -6,7 +6,14 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif + +@available(*, deprecated, renamed: "PetstoreClient.EnumTest") +public typealias EnumTest = PetstoreClient.EnumTest + +extension PetstoreClient { public final class EnumTest: Codable, Hashable { @@ -41,6 +48,7 @@ public final class EnumTest: Codable, Hashable { self.enumNumber = enumNumber self.outerEnum = outerEnum } + public enum CodingKeys: String, CodingKey, CaseIterable { case enumString = "enum_string" case enumStringRequired = "enum_string_required" @@ -60,8 +68,6 @@ public final class EnumTest: Codable, Hashable { try container.encodeIfPresent(outerEnum, forKey: .outerEnum) } - - public static func == (lhs: EnumTest, rhs: EnumTest) -> Bool { lhs.enumString == rhs.enumString && lhs.enumStringRequired == rhs.enumStringRequired && @@ -79,5 +85,6 @@ public final class EnumTest: Codable, Hashable { hasher.combine(outerEnum?.hashValue) } +} } diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/File.swift b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/File.swift index a899d021b87..ad1922e129b 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/File.swift +++ b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/File.swift @@ -6,7 +6,14 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif + +@available(*, deprecated, renamed: "PetstoreClient.File") +public typealias File = PetstoreClient.File + +extension PetstoreClient { /** Must be named `File` for test. */ public final class File: Codable, Hashable { @@ -17,6 +24,7 @@ public final class File: Codable, Hashable { public init(sourceURI: String? = nil) { self.sourceURI = sourceURI } + public enum CodingKeys: String, CodingKey, CaseIterable { case sourceURI } @@ -28,8 +36,6 @@ public final class File: Codable, Hashable { try container.encodeIfPresent(sourceURI, forKey: .sourceURI) } - - public static func == (lhs: File, rhs: File) -> Bool { lhs.sourceURI == rhs.sourceURI @@ -39,5 +45,6 @@ public final class File: Codable, Hashable { hasher.combine(sourceURI?.hashValue) } +} } diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/FileSchemaTestClass.swift b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/FileSchemaTestClass.swift index 2465bd5103f..523b2bab52e 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/FileSchemaTestClass.swift +++ b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/FileSchemaTestClass.swift @@ -6,7 +6,14 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif + +@available(*, deprecated, renamed: "PetstoreClient.FileSchemaTestClass") +public typealias FileSchemaTestClass = PetstoreClient.FileSchemaTestClass + +extension PetstoreClient { public final class FileSchemaTestClass: Codable, Hashable { @@ -17,6 +24,7 @@ public final class FileSchemaTestClass: Codable, Hashable { self.file = file self.files = files } + public enum CodingKeys: String, CodingKey, CaseIterable { case file case files @@ -30,8 +38,6 @@ public final class FileSchemaTestClass: Codable, Hashable { try container.encodeIfPresent(files, forKey: .files) } - - public static func == (lhs: FileSchemaTestClass, rhs: FileSchemaTestClass) -> Bool { lhs.file == rhs.file && lhs.files == rhs.files @@ -43,5 +49,6 @@ public final class FileSchemaTestClass: Codable, Hashable { hasher.combine(files?.hashValue) } +} } diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/FormatTest.swift b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/FormatTest.swift index 52c9d58241f..7ea8c7dc1ee 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/FormatTest.swift +++ b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/FormatTest.swift @@ -6,7 +6,14 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif + +@available(*, deprecated, renamed: "PetstoreClient.FormatTest") +public typealias FormatTest = PetstoreClient.FormatTest + +extension PetstoreClient { public final class FormatTest: Codable, Hashable { @@ -39,6 +46,7 @@ public final class FormatTest: Codable, Hashable { self.uuid = uuid self.password = password } + public enum CodingKeys: String, CodingKey, CaseIterable { case integer case int32 @@ -74,8 +82,6 @@ public final class FormatTest: Codable, Hashable { try container.encode(password, forKey: .password) } - - public static func == (lhs: FormatTest, rhs: FormatTest) -> Bool { lhs.integer == rhs.integer && lhs.int32 == rhs.int32 && @@ -109,5 +115,6 @@ public final class FormatTest: Codable, Hashable { hasher.combine(password.hashValue) } +} } diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/HasOnlyReadOnly.swift b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/HasOnlyReadOnly.swift index 4044065d4f8..75ce3afe50d 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/HasOnlyReadOnly.swift +++ b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/HasOnlyReadOnly.swift @@ -6,7 +6,14 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif + +@available(*, deprecated, renamed: "PetstoreClient.HasOnlyReadOnly") +public typealias HasOnlyReadOnly = PetstoreClient.HasOnlyReadOnly + +extension PetstoreClient { public final class HasOnlyReadOnly: Codable, Hashable { @@ -17,6 +24,7 @@ public final class HasOnlyReadOnly: Codable, Hashable { self.bar = bar self.foo = foo } + public enum CodingKeys: String, CodingKey, CaseIterable { case bar case foo @@ -30,8 +38,6 @@ public final class HasOnlyReadOnly: Codable, Hashable { try container.encodeIfPresent(foo, forKey: .foo) } - - public static func == (lhs: HasOnlyReadOnly, rhs: HasOnlyReadOnly) -> Bool { lhs.bar == rhs.bar && lhs.foo == rhs.foo @@ -43,5 +49,6 @@ public final class HasOnlyReadOnly: Codable, Hashable { hasher.combine(foo?.hashValue) } +} } diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/List.swift b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/List.swift index c2457325b5b..0dbb9c9f351 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/List.swift +++ b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/List.swift @@ -6,7 +6,14 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif + +@available(*, deprecated, renamed: "PetstoreClient.List") +public typealias List = PetstoreClient.List + +extension PetstoreClient { public final class List: Codable, Hashable { @@ -15,6 +22,7 @@ public final class List: Codable, Hashable { public init(_123list: String? = nil) { self._123list = _123list } + public enum CodingKeys: String, CodingKey, CaseIterable { case _123list = "123-list" } @@ -26,8 +34,6 @@ public final class List: Codable, Hashable { try container.encodeIfPresent(_123list, forKey: ._123list) } - - public static func == (lhs: List, rhs: List) -> Bool { lhs._123list == rhs._123list @@ -37,5 +43,6 @@ public final class List: Codable, Hashable { hasher.combine(_123list?.hashValue) } +} } diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/MapTest.swift b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/MapTest.swift index 83a6f77e76e..fa4d05b2b0d 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/MapTest.swift +++ b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/MapTest.swift @@ -6,7 +6,14 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif + +@available(*, deprecated, renamed: "PetstoreClient.MapTest") +public typealias MapTest = PetstoreClient.MapTest + +extension PetstoreClient { public final class MapTest: Codable, Hashable { @@ -25,6 +32,7 @@ public final class MapTest: Codable, Hashable { self.directMap = directMap self.indirectMap = indirectMap } + public enum CodingKeys: String, CodingKey, CaseIterable { case mapMapOfString = "map_map_of_string" case mapOfEnumString = "map_of_enum_string" @@ -42,8 +50,6 @@ public final class MapTest: Codable, Hashable { try container.encodeIfPresent(indirectMap, forKey: .indirectMap) } - - public static func == (lhs: MapTest, rhs: MapTest) -> Bool { lhs.mapMapOfString == rhs.mapMapOfString && lhs.mapOfEnumString == rhs.mapOfEnumString && @@ -59,5 +65,6 @@ public final class MapTest: Codable, Hashable { hasher.combine(indirectMap?.hashValue) } +} } diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/MixedPropertiesAndAdditionalPropertiesClass.swift b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/MixedPropertiesAndAdditionalPropertiesClass.swift index 08222b23f5c..af739161a45 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/MixedPropertiesAndAdditionalPropertiesClass.swift +++ b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/MixedPropertiesAndAdditionalPropertiesClass.swift @@ -6,7 +6,14 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif + +@available(*, deprecated, renamed: "PetstoreClient.MixedPropertiesAndAdditionalPropertiesClass") +public typealias MixedPropertiesAndAdditionalPropertiesClass = PetstoreClient.MixedPropertiesAndAdditionalPropertiesClass + +extension PetstoreClient { public final class MixedPropertiesAndAdditionalPropertiesClass: Codable, Hashable { @@ -19,6 +26,7 @@ public final class MixedPropertiesAndAdditionalPropertiesClass: Codable, Hashabl self.dateTime = dateTime self.map = map } + public enum CodingKeys: String, CodingKey, CaseIterable { case uuid case dateTime @@ -34,8 +42,6 @@ public final class MixedPropertiesAndAdditionalPropertiesClass: Codable, Hashabl try container.encodeIfPresent(map, forKey: .map) } - - public static func == (lhs: MixedPropertiesAndAdditionalPropertiesClass, rhs: MixedPropertiesAndAdditionalPropertiesClass) -> Bool { lhs.uuid == rhs.uuid && lhs.dateTime == rhs.dateTime && @@ -49,5 +55,6 @@ public final class MixedPropertiesAndAdditionalPropertiesClass: Codable, Hashabl hasher.combine(map?.hashValue) } +} } diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/Model200Response.swift b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/Model200Response.swift index 10290c43c3e..c029d5acbd8 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/Model200Response.swift +++ b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/Model200Response.swift @@ -6,7 +6,14 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif + +@available(*, deprecated, renamed: "PetstoreClient.Model200Response") +public typealias Model200Response = PetstoreClient.Model200Response + +extension PetstoreClient { /** Model for testing model name starting with number */ public final class Model200Response: Codable, Hashable { @@ -18,6 +25,7 @@ public final class Model200Response: Codable, Hashable { self.name = name self._class = _class } + public enum CodingKeys: String, CodingKey, CaseIterable { case name case _class = "class" @@ -31,8 +39,6 @@ public final class Model200Response: Codable, Hashable { try container.encodeIfPresent(_class, forKey: ._class) } - - public static func == (lhs: Model200Response, rhs: Model200Response) -> Bool { lhs.name == rhs.name && lhs._class == rhs._class @@ -44,5 +50,6 @@ public final class Model200Response: Codable, Hashable { hasher.combine(_class?.hashValue) } +} } diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/Name.swift b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/Name.swift index 533e5f2aea3..e37f05bbb5e 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/Name.swift +++ b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/Name.swift @@ -6,7 +6,14 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif + +@available(*, deprecated, renamed: "PetstoreClient.Name") +public typealias Name = PetstoreClient.Name + +extension PetstoreClient { /** Model for testing model name same as property name */ public final class Name: Codable, Hashable { @@ -22,6 +29,7 @@ public final class Name: Codable, Hashable { self.property = property self._123number = _123number } + public enum CodingKeys: String, CodingKey, CaseIterable { case name case snakeCase = "snake_case" @@ -39,8 +47,6 @@ public final class Name: Codable, Hashable { try container.encodeIfPresent(_123number, forKey: ._123number) } - - public static func == (lhs: Name, rhs: Name) -> Bool { lhs.name == rhs.name && lhs.snakeCase == rhs.snakeCase && @@ -56,5 +62,6 @@ public final class Name: Codable, Hashable { hasher.combine(_123number?.hashValue) } +} } diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/NumberOnly.swift b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/NumberOnly.swift index be9925066ce..b375325d252 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/NumberOnly.swift +++ b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/NumberOnly.swift @@ -6,7 +6,14 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif + +@available(*, deprecated, renamed: "PetstoreClient.NumberOnly") +public typealias NumberOnly = PetstoreClient.NumberOnly + +extension PetstoreClient { public final class NumberOnly: Codable, Hashable { @@ -15,6 +22,7 @@ public final class NumberOnly: Codable, Hashable { public init(justNumber: Double? = nil) { self.justNumber = justNumber } + public enum CodingKeys: String, CodingKey, CaseIterable { case justNumber = "JustNumber" } @@ -26,8 +34,6 @@ public final class NumberOnly: Codable, Hashable { try container.encodeIfPresent(justNumber, forKey: .justNumber) } - - public static func == (lhs: NumberOnly, rhs: NumberOnly) -> Bool { lhs.justNumber == rhs.justNumber @@ -37,5 +43,6 @@ public final class NumberOnly: Codable, Hashable { hasher.combine(justNumber?.hashValue) } +} } diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/Order.swift b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/Order.swift index cfce5645a20..9399d0b83f8 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/Order.swift +++ b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/Order.swift @@ -6,7 +6,14 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif + +@available(*, deprecated, renamed: "PetstoreClient.Order") +public typealias Order = PetstoreClient.Order + +extension PetstoreClient { public final class Order: Codable, Hashable { @@ -31,6 +38,7 @@ public final class Order: Codable, Hashable { self.status = status self.complete = complete } + public enum CodingKeys: String, CodingKey, CaseIterable { case id case petId @@ -52,8 +60,6 @@ public final class Order: Codable, Hashable { try container.encodeIfPresent(complete, forKey: .complete) } - - public static func == (lhs: Order, rhs: Order) -> Bool { lhs.id == rhs.id && lhs.petId == rhs.petId && @@ -73,5 +79,6 @@ public final class Order: Codable, Hashable { hasher.combine(complete?.hashValue) } +} } diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/OuterComposite.swift b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/OuterComposite.swift index d238c4c13dd..125a7f19c8e 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/OuterComposite.swift +++ b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/OuterComposite.swift @@ -6,7 +6,14 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif + +@available(*, deprecated, renamed: "PetstoreClient.OuterComposite") +public typealias OuterComposite = PetstoreClient.OuterComposite + +extension PetstoreClient { public final class OuterComposite: Codable, Hashable { @@ -19,6 +26,7 @@ public final class OuterComposite: Codable, Hashable { self.myString = myString self.myBoolean = myBoolean } + public enum CodingKeys: String, CodingKey, CaseIterable { case myNumber = "my_number" case myString = "my_string" @@ -34,8 +42,6 @@ public final class OuterComposite: Codable, Hashable { try container.encodeIfPresent(myBoolean, forKey: .myBoolean) } - - public static func == (lhs: OuterComposite, rhs: OuterComposite) -> Bool { lhs.myNumber == rhs.myNumber && lhs.myString == rhs.myString && @@ -49,5 +55,6 @@ public final class OuterComposite: Codable, Hashable { hasher.combine(myBoolean?.hashValue) } +} } diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/OuterEnum.swift b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/OuterEnum.swift index 9bd6f3bef8f..78ad5bedb38 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/OuterEnum.swift +++ b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/OuterEnum.swift @@ -6,10 +6,18 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif + +@available(*, deprecated, renamed: "PetstoreClient.OuterEnum") +public typealias OuterEnum = PetstoreClient.OuterEnum + +extension PetstoreClient { public enum OuterEnum: String, Codable, CaseIterable { case placed = "placed" case approved = "approved" case delivered = "delivered" } +} diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/Pet.swift b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/Pet.swift index c036d6d0cfb..7c3e1f6e58a 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/Pet.swift +++ b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/Pet.swift @@ -6,7 +6,14 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif + +@available(*, deprecated, renamed: "PetstoreClient.Pet") +public typealias Pet = PetstoreClient.Pet + +extension PetstoreClient { public final class Pet: Codable, Hashable { @@ -31,6 +38,7 @@ public final class Pet: Codable, Hashable { self.tags = tags self.status = status } + public enum CodingKeys: String, CodingKey, CaseIterable { case id case category @@ -52,8 +60,6 @@ public final class Pet: Codable, Hashable { try container.encodeIfPresent(status, forKey: .status) } - - public static func == (lhs: Pet, rhs: Pet) -> Bool { lhs.id == rhs.id && lhs.category == rhs.category && @@ -73,5 +79,6 @@ public final class Pet: Codable, Hashable { hasher.combine(status?.hashValue) } +} } diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/ReadOnlyFirst.swift b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/ReadOnlyFirst.swift index 1e2cdb966f2..d6ff6cf50f8 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/ReadOnlyFirst.swift +++ b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/ReadOnlyFirst.swift @@ -6,7 +6,14 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif + +@available(*, deprecated, renamed: "PetstoreClient.ReadOnlyFirst") +public typealias ReadOnlyFirst = PetstoreClient.ReadOnlyFirst + +extension PetstoreClient { public final class ReadOnlyFirst: Codable, Hashable { @@ -17,6 +24,7 @@ public final class ReadOnlyFirst: Codable, Hashable { self.bar = bar self.baz = baz } + public enum CodingKeys: String, CodingKey, CaseIterable { case bar case baz @@ -30,8 +38,6 @@ public final class ReadOnlyFirst: Codable, Hashable { try container.encodeIfPresent(baz, forKey: .baz) } - - public static func == (lhs: ReadOnlyFirst, rhs: ReadOnlyFirst) -> Bool { lhs.bar == rhs.bar && lhs.baz == rhs.baz @@ -43,5 +49,6 @@ public final class ReadOnlyFirst: Codable, Hashable { hasher.combine(baz?.hashValue) } +} } diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/Return.swift b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/Return.swift index c28939bb89d..c7a9c35ec1c 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/Return.swift +++ b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/Return.swift @@ -6,7 +6,14 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif + +@available(*, deprecated, renamed: "PetstoreClient.Return") +public typealias Return = PetstoreClient.Return + +extension PetstoreClient { /** Model for testing reserved words */ public final class Return: Codable, Hashable { @@ -16,6 +23,7 @@ public final class Return: Codable, Hashable { public init(_return: Int? = nil) { self._return = _return } + public enum CodingKeys: String, CodingKey, CaseIterable { case _return = "return" } @@ -27,8 +35,6 @@ public final class Return: Codable, Hashable { try container.encodeIfPresent(_return, forKey: ._return) } - - public static func == (lhs: Return, rhs: Return) -> Bool { lhs._return == rhs._return @@ -38,5 +44,6 @@ public final class Return: Codable, Hashable { hasher.combine(_return?.hashValue) } +} } diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/SpecialModelName.swift b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/SpecialModelName.swift index 3fd24733174..1f6a989b081 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/SpecialModelName.swift +++ b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/SpecialModelName.swift @@ -6,7 +6,14 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif + +@available(*, deprecated, renamed: "PetstoreClient.SpecialModelName") +public typealias SpecialModelName = PetstoreClient.SpecialModelName + +extension PetstoreClient { public final class SpecialModelName: Codable, Hashable { @@ -15,6 +22,7 @@ public final class SpecialModelName: Codable, Hashable { public init(specialPropertyName: Int64? = nil) { self.specialPropertyName = specialPropertyName } + public enum CodingKeys: String, CodingKey, CaseIterable { case specialPropertyName = "$special[property.name]" } @@ -26,8 +34,6 @@ public final class SpecialModelName: Codable, Hashable { try container.encodeIfPresent(specialPropertyName, forKey: .specialPropertyName) } - - public static func == (lhs: SpecialModelName, rhs: SpecialModelName) -> Bool { lhs.specialPropertyName == rhs.specialPropertyName @@ -37,5 +43,6 @@ public final class SpecialModelName: Codable, Hashable { hasher.combine(specialPropertyName?.hashValue) } +} } diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/StringBooleanMap.swift b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/StringBooleanMap.swift index 9e90edf7be9..67216302d21 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/StringBooleanMap.swift +++ b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/StringBooleanMap.swift @@ -6,12 +6,21 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif + +@available(*, deprecated, renamed: "PetstoreClient.StringBooleanMap") +public typealias StringBooleanMap = PetstoreClient.StringBooleanMap + +extension PetstoreClient { public final class StringBooleanMap: Codable, Hashable { + public enum CodingKeys: CodingKey, CaseIterable { } + public var additionalProperties: [String: Bool] = [:] public subscript(key: String) -> Bool? { @@ -38,13 +47,13 @@ public final class StringBooleanMap: Codable, Hashable { // Decodable protocol methods public init(from decoder: Decoder) throws { - let container = try decoder.container(keyedBy: String.self) + let container = try decoder.container(keyedBy: CodingKeys.self) var nonAdditionalPropertyKeys = Set() - additionalProperties = try container.decodeMap(Bool.self, excludedKeys: nonAdditionalPropertyKeys) + let additionalPropertiesContainer = try decoder.container(keyedBy: String.self) + additionalProperties = try additionalPropertiesContainer.decodeMap(Bool.self, excludedKeys: nonAdditionalPropertyKeys) } - public static func == (lhs: StringBooleanMap, rhs: StringBooleanMap) -> Bool { lhs.additionalProperties == rhs.additionalProperties } @@ -52,5 +61,6 @@ public final class StringBooleanMap: Codable, Hashable { public func hash(into hasher: inout Hasher) { hasher.combine(additionalProperties.hashValue) } +} } diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/Tag.swift b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/Tag.swift index b30b0f62ace..365ccb8b3aa 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/Tag.swift +++ b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/Tag.swift @@ -6,7 +6,14 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif + +@available(*, deprecated, renamed: "PetstoreClient.Tag") +public typealias Tag = PetstoreClient.Tag + +extension PetstoreClient { public final class Tag: Codable, Hashable { @@ -17,6 +24,7 @@ public final class Tag: Codable, Hashable { self.id = id self.name = name } + public enum CodingKeys: String, CodingKey, CaseIterable { case id case name @@ -30,8 +38,6 @@ public final class Tag: Codable, Hashable { try container.encodeIfPresent(name, forKey: .name) } - - public static func == (lhs: Tag, rhs: Tag) -> Bool { lhs.id == rhs.id && lhs.name == rhs.name @@ -43,5 +49,6 @@ public final class Tag: Codable, Hashable { hasher.combine(name?.hashValue) } +} } diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/TypeHolderDefault.swift b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/TypeHolderDefault.swift index f99b86d1d64..3f64638c1bc 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/TypeHolderDefault.swift +++ b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/TypeHolderDefault.swift @@ -6,7 +6,14 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif + +@available(*, deprecated, renamed: "PetstoreClient.TypeHolderDefault") +public typealias TypeHolderDefault = PetstoreClient.TypeHolderDefault + +extension PetstoreClient { public final class TypeHolderDefault: Codable, Hashable { @@ -23,6 +30,7 @@ public final class TypeHolderDefault: Codable, Hashable { self.boolItem = boolItem self.arrayItem = arrayItem } + public enum CodingKeys: String, CodingKey, CaseIterable { case stringItem = "string_item" case numberItem = "number_item" @@ -42,8 +50,6 @@ public final class TypeHolderDefault: Codable, Hashable { try container.encode(arrayItem, forKey: .arrayItem) } - - public static func == (lhs: TypeHolderDefault, rhs: TypeHolderDefault) -> Bool { lhs.stringItem == rhs.stringItem && lhs.numberItem == rhs.numberItem && @@ -61,5 +67,6 @@ public final class TypeHolderDefault: Codable, Hashable { hasher.combine(arrayItem.hashValue) } +} } diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/TypeHolderExample.swift b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/TypeHolderExample.swift index d266ad2f0d1..c7b480af0d0 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/TypeHolderExample.swift +++ b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/TypeHolderExample.swift @@ -6,7 +6,14 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif + +@available(*, deprecated, renamed: "PetstoreClient.TypeHolderExample") +public typealias TypeHolderExample = PetstoreClient.TypeHolderExample + +extension PetstoreClient { public final class TypeHolderExample: Codable, Hashable { @@ -23,6 +30,7 @@ public final class TypeHolderExample: Codable, Hashable { self.boolItem = boolItem self.arrayItem = arrayItem } + public enum CodingKeys: String, CodingKey, CaseIterable { case stringItem = "string_item" case numberItem = "number_item" @@ -42,8 +50,6 @@ public final class TypeHolderExample: Codable, Hashable { try container.encode(arrayItem, forKey: .arrayItem) } - - public static func == (lhs: TypeHolderExample, rhs: TypeHolderExample) -> Bool { lhs.stringItem == rhs.stringItem && lhs.numberItem == rhs.numberItem && @@ -61,5 +67,6 @@ public final class TypeHolderExample: Codable, Hashable { hasher.combine(arrayItem.hashValue) } +} } diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/User.swift b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/User.swift index dcbecdf498d..3af56094d8c 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/User.swift +++ b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models/User.swift @@ -6,7 +6,14 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif + +@available(*, deprecated, renamed: "PetstoreClient.User") +public typealias User = PetstoreClient.User + +extension PetstoreClient { public final class User: Codable, Hashable { @@ -30,6 +37,7 @@ public final class User: Codable, Hashable { self.phone = phone self.userStatus = userStatus } + public enum CodingKeys: String, CodingKey, CaseIterable { case id case username @@ -55,8 +63,6 @@ public final class User: Codable, Hashable { try container.encodeIfPresent(userStatus, forKey: .userStatus) } - - public static func == (lhs: User, rhs: User) -> Bool { lhs.id == rhs.id && lhs.username == rhs.username && @@ -80,5 +86,6 @@ public final class User: Codable, Hashable { hasher.combine(userStatus?.hashValue) } +} } diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/URLSessionImplementations.swift b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/URLSessionImplementations.swift index 52b2071ec1a..41959190a26 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/URLSessionImplementations.swift +++ b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/URLSessionImplementations.swift @@ -93,14 +93,14 @@ open class URLSessionRequestBuilder: RequestBuilder { return modifiedRequest } - override open func execute(_ apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, _ completion: @escaping (_ result: Swift.Result, Error>) -> Void) { + override open func execute(_ apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, _ completion: @escaping (_ result: Swift.Result, Error>) -> Void) { let urlSessionId = UUID().uuidString // Create a new manager for each request to customize its request header let urlSession = createURLSession() urlSessionStore[urlSessionId] = urlSession guard let xMethod = HTTPMethod(rawValue: method) else { - fatalError("Unsuported Http method - \(method)") + fatalError("Unsupported Http method - \(method)") } let encoding: ParameterEncoding @@ -119,7 +119,7 @@ open class URLSessionRequestBuilder: RequestBuilder { } else if contentType == "application/x-www-form-urlencoded" { encoding = FormURLEncoding() } else { - fatalError("Unsuported Media Type - \(contentType)") + fatalError("Unsupported Media Type - \(contentType)") } } @@ -205,16 +205,18 @@ open class URLSessionRequestBuilder: RequestBuilder { } let fileManager = FileManager.default - let documentsDirectory = fileManager.urls(for: .documentDirectory, in: .userDomainMask)[0] + let cachesDirectory = fileManager.urls(for: .cachesDirectory, in: .userDomainMask)[0] let requestURL = try getURL(from: urlRequest) var requestPath = try getPath(from: requestURL) if let headerFileName = getFileName(fromContentDisposition: httpResponse.allHeaderFields["Content-Disposition"] as? String) { requestPath = requestPath.appending("/\(headerFileName)") + } else { + requestPath = requestPath.appending("/tmp.PetstoreClient.\(UUID().uuidString)") } - let filePath = documentsDirectory.appendingPathComponent(requestPath) + let filePath = cachesDirectory.appendingPathComponent(requestPath) let directoryPath = filePath.deletingLastPathComponent().path try fileManager.createDirectory(atPath: directoryPath, withIntermediateDirectories: true, attributes: nil) @@ -232,6 +234,10 @@ open class URLSessionRequestBuilder: RequestBuilder { completion(.success(Response(response: httpResponse, body: nil))) + case is Data.Type: + + completion(.success(Response(response: httpResponse, body: data as? T))) + default: completion(.success(Response(response: httpResponse, body: data as? T))) @@ -244,7 +250,7 @@ open class URLSessionRequestBuilder: RequestBuilder { for (key, value) in headers { httpHeaders[key] = value } - for (key, value) in PetstoreClientAPI.customHeaders { + for (key, value) in PetstoreClient.customHeaders { httpHeaders[key] = value } return httpHeaders @@ -328,6 +334,43 @@ open class URLSessionDecodableRequestBuilder: URLSessionRequestBui completion(.success(Response(response: httpResponse, body: body as? T))) + case is URL.Type: + do { + + guard error == nil else { + throw DownloadException.responseFailed + } + + guard let data = data else { + throw DownloadException.responseDataMissing + } + + let fileManager = FileManager.default + let cachesDirectory = fileManager.urls(for: .cachesDirectory, in: .userDomainMask)[0] + let requestURL = try getURL(from: urlRequest) + + var requestPath = try getPath(from: requestURL) + + if let headerFileName = getFileName(fromContentDisposition: httpResponse.allHeaderFields["Content-Disposition"] as? String) { + requestPath = requestPath.appending("/\(headerFileName)") + } else { + requestPath = requestPath.appending("/tmp.PetstoreClient.\(UUID().uuidString)") + } + + let filePath = cachesDirectory.appendingPathComponent(requestPath) + let directoryPath = filePath.deletingLastPathComponent().path + + try fileManager.createDirectory(atPath: directoryPath, withIntermediateDirectories: true, attributes: nil) + try data.write(to: filePath, options: .atomic) + + completion(.success(Response(response: httpResponse, body: filePath as? T))) + + } catch let requestParserError as DownloadException { + completion(.failure(ErrorResponse.error(400, data, response, requestParserError))) + } catch { + completion(.failure(ErrorResponse.error(400, data, response, error))) + } + case is Void.Type: completion(.success(Response(response: httpResponse, body: nil))) diff --git a/samples/client/petstore/swift5/urlsessionLibrary/SwaggerClientTests/.gitignore b/samples/client/petstore/swift5/urlsessionLibrary/SwaggerClientTests/.gitignore index 0269c2f56db..22029d2f644 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/SwaggerClientTests/.gitignore +++ b/samples/client/petstore/swift5/urlsessionLibrary/SwaggerClientTests/.gitignore @@ -1,14 +1,22 @@ -### https://raw.github.com/github/gitignore/7792e50daeaa6c07460484704671d1dc9f0045a7/Swift.gitignore +# Created by https://www.toptal.com/developers/gitignore/api/swift,xcode +# Edit at https://www.toptal.com/developers/gitignore?templates=swift,xcode +### Swift ### # Xcode # # gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore -## Build generated +## User settings +xcuserdata/ + +## compatibility with Xcode 8 and earlier (ignoring not required starting Xcode 9) +*.xcscmblueprint +*.xccheckout + +## compatibility with Xcode 3 and earlier (ignoring not required starting Xcode 4) build/ DerivedData/ - -## Various settings +*.moved-aside *.pbxuser !default.pbxuser *.mode1v3 @@ -17,15 +25,11 @@ DerivedData/ !default.mode2v3 *.perspectivev3 !default.perspectivev3 -xcuserdata/ - -## Other -*.moved-aside -*.xccheckout -*.xcscmblueprint ## Obj-C/Swift specific *.hmap + +## App packaging *.ipa *.dSYM.zip *.dSYM @@ -35,38 +39,67 @@ timeline.xctimeline playground.xcworkspace # Swift Package Manager -# # Add this line if you want to avoid checking in source code from Swift Package Manager dependencies. # Packages/ # Package.pins # Package.resolved +# *.xcodeproj +# Xcode automatically generates this directory with a .xcworkspacedata file and xcuserdata +# hence it is not needed unless you have added a package configuration file to your project +# .swiftpm + .build/ # CocoaPods -# # We recommend against adding the Pods directory to your .gitignore. However # you should judge for yourself, the pros and cons are mentioned at: # https://guides.cocoapods.org/using/using-cocoapods.html#should-i-check-the-pods-directory-into-source-control -# -Pods/ +# Pods/ +# Add this line if you want to avoid checking in source code from the Xcode workspace +# *.xcworkspace # Carthage -# # Add this line if you want to avoid checking in source code from Carthage dependencies. -Carthage/Checkouts +# Carthage/Checkouts -Carthage/Build +Carthage/Build/ + +# Add this lines if you are using Accio dependency management (Deprecated since Xcode 12) +# Dependencies/ +# .accio/ # fastlane -# -# It is recommended to not store the screenshots in the git repo. Instead, use fastlane to re-generate the -# screenshots whenever they are needed. +# It is recommended to not store the screenshots in the git repo. +# Instead, use fastlane to re-generate the screenshots whenever they are needed. # For more information about the recommended setup visit: # https://docs.fastlane.tools/best-practices/source-control/#source-control fastlane/report.xml fastlane/Preview.html -fastlane/screenshots +fastlane/screenshots/**/*.png fastlane/test_output +# Code Injection +# After new code Injection tools there's a generated folder /iOSInjectionProject +# https://github.com/johnno1962/injectionforxcode +iOSInjectionProject/ + +### Xcode ### +# Xcode +# gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore + + + + +## Gcc Patch +/*.gcno + +### Xcode Patch ### +*.xcodeproj/* +!*.xcodeproj/project.pbxproj +!*.xcodeproj/xcshareddata/ +!*.xcworkspace/contents.xcworkspacedata +**/xcshareddata/WorkspaceSettings.xcsettings + +# End of https://www.toptal.com/developers/gitignore/api/swift,xcode \ No newline at end of file diff --git a/samples/client/petstore/swift5/urlsessionLibrary/SwaggerClientTests/Podfile b/samples/client/petstore/swift5/urlsessionLibrary/SwaggerClientTests/Podfile deleted file mode 100644 index 77432f9eee9..00000000000 --- a/samples/client/petstore/swift5/urlsessionLibrary/SwaggerClientTests/Podfile +++ /dev/null @@ -1,13 +0,0 @@ -platform :ios, '9.0' - -source 'https://cdn.cocoapods.org/' - -use_frameworks! - -target 'SwaggerClient' do - pod "PetstoreClient", :path => "../" - - target 'SwaggerClientTests' do - inherit! :search_paths - end -end diff --git a/samples/client/petstore/swift5/urlsessionLibrary/SwaggerClientTests/Podfile.lock b/samples/client/petstore/swift5/urlsessionLibrary/SwaggerClientTests/Podfile.lock deleted file mode 100644 index a621fdeec88..00000000000 --- a/samples/client/petstore/swift5/urlsessionLibrary/SwaggerClientTests/Podfile.lock +++ /dev/null @@ -1,16 +0,0 @@ -PODS: - - PetstoreClient (1.0.0) - -DEPENDENCIES: - - PetstoreClient (from `../`) - -EXTERNAL SOURCES: - PetstoreClient: - :path: "../" - -SPEC CHECKSUMS: - PetstoreClient: b26b235a3ece06dbf1da99dc67e48aa201659f21 - -PODFILE CHECKSUM: 509bec696cc1d8641751b52e4fe4bef04ac4542c - -COCOAPODS: 1.9.0 diff --git a/samples/client/petstore/swift5/urlsessionLibrary/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj b/samples/client/petstore/swift5/urlsessionLibrary/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj index 9c371f929db..aab810debd0 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj +++ b/samples/client/petstore/swift5/urlsessionLibrary/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj @@ -3,12 +3,11 @@ archiveVersion = 1; classes = { }; - objectVersion = 46; + objectVersion = 52; objects = { /* Begin PBXBuildFile section */ 1A501F48219C3DC600F372F6 /* DateFormatTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1A501F47219C3DC600F372F6 /* DateFormatTests.swift */; }; - 23B2E76564651097BE2FE501 /* Pods_SwaggerClient.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 7F98CC8B18E5FA9213F6A68D /* Pods_SwaggerClient.framework */; }; 6D4EFB951C692C6300B96B06 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6D4EFB941C692C6300B96B06 /* AppDelegate.swift */; }; 6D4EFB971C692C6300B96B06 /* ViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6D4EFB961C692C6300B96B06 /* ViewController.swift */; }; 6D4EFB9A1C692C6300B96B06 /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 6D4EFB981C692C6300B96B06 /* Main.storyboard */; }; @@ -18,9 +17,9 @@ 6D4EFBB71C693BED00B96B06 /* StoreAPITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6D4EFBB61C693BED00B96B06 /* StoreAPITests.swift */; }; 6D4EFBB91C693BFC00B96B06 /* UserAPITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6D4EFBB81C693BFC00B96B06 /* UserAPITests.swift */; }; A5465867259E09C600C3929B /* BearerDecodableRequestBuilder.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5465866259E09C600C3929B /* BearerDecodableRequestBuilder.swift */; }; + A5782C772664FBA800CAA106 /* PetstoreClient in Frameworks */ = {isa = PBXBuildFile; productRef = A5782C762664FBA800CAA106 /* PetstoreClient */; }; A5EA12642419439700E30FC3 /* FileUtils.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5EA12622419439700E30FC3 /* FileUtils.swift */; }; A5EA12652419439700E30FC3 /* UIImage+Extras.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5EA12632419439700E30FC3 /* UIImage+Extras.swift */; }; - FB5CCC7EFA680BB2746B695B /* Pods_SwaggerClientTests.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 83FDC034BBA2A07AE9975250 /* Pods_SwaggerClientTests.framework */; }; /* End PBXBuildFile section */ /* Begin PBXContainerItemProxy section */ @@ -34,7 +33,6 @@ /* End PBXContainerItemProxy section */ /* Begin PBXFileReference section */ - 081E9B893DEB1589CB807EA7 /* Pods-SwaggerClient.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-SwaggerClient.debug.xcconfig"; path = "Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient.debug.xcconfig"; sourceTree = ""; }; 1A501F47219C3DC600F372F6 /* DateFormatTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DateFormatTests.swift; sourceTree = ""; }; 6D4EFB911C692C6300B96B06 /* SwaggerClient.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = SwaggerClient.app; sourceTree = BUILT_PRODUCTS_DIR; }; 6D4EFB941C692C6300B96B06 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; @@ -48,15 +46,9 @@ 6D4EFBB41C693BE200B96B06 /* PetAPITests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PetAPITests.swift; sourceTree = ""; }; 6D4EFBB61C693BED00B96B06 /* StoreAPITests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StoreAPITests.swift; sourceTree = ""; }; 6D4EFBB81C693BFC00B96B06 /* UserAPITests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = UserAPITests.swift; sourceTree = ""; }; - 7F98CC8B18E5FA9213F6A68D /* Pods_SwaggerClient.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_SwaggerClient.framework; sourceTree = BUILT_PRODUCTS_DIR; }; - 83FDC034BBA2A07AE9975250 /* Pods_SwaggerClientTests.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_SwaggerClientTests.framework; sourceTree = BUILT_PRODUCTS_DIR; }; A5465866259E09C600C3929B /* BearerDecodableRequestBuilder.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BearerDecodableRequestBuilder.swift; sourceTree = ""; }; A5EA12622419439700E30FC3 /* FileUtils.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FileUtils.swift; sourceTree = ""; }; A5EA12632419439700E30FC3 /* UIImage+Extras.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "UIImage+Extras.swift"; sourceTree = ""; }; - ACB80AC61FA8D8916D4559AA /* Pods-SwaggerClient.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-SwaggerClient.release.xcconfig"; path = "Pods/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient.release.xcconfig"; sourceTree = ""; }; - C07EC0A94AA0F86D60668B32 /* Pods.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods.framework; sourceTree = BUILT_PRODUCTS_DIR; }; - E43FC34A9681D65ED44EE914 /* Pods-SwaggerClientTests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-SwaggerClientTests.debug.xcconfig"; path = "Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests.debug.xcconfig"; sourceTree = ""; }; - ED8576754DBB828CAE63EA87 /* Pods-SwaggerClientTests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-SwaggerClientTests.release.xcconfig"; path = "Pods/Target Support Files/Pods-SwaggerClientTests/Pods-SwaggerClientTests.release.xcconfig"; sourceTree = ""; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ @@ -64,7 +56,7 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( - 23B2E76564651097BE2FE501 /* Pods_SwaggerClient.framework in Frameworks */, + A5782C772664FBA800CAA106 /* PetstoreClient in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -72,30 +64,15 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( - FB5CCC7EFA680BB2746B695B /* Pods_SwaggerClientTests.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */ - 203D4495376E4EB72474B091 /* Pods */ = { - isa = PBXGroup; - children = ( - 081E9B893DEB1589CB807EA7 /* Pods-SwaggerClient.debug.xcconfig */, - ACB80AC61FA8D8916D4559AA /* Pods-SwaggerClient.release.xcconfig */, - E43FC34A9681D65ED44EE914 /* Pods-SwaggerClientTests.debug.xcconfig */, - ED8576754DBB828CAE63EA87 /* Pods-SwaggerClientTests.release.xcconfig */, - ); - name = Pods; - sourceTree = ""; - }; 3FABC56EC0BA84CBF4F99564 /* Frameworks */ = { isa = PBXGroup; children = ( - C07EC0A94AA0F86D60668B32 /* Pods.framework */, - 7F98CC8B18E5FA9213F6A68D /* Pods_SwaggerClient.framework */, - 83FDC034BBA2A07AE9975250 /* Pods_SwaggerClientTests.framework */, ); name = Frameworks; sourceTree = ""; @@ -107,7 +84,6 @@ 6D4EFBA81C692C6300B96B06 /* SwaggerClientTests */, 6D4EFB921C692C6300B96B06 /* Products */, 3FABC56EC0BA84CBF4F99564 /* Frameworks */, - 203D4495376E4EB72474B091 /* Pods */, ); sourceTree = ""; }; @@ -155,17 +131,18 @@ isa = PBXNativeTarget; buildConfigurationList = 6D4EFBAE1C692C6300B96B06 /* Build configuration list for PBXNativeTarget "SwaggerClient" */; buildPhases = ( - 5BC9214E8D9BA5A427A3775B /* [CP] Check Pods Manifest.lock */, 6D4EFB8D1C692C6300B96B06 /* Sources */, 6D4EFB8E1C692C6300B96B06 /* Frameworks */, 6D4EFB8F1C692C6300B96B06 /* Resources */, - FDCA0F14611FE114BFEBA8BB /* [CP] Embed Pods Frameworks */, ); buildRules = ( ); dependencies = ( ); name = SwaggerClient; + packageProductDependencies = ( + A5782C762664FBA800CAA106 /* PetstoreClient */, + ); productName = SwaggerClient; productReference = 6D4EFB911C692C6300B96B06 /* SwaggerClient.app */; productType = "com.apple.product-type.application"; @@ -174,7 +151,6 @@ isa = PBXNativeTarget; buildConfigurationList = 6D4EFBB11C692C6300B96B06 /* Build configuration list for PBXNativeTarget "SwaggerClientTests" */; buildPhases = ( - EEDC5E683F9569976B7C1192 /* [CP] Check Pods Manifest.lock */, 6D4EFBA11C692C6300B96B06 /* Sources */, 6D4EFBA21C692C6300B96B06 /* Frameworks */, 6D4EFBA31C692C6300B96B06 /* Resources */, @@ -249,71 +225,6 @@ }; /* End PBXResourcesBuildPhase section */ -/* Begin PBXShellScriptBuildPhase section */ - 5BC9214E8D9BA5A427A3775B /* [CP] Check Pods Manifest.lock */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputFileListPaths = ( - ); - inputPaths = ( - "${PODS_PODFILE_DIR_PATH}/Podfile.lock", - "${PODS_ROOT}/Manifest.lock", - ); - name = "[CP] Check Pods Manifest.lock"; - outputFileListPaths = ( - ); - outputPaths = ( - "$(DERIVED_FILE_DIR)/Pods-SwaggerClient-checkManifestLockResult.txt", - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; - showEnvVarsInLog = 0; - }; - EEDC5E683F9569976B7C1192 /* [CP] Check Pods Manifest.lock */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputFileListPaths = ( - ); - inputPaths = ( - "${PODS_PODFILE_DIR_PATH}/Podfile.lock", - "${PODS_ROOT}/Manifest.lock", - ); - name = "[CP] Check Pods Manifest.lock"; - outputFileListPaths = ( - ); - outputPaths = ( - "$(DERIVED_FILE_DIR)/Pods-SwaggerClientTests-checkManifestLockResult.txt", - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; - showEnvVarsInLog = 0; - }; - FDCA0F14611FE114BFEBA8BB /* [CP] Embed Pods Frameworks */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputPaths = ( - "${PODS_ROOT}/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-frameworks.sh", - "${BUILT_PRODUCTS_DIR}/PetstoreClient/PetstoreClient.framework", - ); - name = "[CP] Embed Pods Frameworks"; - outputPaths = ( - "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/PetstoreClient.framework", - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-SwaggerClient/Pods-SwaggerClient-frameworks.sh\"\n"; - showEnvVarsInLog = 0; - }; -/* End PBXShellScriptBuildPhase section */ - /* Begin PBXSourcesBuildPhase section */ 6D4EFB8D1C692C6300B96B06 /* Sources */ = { isa = PBXSourcesBuildPhase; @@ -478,11 +389,13 @@ }; 6D4EFBAF1C692C6300B96B06 /* Debug */ = { isa = XCBuildConfiguration; - baseConfigurationReference = 081E9B893DEB1589CB807EA7 /* Pods-SwaggerClient.debug.xcconfig */; buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; INFOPLIST_FILE = SwaggerClient/Info.plist; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); PRODUCT_BUNDLE_IDENTIFIER = com.swagger.SwaggerClient; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_VERSION = 5.0; @@ -491,11 +404,13 @@ }; 6D4EFBB01C692C6300B96B06 /* Release */ = { isa = XCBuildConfiguration; - baseConfigurationReference = ACB80AC61FA8D8916D4559AA /* Pods-SwaggerClient.release.xcconfig */; buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; INFOPLIST_FILE = SwaggerClient/Info.plist; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); PRODUCT_BUNDLE_IDENTIFIER = com.swagger.SwaggerClient; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_VERSION = 5.0; @@ -504,11 +419,14 @@ }; 6D4EFBB21C692C6300B96B06 /* Debug */ = { isa = XCBuildConfiguration; - baseConfigurationReference = E43FC34A9681D65ED44EE914 /* Pods-SwaggerClientTests.debug.xcconfig */; buildSettings = { BUNDLE_LOADER = "$(TEST_HOST)"; INFOPLIST_FILE = SwaggerClientTests/Info.plist; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); PRODUCT_BUNDLE_IDENTIFIER = com.swagger.SwaggerClientTests; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_VERSION = 5.0; @@ -518,11 +436,14 @@ }; 6D4EFBB31C692C6300B96B06 /* Release */ = { isa = XCBuildConfiguration; - baseConfigurationReference = ED8576754DBB828CAE63EA87 /* Pods-SwaggerClientTests.release.xcconfig */; buildSettings = { BUNDLE_LOADER = "$(TEST_HOST)"; INFOPLIST_FILE = SwaggerClientTests/Info.plist; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); PRODUCT_BUNDLE_IDENTIFIER = com.swagger.SwaggerClientTests; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_VERSION = 5.0; @@ -561,6 +482,13 @@ defaultConfigurationName = Release; }; /* End XCConfigurationList section */ + +/* Begin XCSwiftPackageProductDependency section */ + A5782C762664FBA800CAA106 /* PetstoreClient */ = { + isa = XCSwiftPackageProductDependency; + productName = PetstoreClient; + }; +/* End XCSwiftPackageProductDependency section */ }; rootObject = 6D4EFB891C692C6300B96B06 /* Project object */; } diff --git a/samples/client/petstore/swift5/urlsessionLibrary/SwaggerClientTests/SwaggerClient.xcworkspace/contents.xcworkspacedata b/samples/client/petstore/swift5/urlsessionLibrary/SwaggerClientTests/SwaggerClient.xcworkspace/contents.xcworkspacedata index 9b3fa18954f..00ec9b53a7f 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/SwaggerClientTests/SwaggerClient.xcworkspace/contents.xcworkspacedata +++ b/samples/client/petstore/swift5/urlsessionLibrary/SwaggerClientTests/SwaggerClient.xcworkspace/contents.xcworkspacedata @@ -2,9 +2,9 @@ + location = "group:.."> + location = "group:SwaggerClient.xcodeproj"> diff --git a/samples/client/petstore/swift5/urlsessionLibrary/SwaggerClientTests/SwaggerClient.xcworkspace/xcshareddata/swiftpm/Package.resolved b/samples/client/petstore/swift5/urlsessionLibrary/SwaggerClientTests/SwaggerClient.xcworkspace/xcshareddata/swiftpm/Package.resolved new file mode 100644 index 00000000000..d384b276b4b --- /dev/null +++ b/samples/client/petstore/swift5/urlsessionLibrary/SwaggerClientTests/SwaggerClient.xcworkspace/xcshareddata/swiftpm/Package.resolved @@ -0,0 +1,16 @@ +{ + "object": { + "pins": [ + { + "package": "AnyCodable", + "repositoryURL": "https://github.com/Flight-School/AnyCodable", + "state": { + "branch": null, + "revision": "876d162385e9862ae8b3c8d65dc301312b040005", + "version": "0.6.0" + } + } + ] + }, + "version": 1 +} diff --git a/samples/client/petstore/swift5/urlsessionLibrary/docs/FakeAPI.md b/samples/client/petstore/swift5/urlsessionLibrary/docs/FakeAPI.md index 543869c0d2e..553a46281aa 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/docs/FakeAPI.md +++ b/samples/client/petstore/swift5/urlsessionLibrary/docs/FakeAPI.md @@ -379,7 +379,7 @@ import PetstoreClient let number = 987 // Double | None let double = 987 // Double | None let patternWithoutDelimiter = "patternWithoutDelimiter_example" // String | None -let byte = 987 // Data | None +let byte = Data([9, 8, 7]) // Data | None let integer = 987 // Int | None (optional) let int32 = 987 // Int | None (optional) let int64 = 987 // Int64 | None (optional) diff --git a/samples/client/petstore/swift5/urlsessionLibrary/project.yml b/samples/client/petstore/swift5/urlsessionLibrary/project.yml index 8280cd17d31..af642519aeb 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/project.yml +++ b/samples/client/petstore/swift5/urlsessionLibrary/project.yml @@ -11,5 +11,5 @@ targets: settings: APPLICATION_EXTENSION_API_ONLY: true scheme: {} - + dependencies: - carthage: AnyCodable diff --git a/samples/client/petstore/swift5/vaporLibrary/.gitignore b/samples/client/petstore/swift5/vaporLibrary/.gitignore new file mode 100644 index 00000000000..627d360a903 --- /dev/null +++ b/samples/client/petstore/swift5/vaporLibrary/.gitignore @@ -0,0 +1,105 @@ +# Created by https://www.toptal.com/developers/gitignore/api/swift,xcode +# Edit at https://www.toptal.com/developers/gitignore?templates=swift,xcode + +### Swift ### +# Xcode +# +# gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore + +## User settings +xcuserdata/ + +## compatibility with Xcode 8 and earlier (ignoring not required starting Xcode 9) +*.xcscmblueprint +*.xccheckout + +## compatibility with Xcode 3 and earlier (ignoring not required starting Xcode 4) +build/ +DerivedData/ +*.moved-aside +*.pbxuser +!default.pbxuser +*.mode1v3 +!default.mode1v3 +*.mode2v3 +!default.mode2v3 +*.perspectivev3 +!default.perspectivev3 + +## Obj-C/Swift specific +*.hmap + +## App packaging +*.ipa +*.dSYM.zip +*.dSYM + +## Playgrounds +timeline.xctimeline +playground.xcworkspace + +# Swift Package Manager +# Add this line if you want to avoid checking in source code from Swift Package Manager dependencies. +# Packages/ +# Package.pins +# Package.resolved +# *.xcodeproj +# Xcode automatically generates this directory with a .xcworkspacedata file and xcuserdata +# hence it is not needed unless you have added a package configuration file to your project +# .swiftpm + +.build/ + +# CocoaPods +# We recommend against adding the Pods directory to your .gitignore. However +# you should judge for yourself, the pros and cons are mentioned at: +# https://guides.cocoapods.org/using/using-cocoapods.html#should-i-check-the-pods-directory-into-source-control +# Pods/ +# Add this line if you want to avoid checking in source code from the Xcode workspace +# *.xcworkspace + +# Carthage +# Add this line if you want to avoid checking in source code from Carthage dependencies. +# Carthage/Checkouts + +Carthage/Build/ + +# Add this lines if you are using Accio dependency management (Deprecated since Xcode 12) +# Dependencies/ +# .accio/ + +# fastlane +# It is recommended to not store the screenshots in the git repo. +# Instead, use fastlane to re-generate the screenshots whenever they are needed. +# For more information about the recommended setup visit: +# https://docs.fastlane.tools/best-practices/source-control/#source-control + +fastlane/report.xml +fastlane/Preview.html +fastlane/screenshots/**/*.png +fastlane/test_output + +# Code Injection +# After new code Injection tools there's a generated folder /iOSInjectionProject +# https://github.com/johnno1962/injectionforxcode + +iOSInjectionProject/ + +### Xcode ### +# Xcode +# gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore + + + + +## Gcc Patch +/*.gcno + +### Xcode Patch ### +*.xcodeproj/* +!*.xcodeproj/project.pbxproj +!*.xcodeproj/xcshareddata/ +!*.xcworkspace/contents.xcworkspacedata +**/xcshareddata/WorkspaceSettings.xcsettings + +# End of https://www.toptal.com/developers/gitignore/api/swift,xcode diff --git a/samples/client/petstore/swift5/vaporLibrary/.openapi-generator-ignore b/samples/client/petstore/swift5/vaporLibrary/.openapi-generator-ignore new file mode 100644 index 00000000000..7484ee590a3 --- /dev/null +++ b/samples/client/petstore/swift5/vaporLibrary/.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/swift5/vaporLibrary/.openapi-generator/FILES b/samples/client/petstore/swift5/vaporLibrary/.openapi-generator/FILES new file mode 100644 index 00000000000..ec27ad4b38e --- /dev/null +++ b/samples/client/petstore/swift5/vaporLibrary/.openapi-generator/FILES @@ -0,0 +1,118 @@ +.gitignore +Package.swift +README.md +Sources/PetstoreClient/APIs.swift +Sources/PetstoreClient/APIs/AnotherFakeAPI.swift +Sources/PetstoreClient/APIs/FakeAPI.swift +Sources/PetstoreClient/APIs/FakeClassnameTags123API.swift +Sources/PetstoreClient/APIs/PetAPI.swift +Sources/PetstoreClient/APIs/StoreAPI.swift +Sources/PetstoreClient/APIs/UserAPI.swift +Sources/PetstoreClient/Configuration.swift +Sources/PetstoreClient/Extensions.swift +Sources/PetstoreClient/Models/AdditionalPropertiesAnyType.swift +Sources/PetstoreClient/Models/AdditionalPropertiesArray.swift +Sources/PetstoreClient/Models/AdditionalPropertiesBoolean.swift +Sources/PetstoreClient/Models/AdditionalPropertiesClass.swift +Sources/PetstoreClient/Models/AdditionalPropertiesInteger.swift +Sources/PetstoreClient/Models/AdditionalPropertiesNumber.swift +Sources/PetstoreClient/Models/AdditionalPropertiesObject.swift +Sources/PetstoreClient/Models/AdditionalPropertiesString.swift +Sources/PetstoreClient/Models/Animal.swift +Sources/PetstoreClient/Models/AnimalFarm.swift +Sources/PetstoreClient/Models/ApiResponse.swift +Sources/PetstoreClient/Models/ArrayOfArrayOfNumberOnly.swift +Sources/PetstoreClient/Models/ArrayOfNumberOnly.swift +Sources/PetstoreClient/Models/ArrayTest.swift +Sources/PetstoreClient/Models/BigCat.swift +Sources/PetstoreClient/Models/BigCatAllOf.swift +Sources/PetstoreClient/Models/Capitalization.swift +Sources/PetstoreClient/Models/Cat.swift +Sources/PetstoreClient/Models/CatAllOf.swift +Sources/PetstoreClient/Models/Category.swift +Sources/PetstoreClient/Models/ClassModel.swift +Sources/PetstoreClient/Models/Client.swift +Sources/PetstoreClient/Models/Dog.swift +Sources/PetstoreClient/Models/DogAllOf.swift +Sources/PetstoreClient/Models/EnumArrays.swift +Sources/PetstoreClient/Models/EnumClass.swift +Sources/PetstoreClient/Models/EnumTest.swift +Sources/PetstoreClient/Models/File.swift +Sources/PetstoreClient/Models/FileSchemaTestClass.swift +Sources/PetstoreClient/Models/FormatTest.swift +Sources/PetstoreClient/Models/HasOnlyReadOnly.swift +Sources/PetstoreClient/Models/List.swift +Sources/PetstoreClient/Models/MapTest.swift +Sources/PetstoreClient/Models/MixedPropertiesAndAdditionalPropertiesClass.swift +Sources/PetstoreClient/Models/Model200Response.swift +Sources/PetstoreClient/Models/Name.swift +Sources/PetstoreClient/Models/NumberOnly.swift +Sources/PetstoreClient/Models/Order.swift +Sources/PetstoreClient/Models/OuterComposite.swift +Sources/PetstoreClient/Models/OuterEnum.swift +Sources/PetstoreClient/Models/Pet.swift +Sources/PetstoreClient/Models/ReadOnlyFirst.swift +Sources/PetstoreClient/Models/Return.swift +Sources/PetstoreClient/Models/SpecialModelName.swift +Sources/PetstoreClient/Models/StringBooleanMap.swift +Sources/PetstoreClient/Models/Tag.swift +Sources/PetstoreClient/Models/TypeHolderDefault.swift +Sources/PetstoreClient/Models/TypeHolderExample.swift +Sources/PetstoreClient/Models/User.swift +Sources/PetstoreClient/Models/XmlItem.swift +docs/AdditionalPropertiesAnyType.md +docs/AdditionalPropertiesArray.md +docs/AdditionalPropertiesBoolean.md +docs/AdditionalPropertiesClass.md +docs/AdditionalPropertiesInteger.md +docs/AdditionalPropertiesNumber.md +docs/AdditionalPropertiesObject.md +docs/AdditionalPropertiesString.md +docs/Animal.md +docs/AnimalFarm.md +docs/AnotherFakeAPI.md +docs/ApiResponse.md +docs/ArrayOfArrayOfNumberOnly.md +docs/ArrayOfNumberOnly.md +docs/ArrayTest.md +docs/BigCat.md +docs/BigCatAllOf.md +docs/Capitalization.md +docs/Cat.md +docs/CatAllOf.md +docs/Category.md +docs/ClassModel.md +docs/Client.md +docs/Dog.md +docs/DogAllOf.md +docs/EnumArrays.md +docs/EnumClass.md +docs/EnumTest.md +docs/FakeAPI.md +docs/FakeClassnameTags123API.md +docs/File.md +docs/FileSchemaTestClass.md +docs/FormatTest.md +docs/HasOnlyReadOnly.md +docs/List.md +docs/MapTest.md +docs/MixedPropertiesAndAdditionalPropertiesClass.md +docs/Model200Response.md +docs/Name.md +docs/NumberOnly.md +docs/Order.md +docs/OuterComposite.md +docs/OuterEnum.md +docs/Pet.md +docs/PetAPI.md +docs/ReadOnlyFirst.md +docs/Return.md +docs/SpecialModelName.md +docs/StoreAPI.md +docs/StringBooleanMap.md +docs/Tag.md +docs/TypeHolderDefault.md +docs/TypeHolderExample.md +docs/User.md +docs/UserAPI.md +docs/XmlItem.md diff --git a/samples/client/petstore/swift5/vaporLibrary/.openapi-generator/VERSION b/samples/client/petstore/swift5/vaporLibrary/.openapi-generator/VERSION new file mode 100644 index 00000000000..4b448de535c --- /dev/null +++ b/samples/client/petstore/swift5/vaporLibrary/.openapi-generator/VERSION @@ -0,0 +1 @@ +5.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/swift5/vaporLibrary/.swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata b/samples/client/petstore/swift5/vaporLibrary/.swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata new file mode 100644 index 00000000000..919434a6254 --- /dev/null +++ b/samples/client/petstore/swift5/vaporLibrary/.swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/samples/client/petstore/swift5/vaporLibrary/Package.resolved b/samples/client/petstore/swift5/vaporLibrary/Package.resolved new file mode 100644 index 00000000000..2d40b361051 --- /dev/null +++ b/samples/client/petstore/swift5/vaporLibrary/Package.resolved @@ -0,0 +1,160 @@ +{ + "object": { + "pins": [ + { + "package": "AnyCodable", + "repositoryURL": "https://github.com/Flight-School/AnyCodable", + "state": { + "branch": null, + "revision": "69261f239f0fffaf51495dadc4f8483fbfe97025", + "version": "0.6.1" + } + }, + { + "package": "async-http-client", + "repositoryURL": "https://github.com/swift-server/async-http-client.git", + "state": { + "branch": null, + "revision": "8e4d51908dd49272667126403bf977c5c503f78f", + "version": "1.5.0" + } + }, + { + "package": "async-kit", + "repositoryURL": "https://github.com/vapor/async-kit.git", + "state": { + "branch": null, + "revision": "c1de408100a2f2e4ab2ea06512e8635bc1a59144", + "version": "1.3.1" + } + }, + { + "package": "console-kit", + "repositoryURL": "https://github.com/vapor/console-kit.git", + "state": { + "branch": null, + "revision": "cfe8bcd58f74ffecb4f536d8237de146b634ecd3", + "version": "4.2.6" + } + }, + { + "package": "multipart-kit", + "repositoryURL": "https://github.com/vapor/multipart-kit.git", + "state": { + "branch": null, + "revision": "c9ea04017b7fb3b1f034ad7a77f8e53d3e080be5", + "version": "4.2.1" + } + }, + { + "package": "routing-kit", + "repositoryURL": "https://github.com/vapor/routing-kit.git", + "state": { + "branch": null, + "revision": "a0801a36a6ad501d5ad6285cbcd4774de6b0a734", + "version": "4.3.0" + } + }, + { + "package": "swift-backtrace", + "repositoryURL": "https://github.com/swift-server/swift-backtrace.git", + "state": { + "branch": null, + "revision": "54a65d6391a1467a896d0d351ff2de6f469ee53c", + "version": "1.2.3" + } + }, + { + "package": "swift-crypto", + "repositoryURL": "https://github.com/apple/swift-crypto.git", + "state": { + "branch": null, + "revision": "3bea268b223651c4ab7b7b9ad62ef9b2d4143eb6", + "version": "1.1.6" + } + }, + { + "package": "swift-log", + "repositoryURL": "https://github.com/apple/swift-log.git", + "state": { + "branch": null, + "revision": "5d66f7ba25daf4f94100e7022febf3c75e37a6c7", + "version": "1.4.2" + } + }, + { + "package": "swift-metrics", + "repositoryURL": "https://github.com/apple/swift-metrics.git", + "state": { + "branch": null, + "revision": "e382458581b05839a571c578e90060fff499f101", + "version": "2.1.1" + } + }, + { + "package": "swift-nio", + "repositoryURL": "https://github.com/apple/swift-nio.git", + "state": { + "branch": null, + "revision": "d79e33308b0ac83326b0ead0ea6446e604b8162d", + "version": "2.30.0" + } + }, + { + "package": "swift-nio-extras", + "repositoryURL": "https://github.com/apple/swift-nio-extras.git", + "state": { + "branch": null, + "revision": "f72c4688f89c28502105509186eadc49a49cb922", + "version": "1.10.0" + } + }, + { + "package": "swift-nio-http2", + "repositoryURL": "https://github.com/apple/swift-nio-http2.git", + "state": { + "branch": null, + "revision": "13b6a7a83864005334818d7ea2a3053869a96c04", + "version": "1.18.0" + } + }, + { + "package": "swift-nio-ssl", + "repositoryURL": "https://github.com/apple/swift-nio-ssl.git", + "state": { + "branch": null, + "revision": "9db7cee4b62c39160a6bd513a47a1ecdcceac18a", + "version": "2.14.0" + } + }, + { + "package": "swift-nio-transport-services", + "repositoryURL": "https://github.com/apple/swift-nio-transport-services.git", + "state": { + "branch": null, + "revision": "39587bceccda72780e2a8a8c5e857e42a9df2fa8", + "version": "1.11.0" + } + }, + { + "package": "vapor", + "repositoryURL": "https://github.com/vapor/vapor", + "state": { + "branch": null, + "revision": "086d0b80f2c3623ffd6b5e32b964ad00b67c2e90", + "version": "4.47.1" + } + }, + { + "package": "websocket-kit", + "repositoryURL": "https://github.com/vapor/websocket-kit.git", + "state": { + "branch": null, + "revision": "a2d26b3de8b3be292f3208d1c74024f76ac503da", + "version": "2.1.3" + } + } + ] + }, + "version": 1 +} diff --git a/samples/client/petstore/swift5/vaporLibrary/Package.swift b/samples/client/petstore/swift5/vaporLibrary/Package.swift new file mode 100644 index 00000000000..d467b6e4a2e --- /dev/null +++ b/samples/client/petstore/swift5/vaporLibrary/Package.swift @@ -0,0 +1,31 @@ +// swift-tools-version:5.1 + +import PackageDescription + +let package = Package( + name: "PetstoreClient", + platforms: [ + .macOS(.v10_15), + ], + products: [ + // Products define the executables and libraries produced by a package, and make them visible to other packages. + .library( + name: "PetstoreClient", + targets: ["PetstoreClient"] + ), + ], + dependencies: [ + // Dependencies declare other packages that this package depends on. + .package(url: "https://github.com/Flight-School/AnyCodable", from: "0.6.1"), + .package(url: "https://github.com/vapor/vapor", from: "4.0.0") + ], + targets: [ + // Targets are the basic building blocks of a package. A target can define a module or a test suite. + // Targets can depend on other targets in this package, and on products in packages which this package depends on. + .target( + name: "PetstoreClient", + dependencies: ["AnyCodable", "Vapor", ], + path: "Sources/PetstoreClient" + ), + ] +) diff --git a/samples/client/petstore/swift5/vaporLibrary/README.md b/samples/client/petstore/swift5/vaporLibrary/README.md new file mode 100644 index 00000000000..ee3cf1af06f --- /dev/null +++ b/samples/client/petstore/swift5/vaporLibrary/README.md @@ -0,0 +1,149 @@ +# Swift5 API client for PetstoreClient + +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 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.Swift5ClientCodegen + +## Installation + +Add the following entry in your Package.swift: + +> .package(path: "./PetstoreClient") + +## Documentation for API Endpoints + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +Class | Method | HTTP request | Description +------------ | ------------- | ------------- | ------------- +*AnotherFakeAPI* | [**call123testSpecialTags**](docs/AnotherFakeAPI.md#call123testspecialtags) | **PATCH** /another-fake/dummy | To test special tags +*FakeAPI* | [**createXmlItem**](docs/FakeAPI.md#createxmlitem) | **POST** /fake/create_xml_item | creates an XmlItem +*FakeAPI* | [**fakeOuterBooleanSerialize**](docs/FakeAPI.md#fakeouterbooleanserialize) | **POST** /fake/outer/boolean | +*FakeAPI* | [**fakeOuterCompositeSerialize**](docs/FakeAPI.md#fakeoutercompositeserialize) | **POST** /fake/outer/composite | +*FakeAPI* | [**fakeOuterNumberSerialize**](docs/FakeAPI.md#fakeouternumberserialize) | **POST** /fake/outer/number | +*FakeAPI* | [**fakeOuterStringSerialize**](docs/FakeAPI.md#fakeouterstringserialize) | **POST** /fake/outer/string | +*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 +*FakeAPI* | [**testEndpointParameters**](docs/FakeAPI.md#testendpointparameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 +*FakeAPI* | [**testEnumParameters**](docs/FakeAPI.md#testenumparameters) | **GET** /fake | To test enum parameters +*FakeAPI* | [**testGroupParameters**](docs/FakeAPI.md#testgroupparameters) | **DELETE** /fake | Fake endpoint to test group parameters (optional) +*FakeAPI* | [**testInlineAdditionalProperties**](docs/FakeAPI.md#testinlineadditionalproperties) | **POST** /fake/inline-additionalProperties | test inline additionalProperties +*FakeAPI* | [**testJsonFormData**](docs/FakeAPI.md#testjsonformdata) | **GET** /fake/jsonFormData | test json serialization of form data +*FakeAPI* | [**testQueryParameterCollectionFormat**](docs/FakeAPI.md#testqueryparametercollectionformat) | **PUT** /fake/test-query-paramters | +*FakeClassnameTags123API* | [**testClassname**](docs/FakeClassnameTags123API.md#testclassname) | **PATCH** /fake_classname_test | To test class name in snake case +*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 +*PetAPI* | [**uploadFileWithRequiredFile**](docs/PetAPI.md#uploadfilewithrequiredfile) | **POST** /fake/{petId}/uploadImageWithRequiredFile | uploads an image (required) +*StoreAPI* | [**deleteOrder**](docs/StoreAPI.md#deleteorder) | **DELETE** /store/order/{order_id} | 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/{order_id} | 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 + + - [AdditionalPropertiesAnyType](docs/AdditionalPropertiesAnyType.md) + - [AdditionalPropertiesArray](docs/AdditionalPropertiesArray.md) + - [AdditionalPropertiesBoolean](docs/AdditionalPropertiesBoolean.md) + - [AdditionalPropertiesClass](docs/AdditionalPropertiesClass.md) + - [AdditionalPropertiesInteger](docs/AdditionalPropertiesInteger.md) + - [AdditionalPropertiesNumber](docs/AdditionalPropertiesNumber.md) + - [AdditionalPropertiesObject](docs/AdditionalPropertiesObject.md) + - [AdditionalPropertiesString](docs/AdditionalPropertiesString.md) + - [Animal](docs/Animal.md) + - [AnimalFarm](docs/AnimalFarm.md) + - [ApiResponse](docs/ApiResponse.md) + - [ArrayOfArrayOfNumberOnly](docs/ArrayOfArrayOfNumberOnly.md) + - [ArrayOfNumberOnly](docs/ArrayOfNumberOnly.md) + - [ArrayTest](docs/ArrayTest.md) + - [BigCat](docs/BigCat.md) + - [BigCatAllOf](docs/BigCatAllOf.md) + - [Capitalization](docs/Capitalization.md) + - [Cat](docs/Cat.md) + - [CatAllOf](docs/CatAllOf.md) + - [Category](docs/Category.md) + - [ClassModel](docs/ClassModel.md) + - [Client](docs/Client.md) + - [Dog](docs/Dog.md) + - [DogAllOf](docs/DogAllOf.md) + - [EnumArrays](docs/EnumArrays.md) + - [EnumClass](docs/EnumClass.md) + - [EnumTest](docs/EnumTest.md) + - [File](docs/File.md) + - [FileSchemaTestClass](docs/FileSchemaTestClass.md) + - [FormatTest](docs/FormatTest.md) + - [HasOnlyReadOnly](docs/HasOnlyReadOnly.md) + - [List](docs/List.md) + - [MapTest](docs/MapTest.md) + - [MixedPropertiesAndAdditionalPropertiesClass](docs/MixedPropertiesAndAdditionalPropertiesClass.md) + - [Model200Response](docs/Model200Response.md) + - [Name](docs/Name.md) + - [NumberOnly](docs/NumberOnly.md) + - [Order](docs/Order.md) + - [OuterComposite](docs/OuterComposite.md) + - [OuterEnum](docs/OuterEnum.md) + - [Pet](docs/Pet.md) + - [ReadOnlyFirst](docs/ReadOnlyFirst.md) + - [Return](docs/Return.md) + - [SpecialModelName](docs/SpecialModelName.md) + - [StringBooleanMap](docs/StringBooleanMap.md) + - [Tag](docs/Tag.md) + - [TypeHolderDefault](docs/TypeHolderDefault.md) + - [TypeHolderExample](docs/TypeHolderExample.md) + - [User](docs/User.md) + - [XmlItem](docs/XmlItem.md) + + +## Documentation For Authorization + + +## api_key + +- **Type**: API key +- **API key parameter name**: api_key +- **Location**: HTTP header + +## api_key_query + +- **Type**: API key +- **API key parameter name**: api_key_query +- **Location**: URL query string + +## http_basic_test + +- **Type**: HTTP basic authentication + +## 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 + + +## Author + + + diff --git a/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/APIs.swift b/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/APIs.swift new file mode 100644 index 00000000000..975fee896fa --- /dev/null +++ b/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/APIs.swift @@ -0,0 +1,16 @@ +// APIs.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +import Vapor + +@available(*, deprecated, renamed: "PetstoreClient") +public typealias PetstoreClientAPI = PetstoreClient + +open class PetstoreClient { + public static var basePath = "http://petstore.swagger.io:80/v2" + public static var customHeaders: HTTPHeaders = [:] +} diff --git a/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/APIs/AnotherFakeAPI.swift b/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/APIs/AnotherFakeAPI.swift new file mode 100644 index 00000000000..ac279c5e199 --- /dev/null +++ b/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/APIs/AnotherFakeAPI.swift @@ -0,0 +1,64 @@ +// +// AnotherFakeAPI.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +import Vapor +#if canImport(AnyCodable) +import AnyCodable +#endif + +open class AnotherFakeAPI { + + /** + To test special tags + PATCH /another-fake/dummy + To test special tags and operation ID starting with number + - parameter body: (body) client model + - returns: `EventLoopFuture` of `ClientResponse` + */ + open class func call123testSpecialTagsRaw(body: Client, headers: HTTPHeaders = PetstoreClient.customHeaders, beforeSend: (inout ClientRequest) throws -> () = { _ in }) -> EventLoopFuture { + let localVariablePath = "/another-fake/dummy" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + + guard let localVariableApiClient = Configuration.apiClient else { + fatalError("Configuration.apiClient is not set.") + } + + return localVariableApiClient.send(.PATCH, headers: headers, to: URI(string: localVariableURLString)) { localVariableRequest in + try Configuration.apiWrapper(&localVariableRequest) + + + try localVariableRequest.content.encode(body, using: Configuration.contentConfiguration.requireEncoder(for: Client.defaultContentType)) + + try beforeSend(&localVariableRequest) + } + } + + public enum Call123testSpecialTags { + case http200(value: Client, raw: ClientResponse) + case http0(raw: ClientResponse) + } + + /** + To test special tags + PATCH /another-fake/dummy + To test special tags and operation ID starting with number + - parameter body: (body) client model + - returns: `EventLoopFuture` of `Call123testSpecialTags` + */ + open class func call123testSpecialTags(body: Client, headers: HTTPHeaders = PetstoreClient.customHeaders, beforeSend: (inout ClientRequest) throws -> () = { _ in }) -> EventLoopFuture { + return call123testSpecialTagsRaw(body: body, headers: headers, beforeSend: beforeSend).flatMapThrowing { response -> Call123testSpecialTags in + switch response.status.code { + case 200: + return .http200(value: try response.content.decode(Client.self, using: Configuration.contentConfiguration.requireDecoder(for: Client.defaultContentType)), raw: response) + default: + return .http0(raw: response) + } + } + } + +} diff --git a/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/APIs/FakeAPI.swift b/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/APIs/FakeAPI.swift new file mode 100644 index 00000000000..16aa16bac11 --- /dev/null +++ b/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/APIs/FakeAPI.swift @@ -0,0 +1,882 @@ +// +// FakeAPI.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +import Vapor +#if canImport(AnyCodable) +import AnyCodable +#endif + +open class FakeAPI { + + /** + creates an XmlItem + POST /fake/create_xml_item + this route creates an XmlItem + - parameter xmlItem: (body) XmlItem Body + - returns: `EventLoopFuture` of `ClientResponse` + */ + open class func createXmlItemRaw(xmlItem: XmlItem, headers: HTTPHeaders = PetstoreClient.customHeaders, beforeSend: (inout ClientRequest) throws -> () = { _ in }) -> EventLoopFuture { + let localVariablePath = "/fake/create_xml_item" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + + guard let localVariableApiClient = Configuration.apiClient else { + fatalError("Configuration.apiClient is not set.") + } + + return localVariableApiClient.send(.POST, headers: headers, to: URI(string: localVariableURLString)) { localVariableRequest in + try Configuration.apiWrapper(&localVariableRequest) + + + try localVariableRequest.content.encode(xmlItem, using: Configuration.contentConfiguration.requireEncoder(for: XmlItem.defaultContentType)) + + try beforeSend(&localVariableRequest) + } + } + + public enum CreateXmlItem { + case http200(raw: ClientResponse) + case http0(raw: ClientResponse) + } + + /** + creates an XmlItem + POST /fake/create_xml_item + this route creates an XmlItem + - parameter xmlItem: (body) XmlItem Body + - returns: `EventLoopFuture` of `CreateXmlItem` + */ + open class func createXmlItem(xmlItem: XmlItem, headers: HTTPHeaders = PetstoreClient.customHeaders, beforeSend: (inout ClientRequest) throws -> () = { _ in }) -> EventLoopFuture { + return createXmlItemRaw(xmlItem: xmlItem, headers: headers, beforeSend: beforeSend).flatMapThrowing { response -> CreateXmlItem in + switch response.status.code { + case 200: + return .http200(raw: response) + default: + return .http0(raw: response) + } + } + } + + + /** + POST /fake/outer/boolean + Test serialization of outer boolean types + - parameter body: (body) Input boolean as post body (optional) + - returns: `EventLoopFuture` of `ClientResponse` + */ + open class func fakeOuterBooleanSerializeRaw(body: Bool? = nil, headers: HTTPHeaders = PetstoreClient.customHeaders, beforeSend: (inout ClientRequest) throws -> () = { _ in }) -> EventLoopFuture { + let localVariablePath = "/fake/outer/boolean" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + + guard let localVariableApiClient = Configuration.apiClient else { + fatalError("Configuration.apiClient is not set.") + } + + return localVariableApiClient.send(.POST, headers: headers, to: URI(string: localVariableURLString)) { localVariableRequest in + try Configuration.apiWrapper(&localVariableRequest) + + + if let localVariableBody = body { + try localVariableRequest.content.encode(localVariableBody, using: Configuration.contentConfiguration.requireEncoder(for: Bool.defaultContentType)) + } + + try beforeSend(&localVariableRequest) + } + } + + public enum FakeOuterBooleanSerialize { + case http200(value: Bool, raw: ClientResponse) + case http0(raw: ClientResponse) + } + + /** + POST /fake/outer/boolean + Test serialization of outer boolean types + - parameter body: (body) Input boolean as post body (optional) + - returns: `EventLoopFuture` of `FakeOuterBooleanSerialize` + */ + open class func fakeOuterBooleanSerialize(body: Bool? = nil, headers: HTTPHeaders = PetstoreClient.customHeaders, beforeSend: (inout ClientRequest) throws -> () = { _ in }) -> EventLoopFuture { + return fakeOuterBooleanSerializeRaw(body: body, headers: headers, beforeSend: beforeSend).flatMapThrowing { response -> FakeOuterBooleanSerialize in + switch response.status.code { + case 200: + return .http200(value: try response.content.decode(Bool.self, using: Configuration.contentConfiguration.requireDecoder(for: Bool.defaultContentType)), raw: response) + default: + return .http0(raw: response) + } + } + } + + + /** + POST /fake/outer/composite + Test serialization of object with outer number type + - parameter body: (body) Input composite as post body (optional) + - returns: `EventLoopFuture` of `ClientResponse` + */ + open class func fakeOuterCompositeSerializeRaw(body: OuterComposite? = nil, headers: HTTPHeaders = PetstoreClient.customHeaders, beforeSend: (inout ClientRequest) throws -> () = { _ in }) -> EventLoopFuture { + let localVariablePath = "/fake/outer/composite" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + + guard let localVariableApiClient = Configuration.apiClient else { + fatalError("Configuration.apiClient is not set.") + } + + return localVariableApiClient.send(.POST, headers: headers, to: URI(string: localVariableURLString)) { localVariableRequest in + try Configuration.apiWrapper(&localVariableRequest) + + + if let localVariableBody = body { + try localVariableRequest.content.encode(localVariableBody, using: Configuration.contentConfiguration.requireEncoder(for: OuterComposite.defaultContentType)) + } + + try beforeSend(&localVariableRequest) + } + } + + public enum FakeOuterCompositeSerialize { + case http200(value: OuterComposite, raw: ClientResponse) + case http0(raw: ClientResponse) + } + + /** + POST /fake/outer/composite + Test serialization of object with outer number type + - parameter body: (body) Input composite as post body (optional) + - returns: `EventLoopFuture` of `FakeOuterCompositeSerialize` + */ + open class func fakeOuterCompositeSerialize(body: OuterComposite? = nil, headers: HTTPHeaders = PetstoreClient.customHeaders, beforeSend: (inout ClientRequest) throws -> () = { _ in }) -> EventLoopFuture { + return fakeOuterCompositeSerializeRaw(body: body, headers: headers, beforeSend: beforeSend).flatMapThrowing { response -> FakeOuterCompositeSerialize in + switch response.status.code { + case 200: + return .http200(value: try response.content.decode(OuterComposite.self, using: Configuration.contentConfiguration.requireDecoder(for: OuterComposite.defaultContentType)), raw: response) + default: + return .http0(raw: response) + } + } + } + + + /** + POST /fake/outer/number + Test serialization of outer number types + - parameter body: (body) Input number as post body (optional) + - returns: `EventLoopFuture` of `ClientResponse` + */ + open class func fakeOuterNumberSerializeRaw(body: Double? = nil, headers: HTTPHeaders = PetstoreClient.customHeaders, beforeSend: (inout ClientRequest) throws -> () = { _ in }) -> EventLoopFuture { + let localVariablePath = "/fake/outer/number" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + + guard let localVariableApiClient = Configuration.apiClient else { + fatalError("Configuration.apiClient is not set.") + } + + return localVariableApiClient.send(.POST, headers: headers, to: URI(string: localVariableURLString)) { localVariableRequest in + try Configuration.apiWrapper(&localVariableRequest) + + + if let localVariableBody = body { + try localVariableRequest.content.encode(localVariableBody, using: Configuration.contentConfiguration.requireEncoder(for: Double.defaultContentType)) + } + + try beforeSend(&localVariableRequest) + } + } + + public enum FakeOuterNumberSerialize { + case http200(value: Double, raw: ClientResponse) + case http0(raw: ClientResponse) + } + + /** + POST /fake/outer/number + Test serialization of outer number types + - parameter body: (body) Input number as post body (optional) + - returns: `EventLoopFuture` of `FakeOuterNumberSerialize` + */ + open class func fakeOuterNumberSerialize(body: Double? = nil, headers: HTTPHeaders = PetstoreClient.customHeaders, beforeSend: (inout ClientRequest) throws -> () = { _ in }) -> EventLoopFuture { + return fakeOuterNumberSerializeRaw(body: body, headers: headers, beforeSend: beforeSend).flatMapThrowing { response -> FakeOuterNumberSerialize in + switch response.status.code { + case 200: + return .http200(value: try response.content.decode(Double.self, using: Configuration.contentConfiguration.requireDecoder(for: Double.defaultContentType)), raw: response) + default: + return .http0(raw: response) + } + } + } + + + /** + POST /fake/outer/string + Test serialization of outer string types + - parameter body: (body) Input string as post body (optional) + - returns: `EventLoopFuture` of `ClientResponse` + */ + open class func fakeOuterStringSerializeRaw(body: String? = nil, headers: HTTPHeaders = PetstoreClient.customHeaders, beforeSend: (inout ClientRequest) throws -> () = { _ in }) -> EventLoopFuture { + let localVariablePath = "/fake/outer/string" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + + guard let localVariableApiClient = Configuration.apiClient else { + fatalError("Configuration.apiClient is not set.") + } + + return localVariableApiClient.send(.POST, headers: headers, to: URI(string: localVariableURLString)) { localVariableRequest in + try Configuration.apiWrapper(&localVariableRequest) + + + if let localVariableBody = body { + try localVariableRequest.content.encode(localVariableBody, using: Configuration.contentConfiguration.requireEncoder(for: String.defaultContentType)) + } + + try beforeSend(&localVariableRequest) + } + } + + public enum FakeOuterStringSerialize { + case http200(value: String, raw: ClientResponse) + case http0(raw: ClientResponse) + } + + /** + POST /fake/outer/string + Test serialization of outer string types + - parameter body: (body) Input string as post body (optional) + - returns: `EventLoopFuture` of `FakeOuterStringSerialize` + */ + open class func fakeOuterStringSerialize(body: String? = nil, headers: HTTPHeaders = PetstoreClient.customHeaders, beforeSend: (inout ClientRequest) throws -> () = { _ in }) -> EventLoopFuture { + return fakeOuterStringSerializeRaw(body: body, headers: headers, beforeSend: beforeSend).flatMapThrowing { response -> FakeOuterStringSerialize in + switch response.status.code { + case 200: + return .http200(value: try response.content.decode(String.self, using: Configuration.contentConfiguration.requireDecoder(for: String.defaultContentType)), raw: response) + default: + return .http0(raw: response) + } + } + } + + + /** + PUT /fake/body-with-file-schema + For this test, the body for this request much reference a schema named `File`. + - parameter body: (body) + - returns: `EventLoopFuture` of `ClientResponse` + */ + open class func testBodyWithFileSchemaRaw(body: FileSchemaTestClass, headers: HTTPHeaders = PetstoreClient.customHeaders, beforeSend: (inout ClientRequest) throws -> () = { _ in }) -> EventLoopFuture { + let localVariablePath = "/fake/body-with-file-schema" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + + guard let localVariableApiClient = Configuration.apiClient else { + fatalError("Configuration.apiClient is not set.") + } + + return localVariableApiClient.send(.PUT, headers: headers, to: URI(string: localVariableURLString)) { localVariableRequest in + try Configuration.apiWrapper(&localVariableRequest) + + + try localVariableRequest.content.encode(body, using: Configuration.contentConfiguration.requireEncoder(for: FileSchemaTestClass.defaultContentType)) + + try beforeSend(&localVariableRequest) + } + } + + public enum TestBodyWithFileSchema { + case http200(raw: ClientResponse) + case http0(raw: ClientResponse) + } + + /** + PUT /fake/body-with-file-schema + For this test, the body for this request much reference a schema named `File`. + - parameter body: (body) + - returns: `EventLoopFuture` of `TestBodyWithFileSchema` + */ + open class func testBodyWithFileSchema(body: FileSchemaTestClass, headers: HTTPHeaders = PetstoreClient.customHeaders, beforeSend: (inout ClientRequest) throws -> () = { _ in }) -> EventLoopFuture { + return testBodyWithFileSchemaRaw(body: body, headers: headers, beforeSend: beforeSend).flatMapThrowing { response -> TestBodyWithFileSchema in + switch response.status.code { + case 200: + return .http200(raw: response) + default: + return .http0(raw: response) + } + } + } + + + /** + PUT /fake/body-with-query-params + - parameter query: (query) + - parameter body: (body) + - returns: `EventLoopFuture` of `ClientResponse` + */ + open class func testBodyWithQueryParamsRaw(query: String, body: User, headers: HTTPHeaders = PetstoreClient.customHeaders, beforeSend: (inout ClientRequest) throws -> () = { _ in }) -> EventLoopFuture { + let localVariablePath = "/fake/body-with-query-params" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + + guard let localVariableApiClient = Configuration.apiClient else { + fatalError("Configuration.apiClient is not set.") + } + + return localVariableApiClient.send(.PUT, headers: headers, to: URI(string: localVariableURLString)) { localVariableRequest in + try Configuration.apiWrapper(&localVariableRequest) + + struct QueryParams: Content { + var query: String + } + try localVariableRequest.query.encode(QueryParams(query: query)) + try localVariableRequest.content.encode(body, using: Configuration.contentConfiguration.requireEncoder(for: User.defaultContentType)) + + try beforeSend(&localVariableRequest) + } + } + + public enum TestBodyWithQueryParams { + case http200(raw: ClientResponse) + case http0(raw: ClientResponse) + } + + /** + PUT /fake/body-with-query-params + - parameter query: (query) + - parameter body: (body) + - returns: `EventLoopFuture` of `TestBodyWithQueryParams` + */ + open class func testBodyWithQueryParams(query: String, body: User, headers: HTTPHeaders = PetstoreClient.customHeaders, beforeSend: (inout ClientRequest) throws -> () = { _ in }) -> EventLoopFuture { + return testBodyWithQueryParamsRaw(query: query, body: body, headers: headers, beforeSend: beforeSend).flatMapThrowing { response -> TestBodyWithQueryParams in + switch response.status.code { + case 200: + return .http200(raw: response) + default: + return .http0(raw: response) + } + } + } + + + /** + To test \"client\" model + PATCH /fake + To test \"client\" model + - parameter body: (body) client model + - returns: `EventLoopFuture` of `ClientResponse` + */ + open class func testClientModelRaw(body: Client, headers: HTTPHeaders = PetstoreClient.customHeaders, beforeSend: (inout ClientRequest) throws -> () = { _ in }) -> EventLoopFuture { + let localVariablePath = "/fake" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + + guard let localVariableApiClient = Configuration.apiClient else { + fatalError("Configuration.apiClient is not set.") + } + + return localVariableApiClient.send(.PATCH, headers: headers, to: URI(string: localVariableURLString)) { localVariableRequest in + try Configuration.apiWrapper(&localVariableRequest) + + + try localVariableRequest.content.encode(body, using: Configuration.contentConfiguration.requireEncoder(for: Client.defaultContentType)) + + try beforeSend(&localVariableRequest) + } + } + + public enum TestClientModel { + case http200(value: Client, raw: ClientResponse) + case http0(raw: ClientResponse) + } + + /** + To test \"client\" model + PATCH /fake + To test \"client\" model + - parameter body: (body) client model + - returns: `EventLoopFuture` of `TestClientModel` + */ + open class func testClientModel(body: Client, headers: HTTPHeaders = PetstoreClient.customHeaders, beforeSend: (inout ClientRequest) throws -> () = { _ in }) -> EventLoopFuture { + return testClientModelRaw(body: body, headers: headers, beforeSend: beforeSend).flatMapThrowing { response -> TestClientModel in + switch response.status.code { + case 200: + return .http200(value: try response.content.decode(Client.self, using: Configuration.contentConfiguration.requireDecoder(for: Client.defaultContentType)), raw: response) + default: + return .http0(raw: response) + } + } + } + + + /** + Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + POST /fake + Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + - BASIC: + - type: http + - name: http_basic_test + - parameter number: (form) None + - parameter double: (form) None + - parameter patternWithoutDelimiter: (form) None + - parameter byte: (form) None + - parameter integer: (form) None (optional) + - parameter int32: (form) None (optional) + - parameter int64: (form) None (optional) + - parameter float: (form) None (optional) + - parameter string: (form) None (optional) + - parameter binary: (form) None (optional) + - parameter date: (form) None (optional) + - parameter dateTime: (form) None (optional) + - parameter password: (form) None (optional) + - parameter callback: (form) None (optional) + - returns: `EventLoopFuture` of `ClientResponse` + */ + open class func testEndpointParametersRaw(number: Double, double: Double, patternWithoutDelimiter: String, byte: Data, integer: Int? = nil, int32: Int? = nil, int64: Int64? = nil, float: Float? = nil, string: String? = nil, binary: Data? = nil, date: Date? = nil, dateTime: Date? = nil, password: String? = nil, callback: String? = nil, headers: HTTPHeaders = PetstoreClient.customHeaders, beforeSend: (inout ClientRequest) throws -> () = { _ in }) -> EventLoopFuture { + let localVariablePath = "/fake" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + + guard let localVariableApiClient = Configuration.apiClient else { + fatalError("Configuration.apiClient is not set.") + } + + return localVariableApiClient.send(.POST, headers: headers, to: URI(string: localVariableURLString)) { localVariableRequest in + try Configuration.apiWrapper(&localVariableRequest) + + + struct FormParams: Content { + static let defaultContentType = Vapor.HTTPMediaType.formData + var integer: Int? + var int32: Int? + var int64: Int64? + var number: Double + var float: Float? + var double: Double + var string: String? + var patternWithoutDelimiter: String + var byte: Data + var binary: Data? + var date: Date? + var dateTime: Date? + var password: String? + var callback: String? + } + try localVariableRequest.content.encode(FormParams(integer: integer, int32: int32, int64: int64, number: number, float: float, double: double, string: string, patternWithoutDelimiter: patternWithoutDelimiter, byte: byte, binary: binary, date: date, dateTime: dateTime, password: password, callback: callback), using: Configuration.contentConfiguration.requireEncoder(for: FormParams.defaultContentType)) + try beforeSend(&localVariableRequest) + } + } + + public enum TestEndpointParameters { + case http400(raw: ClientResponse) + case http404(raw: ClientResponse) + case http0(raw: ClientResponse) + } + + /** + Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + POST /fake + Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + - BASIC: + - type: http + - name: http_basic_test + - parameter number: (form) None + - parameter double: (form) None + - parameter patternWithoutDelimiter: (form) None + - parameter byte: (form) None + - parameter integer: (form) None (optional) + - parameter int32: (form) None (optional) + - parameter int64: (form) None (optional) + - parameter float: (form) None (optional) + - parameter string: (form) None (optional) + - parameter binary: (form) None (optional) + - parameter date: (form) None (optional) + - parameter dateTime: (form) None (optional) + - parameter password: (form) None (optional) + - parameter callback: (form) None (optional) + - returns: `EventLoopFuture` of `TestEndpointParameters` + */ + open class func testEndpointParameters(number: Double, double: Double, patternWithoutDelimiter: String, byte: Data, integer: Int? = nil, int32: Int? = nil, int64: Int64? = nil, float: Float? = nil, string: String? = nil, binary: Data? = nil, date: Date? = nil, dateTime: Date? = nil, password: String? = nil, callback: String? = nil, headers: HTTPHeaders = PetstoreClient.customHeaders, beforeSend: (inout ClientRequest) throws -> () = { _ in }) -> EventLoopFuture { + return testEndpointParametersRaw(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, headers: headers, beforeSend: beforeSend).flatMapThrowing { response -> TestEndpointParameters in + switch response.status.code { + case 400: + return .http400(raw: response) + case 404: + return .http404(raw: response) + default: + return .http0(raw: response) + } + } + } + + + /** + * enum for parameter enumHeaderStringArray + */ + public enum EnumHeaderStringArray_testEnumParameters: String, CaseIterable, Content { + case greaterThan = ">" + case dollar = "$" + } + + /** + * enum for parameter enumHeaderString + */ + public enum EnumHeaderString_testEnumParameters: String, CaseIterable, Content { + case abc = "_abc" + case efg = "-efg" + case xyz = "(xyz)" + } + + /** + * enum for parameter enumQueryStringArray + */ + public enum EnumQueryStringArray_testEnumParameters: String, CaseIterable, Content { + case greaterThan = ">" + case dollar = "$" + } + + /** + * enum for parameter enumQueryString + */ + public enum EnumQueryString_testEnumParameters: String, CaseIterable, Content { + case abc = "_abc" + case efg = "-efg" + case xyz = "(xyz)" + } + + /** + * enum for parameter enumQueryInteger + */ + public enum EnumQueryInteger_testEnumParameters: Int, CaseIterable, Content { + case _1 = 1 + case number2 = -2 + } + + /** + * enum for parameter enumQueryDouble + */ + public enum EnumQueryDouble_testEnumParameters: Double, CaseIterable, Content { + case _11 = 1.1 + case number12 = -1.2 + } + + /** + * enum for parameter enumFormStringArray + */ + public enum EnumFormStringArray_testEnumParameters: String, CaseIterable, Content { + case greaterThan = ">" + case dollar = "$" + } + + /** + * enum for parameter enumFormString + */ + public enum EnumFormString_testEnumParameters: String, CaseIterable, Content { + case abc = "_abc" + case efg = "-efg" + case xyz = "(xyz)" + } + + /** + To test enum parameters + GET /fake + To test enum parameters + - parameter enumHeaderStringArray: (header) Header parameter enum test (string array) (optional) + - parameter enumHeaderString: (header) Header parameter enum test (string) (optional, default to .efg) + - parameter enumQueryStringArray: (query) Query parameter enum test (string array) (optional) + - parameter enumQueryString: (query) Query parameter enum test (string) (optional, default to .efg) + - parameter enumQueryInteger: (query) Query parameter enum test (double) (optional) + - parameter enumQueryDouble: (query) Query parameter enum test (double) (optional) + - parameter enumFormStringArray: (form) Form parameter enum test (string array) (optional, default to .dollar) + - parameter enumFormString: (form) Form parameter enum test (string) (optional, default to .efg) + - returns: `EventLoopFuture` of `ClientResponse` + */ + open class func testEnumParametersRaw(enumHeaderStringArray: [EnumHeaderStringArray_testEnumParameters]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [EnumQueryStringArray_testEnumParameters]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [EnumFormStringArray_testEnumParameters]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, headers: HTTPHeaders = PetstoreClient.customHeaders, beforeSend: (inout ClientRequest) throws -> () = { _ in }) -> EventLoopFuture { + let localVariablePath = "/fake" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + + guard let localVariableApiClient = Configuration.apiClient else { + fatalError("Configuration.apiClient is not set.") + } + + return localVariableApiClient.send(.GET, headers: headers, to: URI(string: localVariableURLString)) { localVariableRequest in + try Configuration.apiWrapper(&localVariableRequest) + + localVariableRequest.headers.add(name: "enum_header_string_array", value: enumHeaderStringArray?.map { $0.rawValue.description }.description ?? "") + + localVariableRequest.headers.add(name: "enum_header_string", value: enumHeaderString?.rawValue.description ?? "") + + struct QueryParams: Content { + var enumQueryStringArray: [EnumQueryStringArray_testEnumParameters]? + var enumQueryString: EnumQueryString_testEnumParameters? + var enumQueryInteger: EnumQueryInteger_testEnumParameters? + var enumQueryDouble: EnumQueryDouble_testEnumParameters? + } + try localVariableRequest.query.encode(QueryParams(enumQueryStringArray: enumQueryStringArray, enumQueryString: enumQueryString, enumQueryInteger: enumQueryInteger, enumQueryDouble: enumQueryDouble)) + struct FormParams: Content { + static let defaultContentType = Vapor.HTTPMediaType.formData + var enumFormStringArray: [EnumFormStringArray_testEnumParameters]? + var enumFormString: EnumFormString_testEnumParameters? + } + try localVariableRequest.content.encode(FormParams(enumFormStringArray: enumFormStringArray, enumFormString: enumFormString), using: Configuration.contentConfiguration.requireEncoder(for: FormParams.defaultContentType)) + try beforeSend(&localVariableRequest) + } + } + + public enum TestEnumParameters { + case http400(raw: ClientResponse) + case http404(raw: ClientResponse) + case http0(raw: ClientResponse) + } + + /** + To test enum parameters + GET /fake + To test enum parameters + - parameter enumHeaderStringArray: (header) Header parameter enum test (string array) (optional) + - parameter enumHeaderString: (header) Header parameter enum test (string) (optional, default to .efg) + - parameter enumQueryStringArray: (query) Query parameter enum test (string array) (optional) + - parameter enumQueryString: (query) Query parameter enum test (string) (optional, default to .efg) + - parameter enumQueryInteger: (query) Query parameter enum test (double) (optional) + - parameter enumQueryDouble: (query) Query parameter enum test (double) (optional) + - parameter enumFormStringArray: (form) Form parameter enum test (string array) (optional, default to .dollar) + - parameter enumFormString: (form) Form parameter enum test (string) (optional, default to .efg) + - returns: `EventLoopFuture` of `TestEnumParameters` + */ + open class func testEnumParameters(enumHeaderStringArray: [EnumHeaderStringArray_testEnumParameters]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [EnumQueryStringArray_testEnumParameters]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [EnumFormStringArray_testEnumParameters]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, headers: HTTPHeaders = PetstoreClient.customHeaders, beforeSend: (inout ClientRequest) throws -> () = { _ in }) -> EventLoopFuture { + return testEnumParametersRaw(enumHeaderStringArray: enumHeaderStringArray, enumHeaderString: enumHeaderString, enumQueryStringArray: enumQueryStringArray, enumQueryString: enumQueryString, enumQueryInteger: enumQueryInteger, enumQueryDouble: enumQueryDouble, enumFormStringArray: enumFormStringArray, enumFormString: enumFormString, headers: headers, beforeSend: beforeSend).flatMapThrowing { response -> TestEnumParameters in + switch response.status.code { + case 400: + return .http400(raw: response) + case 404: + return .http404(raw: response) + default: + return .http0(raw: response) + } + } + } + + + /** + Fake endpoint to test group parameters (optional) + DELETE /fake + Fake endpoint to test group parameters (optional) + - parameter requiredStringGroup: (query) Required String in group parameters + - parameter requiredBooleanGroup: (header) Required Boolean in group parameters + - parameter requiredInt64Group: (query) Required Integer in group parameters + - parameter stringGroup: (query) String in group parameters (optional) + - parameter booleanGroup: (header) Boolean in group parameters (optional) + - parameter int64Group: (query) Integer in group parameters (optional) + - returns: `EventLoopFuture` of `ClientResponse` + */ + open class func testGroupParametersRaw(requiredStringGroup: Int, requiredBooleanGroup: Bool, requiredInt64Group: Int64, stringGroup: Int? = nil, booleanGroup: Bool? = nil, int64Group: Int64? = nil, headers: HTTPHeaders = PetstoreClient.customHeaders, beforeSend: (inout ClientRequest) throws -> () = { _ in }) -> EventLoopFuture { + let localVariablePath = "/fake" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + + guard let localVariableApiClient = Configuration.apiClient else { + fatalError("Configuration.apiClient is not set.") + } + + return localVariableApiClient.send(.DELETE, headers: headers, to: URI(string: localVariableURLString)) { localVariableRequest in + try Configuration.apiWrapper(&localVariableRequest) + + localVariableRequest.headers.add(name: "required_boolean_group", value: requiredBooleanGroup.description) + + localVariableRequest.headers.add(name: "boolean_group", value: booleanGroup?.description ?? "") + + struct QueryParams: Content { + var requiredStringGroup: Int + var requiredInt64Group: Int64 + var stringGroup: Int? + var int64Group: Int64? + } + try localVariableRequest.query.encode(QueryParams(requiredStringGroup: requiredStringGroup, requiredInt64Group: requiredInt64Group, stringGroup: stringGroup, int64Group: int64Group)) + + try beforeSend(&localVariableRequest) + } + } + + public enum TestGroupParameters { + case http400(raw: ClientResponse) + case http0(raw: ClientResponse) + } + + /** + Fake endpoint to test group parameters (optional) + DELETE /fake + Fake endpoint to test group parameters (optional) + - parameter requiredStringGroup: (query) Required String in group parameters + - parameter requiredBooleanGroup: (header) Required Boolean in group parameters + - parameter requiredInt64Group: (query) Required Integer in group parameters + - parameter stringGroup: (query) String in group parameters (optional) + - parameter booleanGroup: (header) Boolean in group parameters (optional) + - parameter int64Group: (query) Integer in group parameters (optional) + - returns: `EventLoopFuture` of `TestGroupParameters` + */ + open class func testGroupParameters(requiredStringGroup: Int, requiredBooleanGroup: Bool, requiredInt64Group: Int64, stringGroup: Int? = nil, booleanGroup: Bool? = nil, int64Group: Int64? = nil, headers: HTTPHeaders = PetstoreClient.customHeaders, beforeSend: (inout ClientRequest) throws -> () = { _ in }) -> EventLoopFuture { + return testGroupParametersRaw(requiredStringGroup: requiredStringGroup, requiredBooleanGroup: requiredBooleanGroup, requiredInt64Group: requiredInt64Group, stringGroup: stringGroup, booleanGroup: booleanGroup, int64Group: int64Group, headers: headers, beforeSend: beforeSend).flatMapThrowing { response -> TestGroupParameters in + switch response.status.code { + case 400: + return .http400(raw: response) + default: + return .http0(raw: response) + } + } + } + + + /** + test inline additionalProperties + POST /fake/inline-additionalProperties + - parameter param: (body) request body + - returns: `EventLoopFuture` of `ClientResponse` + */ + open class func testInlineAdditionalPropertiesRaw(param: [String: String], headers: HTTPHeaders = PetstoreClient.customHeaders, beforeSend: (inout ClientRequest) throws -> () = { _ in }) -> EventLoopFuture { + let localVariablePath = "/fake/inline-additionalProperties" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + + guard let localVariableApiClient = Configuration.apiClient else { + fatalError("Configuration.apiClient is not set.") + } + + return localVariableApiClient.send(.POST, headers: headers, to: URI(string: localVariableURLString)) { localVariableRequest in + try Configuration.apiWrapper(&localVariableRequest) + + + try localVariableRequest.content.encode(param, using: Configuration.contentConfiguration.requireEncoder(for: [String: String].defaultContentType)) + + try beforeSend(&localVariableRequest) + } + } + + public enum TestInlineAdditionalProperties { + case http200(raw: ClientResponse) + case http0(raw: ClientResponse) + } + + /** + test inline additionalProperties + POST /fake/inline-additionalProperties + - parameter param: (body) request body + - returns: `EventLoopFuture` of `TestInlineAdditionalProperties` + */ + open class func testInlineAdditionalProperties(param: [String: String], headers: HTTPHeaders = PetstoreClient.customHeaders, beforeSend: (inout ClientRequest) throws -> () = { _ in }) -> EventLoopFuture { + return testInlineAdditionalPropertiesRaw(param: param, headers: headers, beforeSend: beforeSend).flatMapThrowing { response -> TestInlineAdditionalProperties in + switch response.status.code { + case 200: + return .http200(raw: response) + default: + return .http0(raw: response) + } + } + } + + + /** + test json serialization of form data + GET /fake/jsonFormData + - parameter param: (form) field1 + - parameter param2: (form) field2 + - returns: `EventLoopFuture` of `ClientResponse` + */ + open class func testJsonFormDataRaw(param: String, param2: String, headers: HTTPHeaders = PetstoreClient.customHeaders, beforeSend: (inout ClientRequest) throws -> () = { _ in }) -> EventLoopFuture { + let localVariablePath = "/fake/jsonFormData" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + + guard let localVariableApiClient = Configuration.apiClient else { + fatalError("Configuration.apiClient is not set.") + } + + return localVariableApiClient.send(.GET, headers: headers, to: URI(string: localVariableURLString)) { localVariableRequest in + try Configuration.apiWrapper(&localVariableRequest) + + + struct FormParams: Content { + static let defaultContentType = Vapor.HTTPMediaType.formData + var param: String + var param2: String + } + try localVariableRequest.content.encode(FormParams(param: param, param2: param2), using: Configuration.contentConfiguration.requireEncoder(for: FormParams.defaultContentType)) + try beforeSend(&localVariableRequest) + } + } + + public enum TestJsonFormData { + case http200(raw: ClientResponse) + case http0(raw: ClientResponse) + } + + /** + test json serialization of form data + GET /fake/jsonFormData + - parameter param: (form) field1 + - parameter param2: (form) field2 + - returns: `EventLoopFuture` of `TestJsonFormData` + */ + open class func testJsonFormData(param: String, param2: String, headers: HTTPHeaders = PetstoreClient.customHeaders, beforeSend: (inout ClientRequest) throws -> () = { _ in }) -> EventLoopFuture { + return testJsonFormDataRaw(param: param, param2: param2, headers: headers, beforeSend: beforeSend).flatMapThrowing { response -> TestJsonFormData in + switch response.status.code { + case 200: + return .http200(raw: response) + default: + return .http0(raw: response) + } + } + } + + + /** + PUT /fake/test-query-paramters + To test the collection format in query parameters + - parameter pipe: (query) + - parameter ioutil: (query) + - parameter http: (query) + - parameter url: (query) + - parameter context: (query) + - returns: `EventLoopFuture` of `ClientResponse` + */ + open class func testQueryParameterCollectionFormatRaw(pipe: [String], ioutil: [String], http: [String], url: [String], context: [String], headers: HTTPHeaders = PetstoreClient.customHeaders, beforeSend: (inout ClientRequest) throws -> () = { _ in }) -> EventLoopFuture { + let localVariablePath = "/fake/test-query-paramters" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + + guard let localVariableApiClient = Configuration.apiClient else { + fatalError("Configuration.apiClient is not set.") + } + + return localVariableApiClient.send(.PUT, headers: headers, to: URI(string: localVariableURLString)) { localVariableRequest in + try Configuration.apiWrapper(&localVariableRequest) + + struct QueryParams: Content { + var pipe: [String] + var ioutil: [String] + var http: [String] + var url: [String] + var context: [String] + } + try localVariableRequest.query.encode(QueryParams(pipe: pipe, ioutil: ioutil, http: http, url: url, context: context)) + + try beforeSend(&localVariableRequest) + } + } + + public enum TestQueryParameterCollectionFormat { + case http200(raw: ClientResponse) + case http0(raw: ClientResponse) + } + + /** + PUT /fake/test-query-paramters + To test the collection format in query parameters + - parameter pipe: (query) + - parameter ioutil: (query) + - parameter http: (query) + - parameter url: (query) + - parameter context: (query) + - returns: `EventLoopFuture` of `TestQueryParameterCollectionFormat` + */ + open class func testQueryParameterCollectionFormat(pipe: [String], ioutil: [String], http: [String], url: [String], context: [String], headers: HTTPHeaders = PetstoreClient.customHeaders, beforeSend: (inout ClientRequest) throws -> () = { _ in }) -> EventLoopFuture { + return testQueryParameterCollectionFormatRaw(pipe: pipe, ioutil: ioutil, http: http, url: url, context: context, headers: headers, beforeSend: beforeSend).flatMapThrowing { response -> TestQueryParameterCollectionFormat in + switch response.status.code { + case 200: + return .http200(raw: response) + default: + return .http0(raw: response) + } + } + } + +} diff --git a/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/APIs/FakeClassnameTags123API.swift b/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/APIs/FakeClassnameTags123API.swift new file mode 100644 index 00000000000..b7c84887c15 --- /dev/null +++ b/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/APIs/FakeClassnameTags123API.swift @@ -0,0 +1,70 @@ +// +// FakeClassnameTags123API.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +import Vapor +#if canImport(AnyCodable) +import AnyCodable +#endif + +open class FakeClassnameTags123API { + + /** + To test class name in snake case + PATCH /fake_classname_test + To test class name in snake case + - API Key: + - type: apiKey api_key_query (QUERY) + - name: api_key_query + - parameter body: (body) client model + - returns: `EventLoopFuture` of `ClientResponse` + */ + open class func testClassnameRaw(body: Client, headers: HTTPHeaders = PetstoreClient.customHeaders, beforeSend: (inout ClientRequest) throws -> () = { _ in }) -> EventLoopFuture { + let localVariablePath = "/fake_classname_test" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + + guard let localVariableApiClient = Configuration.apiClient else { + fatalError("Configuration.apiClient is not set.") + } + + return localVariableApiClient.send(.PATCH, headers: headers, to: URI(string: localVariableURLString)) { localVariableRequest in + try Configuration.apiWrapper(&localVariableRequest) + + + try localVariableRequest.content.encode(body, using: Configuration.contentConfiguration.requireEncoder(for: Client.defaultContentType)) + + try beforeSend(&localVariableRequest) + } + } + + public enum TestClassname { + case http200(value: Client, raw: ClientResponse) + case http0(raw: ClientResponse) + } + + /** + To test class name in snake case + PATCH /fake_classname_test + To test class name in snake case + - API Key: + - type: apiKey api_key_query (QUERY) + - name: api_key_query + - parameter body: (body) client model + - returns: `EventLoopFuture` of `TestClassname` + */ + open class func testClassname(body: Client, headers: HTTPHeaders = PetstoreClient.customHeaders, beforeSend: (inout ClientRequest) throws -> () = { _ in }) -> EventLoopFuture { + return testClassnameRaw(body: body, headers: headers, beforeSend: beforeSend).flatMapThrowing { response -> TestClassname in + switch response.status.code { + case 200: + return .http200(value: try response.content.decode(Client.self, using: Configuration.contentConfiguration.requireDecoder(for: Client.defaultContentType)), raw: response) + default: + return .http0(raw: response) + } + } + } + +} diff --git a/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/APIs/PetAPI.swift b/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/APIs/PetAPI.swift new file mode 100644 index 00000000000..fb35eba5e72 --- /dev/null +++ b/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/APIs/PetAPI.swift @@ -0,0 +1,581 @@ +// +// PetAPI.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +import Vapor +#if canImport(AnyCodable) +import AnyCodable +#endif + +open class PetAPI { + + /** + Add a new pet to the store + POST /pet + - OAuth: + - type: oauth2 + - name: petstore_auth + - parameter body: (body) Pet object that needs to be added to the store + - returns: `EventLoopFuture` of `ClientResponse` + */ + open class func addPetRaw(body: Pet, headers: HTTPHeaders = PetstoreClient.customHeaders, beforeSend: (inout ClientRequest) throws -> () = { _ in }) -> EventLoopFuture { + let localVariablePath = "/pet" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + + guard let localVariableApiClient = Configuration.apiClient else { + fatalError("Configuration.apiClient is not set.") + } + + return localVariableApiClient.send(.POST, headers: headers, to: URI(string: localVariableURLString)) { localVariableRequest in + try Configuration.apiWrapper(&localVariableRequest) + + + try localVariableRequest.content.encode(body, using: Configuration.contentConfiguration.requireEncoder(for: Pet.defaultContentType)) + + try beforeSend(&localVariableRequest) + } + } + + public enum AddPet { + case http200(raw: ClientResponse) + case http405(raw: ClientResponse) + case http0(raw: ClientResponse) + } + + /** + Add a new pet to the store + POST /pet + - OAuth: + - type: oauth2 + - name: petstore_auth + - parameter body: (body) Pet object that needs to be added to the store + - returns: `EventLoopFuture` of `AddPet` + */ + open class func addPet(body: Pet, headers: HTTPHeaders = PetstoreClient.customHeaders, beforeSend: (inout ClientRequest) throws -> () = { _ in }) -> EventLoopFuture { + return addPetRaw(body: body, headers: headers, beforeSend: beforeSend).flatMapThrowing { response -> AddPet in + switch response.status.code { + case 200: + return .http200(raw: response) + case 405: + return .http405(raw: response) + default: + return .http0(raw: response) + } + } + } + + + /** + Deletes a pet + DELETE /pet/{petId} + - OAuth: + - type: oauth2 + - name: petstore_auth + - parameter petId: (path) Pet id to delete + - parameter apiKey: (header) (optional) + - returns: `EventLoopFuture` of `ClientResponse` + */ + open class func deletePetRaw(petId: Int64, apiKey: String? = nil, headers: HTTPHeaders = PetstoreClient.customHeaders, beforeSend: (inout ClientRequest) throws -> () = { _ in }) -> EventLoopFuture { + var localVariablePath = "/pet/{petId}" + let petIdPreEscape = String(describing: petId) + let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + localVariablePath = localVariablePath.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClient.basePath + localVariablePath + + guard let localVariableApiClient = Configuration.apiClient else { + fatalError("Configuration.apiClient is not set.") + } + + return localVariableApiClient.send(.DELETE, headers: headers, to: URI(string: localVariableURLString)) { localVariableRequest in + try Configuration.apiWrapper(&localVariableRequest) + + localVariableRequest.headers.add(name: "api_key", value: apiKey?.description ?? "") + + + + try beforeSend(&localVariableRequest) + } + } + + public enum DeletePet { + case http200(raw: ClientResponse) + case http400(raw: ClientResponse) + case http0(raw: ClientResponse) + } + + /** + Deletes a pet + DELETE /pet/{petId} + - OAuth: + - type: oauth2 + - name: petstore_auth + - parameter petId: (path) Pet id to delete + - parameter apiKey: (header) (optional) + - returns: `EventLoopFuture` of `DeletePet` + */ + open class func deletePet(petId: Int64, apiKey: String? = nil, headers: HTTPHeaders = PetstoreClient.customHeaders, beforeSend: (inout ClientRequest) throws -> () = { _ in }) -> EventLoopFuture { + return deletePetRaw(petId: petId, apiKey: apiKey, headers: headers, beforeSend: beforeSend).flatMapThrowing { response -> DeletePet in + switch response.status.code { + case 200: + return .http200(raw: response) + case 400: + return .http400(raw: response) + default: + return .http0(raw: response) + } + } + } + + + /** + * enum for parameter status + */ + public enum Status_findPetsByStatus: String, CaseIterable, Content { + case available = "available" + case pending = "pending" + case sold = "sold" + } + + /** + Finds Pets by status + GET /pet/findByStatus + Multiple status values can be provided with comma separated strings + - OAuth: + - type: oauth2 + - name: petstore_auth + - parameter status: (query) Status values that need to be considered for filter + - returns: `EventLoopFuture` of `ClientResponse` + */ + open class func findPetsByStatusRaw(status: [Status_findPetsByStatus], headers: HTTPHeaders = PetstoreClient.customHeaders, beforeSend: (inout ClientRequest) throws -> () = { _ in }) -> EventLoopFuture { + let localVariablePath = "/pet/findByStatus" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + + guard let localVariableApiClient = Configuration.apiClient else { + fatalError("Configuration.apiClient is not set.") + } + + return localVariableApiClient.send(.GET, headers: headers, to: URI(string: localVariableURLString)) { localVariableRequest in + try Configuration.apiWrapper(&localVariableRequest) + + struct QueryParams: Content { + var status: [Status_findPetsByStatus] + } + try localVariableRequest.query.encode(QueryParams(status: status)) + + try beforeSend(&localVariableRequest) + } + } + + public enum FindPetsByStatus { + case http200(value: [Pet], raw: ClientResponse) + case http400(raw: ClientResponse) + case http0(raw: ClientResponse) + } + + /** + Finds Pets by status + GET /pet/findByStatus + Multiple status values can be provided with comma separated strings + - OAuth: + - type: oauth2 + - name: petstore_auth + - parameter status: (query) Status values that need to be considered for filter + - returns: `EventLoopFuture` of `FindPetsByStatus` + */ + open class func findPetsByStatus(status: [Status_findPetsByStatus], headers: HTTPHeaders = PetstoreClient.customHeaders, beforeSend: (inout ClientRequest) throws -> () = { _ in }) -> EventLoopFuture { + return findPetsByStatusRaw(status: status, headers: headers, beforeSend: beforeSend).flatMapThrowing { response -> FindPetsByStatus in + switch response.status.code { + case 200: + return .http200(value: try response.content.decode([Pet].self, using: Configuration.contentConfiguration.requireDecoder(for: [Pet].defaultContentType)), raw: response) + case 400: + return .http400(raw: response) + default: + return .http0(raw: response) + } + } + } + + + /** + Finds Pets by tags + GET /pet/findByTags + Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + - OAuth: + - type: oauth2 + - name: petstore_auth + - parameter tags: (query) Tags to filter by + - returns: `EventLoopFuture` of `ClientResponse` + */ + @available(*, deprecated, message: "This operation is deprecated.") + open class func findPetsByTagsRaw(tags: Set, headers: HTTPHeaders = PetstoreClient.customHeaders, beforeSend: (inout ClientRequest) throws -> () = { _ in }) -> EventLoopFuture { + let localVariablePath = "/pet/findByTags" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + + guard let localVariableApiClient = Configuration.apiClient else { + fatalError("Configuration.apiClient is not set.") + } + + return localVariableApiClient.send(.GET, headers: headers, to: URI(string: localVariableURLString)) { localVariableRequest in + try Configuration.apiWrapper(&localVariableRequest) + + struct QueryParams: Content { + var tags: Set + } + try localVariableRequest.query.encode(QueryParams(tags: tags)) + + try beforeSend(&localVariableRequest) + } + } + + public enum FindPetsByTags { + case http200(value: Set, raw: ClientResponse) + case http400(raw: ClientResponse) + case http0(raw: ClientResponse) + } + + /** + Finds Pets by tags + GET /pet/findByTags + Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + - OAuth: + - type: oauth2 + - name: petstore_auth + - parameter tags: (query) Tags to filter by + - returns: `EventLoopFuture` of `FindPetsByTags` + */ + @available(*, deprecated, message: "This operation is deprecated.") + open class func findPetsByTags(tags: Set, headers: HTTPHeaders = PetstoreClient.customHeaders, beforeSend: (inout ClientRequest) throws -> () = { _ in }) -> EventLoopFuture { + return findPetsByTagsRaw(tags: tags, headers: headers, beforeSend: beforeSend).flatMapThrowing { response -> FindPetsByTags in + switch response.status.code { + case 200: + return .http200(value: try response.content.decode(Set.self, using: Configuration.contentConfiguration.requireDecoder(for: Set.defaultContentType)), raw: response) + case 400: + return .http400(raw: response) + default: + return .http0(raw: response) + } + } + } + + + /** + Find pet by ID + GET /pet/{petId} + Returns a single pet + - API Key: + - type: apiKey api_key + - name: api_key + - parameter petId: (path) ID of pet to return + - returns: `EventLoopFuture` of `ClientResponse` + */ + open class func getPetByIdRaw(petId: Int64, headers: HTTPHeaders = PetstoreClient.customHeaders, beforeSend: (inout ClientRequest) throws -> () = { _ in }) -> EventLoopFuture { + var localVariablePath = "/pet/{petId}" + let petIdPreEscape = String(describing: petId) + let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + localVariablePath = localVariablePath.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClient.basePath + localVariablePath + + guard let localVariableApiClient = Configuration.apiClient else { + fatalError("Configuration.apiClient is not set.") + } + + return localVariableApiClient.send(.GET, headers: headers, to: URI(string: localVariableURLString)) { localVariableRequest in + try Configuration.apiWrapper(&localVariableRequest) + + + + try beforeSend(&localVariableRequest) + } + } + + public enum GetPetById { + case http200(value: Pet, raw: ClientResponse) + case http400(raw: ClientResponse) + case http404(raw: ClientResponse) + case http0(raw: ClientResponse) + } + + /** + Find pet by ID + GET /pet/{petId} + Returns a single pet + - API Key: + - type: apiKey api_key + - name: api_key + - parameter petId: (path) ID of pet to return + - returns: `EventLoopFuture` of `GetPetById` + */ + open class func getPetById(petId: Int64, headers: HTTPHeaders = PetstoreClient.customHeaders, beforeSend: (inout ClientRequest) throws -> () = { _ in }) -> EventLoopFuture { + return getPetByIdRaw(petId: petId, headers: headers, beforeSend: beforeSend).flatMapThrowing { response -> GetPetById in + switch response.status.code { + case 200: + return .http200(value: try response.content.decode(Pet.self, using: Configuration.contentConfiguration.requireDecoder(for: Pet.defaultContentType)), raw: response) + case 400: + return .http400(raw: response) + case 404: + return .http404(raw: response) + default: + return .http0(raw: response) + } + } + } + + + /** + Update an existing pet + PUT /pet + - OAuth: + - type: oauth2 + - name: petstore_auth + - parameter body: (body) Pet object that needs to be added to the store + - returns: `EventLoopFuture` of `ClientResponse` + */ + open class func updatePetRaw(body: Pet, headers: HTTPHeaders = PetstoreClient.customHeaders, beforeSend: (inout ClientRequest) throws -> () = { _ in }) -> EventLoopFuture { + let localVariablePath = "/pet" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + + guard let localVariableApiClient = Configuration.apiClient else { + fatalError("Configuration.apiClient is not set.") + } + + return localVariableApiClient.send(.PUT, headers: headers, to: URI(string: localVariableURLString)) { localVariableRequest in + try Configuration.apiWrapper(&localVariableRequest) + + + try localVariableRequest.content.encode(body, using: Configuration.contentConfiguration.requireEncoder(for: Pet.defaultContentType)) + + try beforeSend(&localVariableRequest) + } + } + + public enum UpdatePet { + case http200(raw: ClientResponse) + case http400(raw: ClientResponse) + case http404(raw: ClientResponse) + case http405(raw: ClientResponse) + case http0(raw: ClientResponse) + } + + /** + Update an existing pet + PUT /pet + - OAuth: + - type: oauth2 + - name: petstore_auth + - parameter body: (body) Pet object that needs to be added to the store + - returns: `EventLoopFuture` of `UpdatePet` + */ + open class func updatePet(body: Pet, headers: HTTPHeaders = PetstoreClient.customHeaders, beforeSend: (inout ClientRequest) throws -> () = { _ in }) -> EventLoopFuture { + return updatePetRaw(body: body, headers: headers, beforeSend: beforeSend).flatMapThrowing { response -> UpdatePet in + switch response.status.code { + case 200: + return .http200(raw: response) + case 400: + return .http400(raw: response) + case 404: + return .http404(raw: response) + case 405: + return .http405(raw: response) + default: + return .http0(raw: response) + } + } + } + + + /** + Updates a pet in the store with form data + POST /pet/{petId} + - OAuth: + - type: oauth2 + - name: petstore_auth + - parameter petId: (path) ID of pet that needs to be updated + - parameter name: (form) Updated name of the pet (optional) + - parameter status: (form) Updated status of the pet (optional) + - returns: `EventLoopFuture` of `ClientResponse` + */ + open class func updatePetWithFormRaw(petId: Int64, name: String? = nil, status: String? = nil, headers: HTTPHeaders = PetstoreClient.customHeaders, beforeSend: (inout ClientRequest) throws -> () = { _ in }) -> EventLoopFuture { + var localVariablePath = "/pet/{petId}" + let petIdPreEscape = String(describing: petId) + let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + localVariablePath = localVariablePath.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClient.basePath + localVariablePath + + guard let localVariableApiClient = Configuration.apiClient else { + fatalError("Configuration.apiClient is not set.") + } + + return localVariableApiClient.send(.POST, headers: headers, to: URI(string: localVariableURLString)) { localVariableRequest in + try Configuration.apiWrapper(&localVariableRequest) + + + struct FormParams: Content { + static let defaultContentType = Vapor.HTTPMediaType.formData + var name: String? + var status: String? + } + try localVariableRequest.content.encode(FormParams(name: name, status: status), using: Configuration.contentConfiguration.requireEncoder(for: FormParams.defaultContentType)) + try beforeSend(&localVariableRequest) + } + } + + public enum UpdatePetWithForm { + case http405(raw: ClientResponse) + case http0(raw: ClientResponse) + } + + /** + Updates a pet in the store with form data + POST /pet/{petId} + - OAuth: + - type: oauth2 + - name: petstore_auth + - parameter petId: (path) ID of pet that needs to be updated + - parameter name: (form) Updated name of the pet (optional) + - parameter status: (form) Updated status of the pet (optional) + - returns: `EventLoopFuture` of `UpdatePetWithForm` + */ + open class func updatePetWithForm(petId: Int64, name: String? = nil, status: String? = nil, headers: HTTPHeaders = PetstoreClient.customHeaders, beforeSend: (inout ClientRequest) throws -> () = { _ in }) -> EventLoopFuture { + return updatePetWithFormRaw(petId: petId, name: name, status: status, headers: headers, beforeSend: beforeSend).flatMapThrowing { response -> UpdatePetWithForm in + switch response.status.code { + case 405: + return .http405(raw: response) + default: + return .http0(raw: response) + } + } + } + + + /** + uploads an image + POST /pet/{petId}/uploadImage + - OAuth: + - type: oauth2 + - name: petstore_auth + - parameter petId: (path) ID of pet to update + - parameter additionalMetadata: (form) Additional data to pass to server (optional) + - parameter file: (form) file to upload (optional) + - returns: `EventLoopFuture` of `ClientResponse` + */ + open class func uploadFileRaw(petId: Int64, additionalMetadata: String? = nil, file: Data? = nil, headers: HTTPHeaders = PetstoreClient.customHeaders, beforeSend: (inout ClientRequest) throws -> () = { _ in }) -> EventLoopFuture { + var localVariablePath = "/pet/{petId}/uploadImage" + let petIdPreEscape = String(describing: petId) + let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + localVariablePath = localVariablePath.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClient.basePath + localVariablePath + + guard let localVariableApiClient = Configuration.apiClient else { + fatalError("Configuration.apiClient is not set.") + } + + return localVariableApiClient.send(.POST, headers: headers, to: URI(string: localVariableURLString)) { localVariableRequest in + try Configuration.apiWrapper(&localVariableRequest) + + + struct FormParams: Content { + static let defaultContentType = Vapor.HTTPMediaType.formData + var additionalMetadata: String? + var file: Data? + } + try localVariableRequest.content.encode(FormParams(additionalMetadata: additionalMetadata, file: file), using: Configuration.contentConfiguration.requireEncoder(for: FormParams.defaultContentType)) + try beforeSend(&localVariableRequest) + } + } + + public enum UploadFile { + case http200(value: ApiResponse, raw: ClientResponse) + case http0(raw: ClientResponse) + } + + /** + uploads an image + POST /pet/{petId}/uploadImage + - OAuth: + - type: oauth2 + - name: petstore_auth + - parameter petId: (path) ID of pet to update + - parameter additionalMetadata: (form) Additional data to pass to server (optional) + - parameter file: (form) file to upload (optional) + - returns: `EventLoopFuture` of `UploadFile` + */ + open class func uploadFile(petId: Int64, additionalMetadata: String? = nil, file: Data? = nil, headers: HTTPHeaders = PetstoreClient.customHeaders, beforeSend: (inout ClientRequest) throws -> () = { _ in }) -> EventLoopFuture { + return uploadFileRaw(petId: petId, additionalMetadata: additionalMetadata, file: file, headers: headers, beforeSend: beforeSend).flatMapThrowing { response -> UploadFile in + switch response.status.code { + case 200: + return .http200(value: try response.content.decode(ApiResponse.self, using: Configuration.contentConfiguration.requireDecoder(for: ApiResponse.defaultContentType)), raw: response) + default: + return .http0(raw: response) + } + } + } + + + /** + uploads an image (required) + POST /fake/{petId}/uploadImageWithRequiredFile + - OAuth: + - type: oauth2 + - name: petstore_auth + - parameter petId: (path) ID of pet to update + - parameter requiredFile: (form) file to upload + - parameter additionalMetadata: (form) Additional data to pass to server (optional) + - returns: `EventLoopFuture` of `ClientResponse` + */ + open class func uploadFileWithRequiredFileRaw(petId: Int64, requiredFile: Data, additionalMetadata: String? = nil, headers: HTTPHeaders = PetstoreClient.customHeaders, beforeSend: (inout ClientRequest) throws -> () = { _ in }) -> EventLoopFuture { + var localVariablePath = "/fake/{petId}/uploadImageWithRequiredFile" + let petIdPreEscape = String(describing: petId) + let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + localVariablePath = localVariablePath.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClient.basePath + localVariablePath + + guard let localVariableApiClient = Configuration.apiClient else { + fatalError("Configuration.apiClient is not set.") + } + + return localVariableApiClient.send(.POST, headers: headers, to: URI(string: localVariableURLString)) { localVariableRequest in + try Configuration.apiWrapper(&localVariableRequest) + + + struct FormParams: Content { + static let defaultContentType = Vapor.HTTPMediaType.formData + var additionalMetadata: String? + var requiredFile: Data + } + try localVariableRequest.content.encode(FormParams(additionalMetadata: additionalMetadata, requiredFile: requiredFile), using: Configuration.contentConfiguration.requireEncoder(for: FormParams.defaultContentType)) + try beforeSend(&localVariableRequest) + } + } + + public enum UploadFileWithRequiredFile { + case http200(value: ApiResponse, raw: ClientResponse) + case http0(raw: ClientResponse) + } + + /** + uploads an image (required) + POST /fake/{petId}/uploadImageWithRequiredFile + - OAuth: + - type: oauth2 + - name: petstore_auth + - parameter petId: (path) ID of pet to update + - parameter requiredFile: (form) file to upload + - parameter additionalMetadata: (form) Additional data to pass to server (optional) + - returns: `EventLoopFuture` of `UploadFileWithRequiredFile` + */ + open class func uploadFileWithRequiredFile(petId: Int64, requiredFile: Data, additionalMetadata: String? = nil, headers: HTTPHeaders = PetstoreClient.customHeaders, beforeSend: (inout ClientRequest) throws -> () = { _ in }) -> EventLoopFuture { + return uploadFileWithRequiredFileRaw(petId: petId, requiredFile: requiredFile, additionalMetadata: additionalMetadata, headers: headers, beforeSend: beforeSend).flatMapThrowing { response -> UploadFileWithRequiredFile in + switch response.status.code { + case 200: + return .http200(value: try response.content.decode(ApiResponse.self, using: Configuration.contentConfiguration.requireDecoder(for: ApiResponse.defaultContentType)), raw: response) + default: + return .http0(raw: response) + } + } + } + +} diff --git a/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/APIs/StoreAPI.swift b/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/APIs/StoreAPI.swift new file mode 100644 index 00000000000..0937a57ad3d --- /dev/null +++ b/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/APIs/StoreAPI.swift @@ -0,0 +1,228 @@ +// +// StoreAPI.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +import Vapor +#if canImport(AnyCodable) +import AnyCodable +#endif + +open class StoreAPI { + + /** + Delete purchase order by ID + DELETE /store/order/{order_id} + For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + - parameter orderId: (path) ID of the order that needs to be deleted + - returns: `EventLoopFuture` of `ClientResponse` + */ + open class func deleteOrderRaw(orderId: String, headers: HTTPHeaders = PetstoreClient.customHeaders, beforeSend: (inout ClientRequest) throws -> () = { _ in }) -> EventLoopFuture { + var localVariablePath = "/store/order/{order_id}" + let orderIdPreEscape = String(describing: orderId) + let orderIdPostEscape = orderIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + localVariablePath = localVariablePath.replacingOccurrences(of: "{order_id}", with: orderIdPostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClient.basePath + localVariablePath + + guard let localVariableApiClient = Configuration.apiClient else { + fatalError("Configuration.apiClient is not set.") + } + + return localVariableApiClient.send(.DELETE, headers: headers, to: URI(string: localVariableURLString)) { localVariableRequest in + try Configuration.apiWrapper(&localVariableRequest) + + + + try beforeSend(&localVariableRequest) + } + } + + public enum DeleteOrder { + case http400(raw: ClientResponse) + case http404(raw: ClientResponse) + case http0(raw: ClientResponse) + } + + /** + Delete purchase order by ID + DELETE /store/order/{order_id} + For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + - parameter orderId: (path) ID of the order that needs to be deleted + - returns: `EventLoopFuture` of `DeleteOrder` + */ + open class func deleteOrder(orderId: String, headers: HTTPHeaders = PetstoreClient.customHeaders, beforeSend: (inout ClientRequest) throws -> () = { _ in }) -> EventLoopFuture { + return deleteOrderRaw(orderId: orderId, headers: headers, beforeSend: beforeSend).flatMapThrowing { response -> DeleteOrder in + switch response.status.code { + case 400: + return .http400(raw: response) + case 404: + return .http404(raw: response) + default: + return .http0(raw: response) + } + } + } + + + /** + Returns pet inventories by status + GET /store/inventory + Returns a map of status codes to quantities + - API Key: + - type: apiKey api_key + - name: api_key + - returns: `EventLoopFuture` of `ClientResponse` + */ + open class func getInventoryRaw(headers: HTTPHeaders = PetstoreClient.customHeaders, beforeSend: (inout ClientRequest) throws -> () = { _ in }) -> EventLoopFuture { + let localVariablePath = "/store/inventory" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + + guard let localVariableApiClient = Configuration.apiClient else { + fatalError("Configuration.apiClient is not set.") + } + + return localVariableApiClient.send(.GET, headers: headers, to: URI(string: localVariableURLString)) { localVariableRequest in + try Configuration.apiWrapper(&localVariableRequest) + + + + try beforeSend(&localVariableRequest) + } + } + + public enum GetInventory { + case http200(value: [String: Int], raw: ClientResponse) + case http0(raw: ClientResponse) + } + + /** + Returns pet inventories by status + GET /store/inventory + Returns a map of status codes to quantities + - API Key: + - type: apiKey api_key + - name: api_key + - returns: `EventLoopFuture` of `GetInventory` + */ + open class func getInventory(headers: HTTPHeaders = PetstoreClient.customHeaders, beforeSend: (inout ClientRequest) throws -> () = { _ in }) -> EventLoopFuture { + return getInventoryRaw(headers: headers, beforeSend: beforeSend).flatMapThrowing { response -> GetInventory in + switch response.status.code { + case 200: + return .http200(value: try response.content.decode([String: Int].self, using: Configuration.contentConfiguration.requireDecoder(for: [String: Int].defaultContentType)), raw: response) + default: + return .http0(raw: response) + } + } + } + + + /** + Find purchase order by ID + GET /store/order/{order_id} + For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + - parameter orderId: (path) ID of pet that needs to be fetched + - returns: `EventLoopFuture` of `ClientResponse` + */ + open class func getOrderByIdRaw(orderId: Int64, headers: HTTPHeaders = PetstoreClient.customHeaders, beforeSend: (inout ClientRequest) throws -> () = { _ in }) -> EventLoopFuture { + var localVariablePath = "/store/order/{order_id}" + let orderIdPreEscape = String(describing: orderId) + let orderIdPostEscape = orderIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + localVariablePath = localVariablePath.replacingOccurrences(of: "{order_id}", with: orderIdPostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClient.basePath + localVariablePath + + guard let localVariableApiClient = Configuration.apiClient else { + fatalError("Configuration.apiClient is not set.") + } + + return localVariableApiClient.send(.GET, headers: headers, to: URI(string: localVariableURLString)) { localVariableRequest in + try Configuration.apiWrapper(&localVariableRequest) + + + + try beforeSend(&localVariableRequest) + } + } + + public enum GetOrderById { + case http200(value: Order, raw: ClientResponse) + case http400(raw: ClientResponse) + case http404(raw: ClientResponse) + case http0(raw: ClientResponse) + } + + /** + Find purchase order by ID + GET /store/order/{order_id} + For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + - parameter orderId: (path) ID of pet that needs to be fetched + - returns: `EventLoopFuture` of `GetOrderById` + */ + open class func getOrderById(orderId: Int64, headers: HTTPHeaders = PetstoreClient.customHeaders, beforeSend: (inout ClientRequest) throws -> () = { _ in }) -> EventLoopFuture { + return getOrderByIdRaw(orderId: orderId, headers: headers, beforeSend: beforeSend).flatMapThrowing { response -> GetOrderById in + switch response.status.code { + case 200: + return .http200(value: try response.content.decode(Order.self, using: Configuration.contentConfiguration.requireDecoder(for: Order.defaultContentType)), raw: response) + case 400: + return .http400(raw: response) + case 404: + return .http404(raw: response) + default: + return .http0(raw: response) + } + } + } + + + /** + Place an order for a pet + POST /store/order + - parameter body: (body) order placed for purchasing the pet + - returns: `EventLoopFuture` of `ClientResponse` + */ + open class func placeOrderRaw(body: Order, headers: HTTPHeaders = PetstoreClient.customHeaders, beforeSend: (inout ClientRequest) throws -> () = { _ in }) -> EventLoopFuture { + let localVariablePath = "/store/order" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + + guard let localVariableApiClient = Configuration.apiClient else { + fatalError("Configuration.apiClient is not set.") + } + + return localVariableApiClient.send(.POST, headers: headers, to: URI(string: localVariableURLString)) { localVariableRequest in + try Configuration.apiWrapper(&localVariableRequest) + + + try localVariableRequest.content.encode(body, using: Configuration.contentConfiguration.requireEncoder(for: Order.defaultContentType)) + + try beforeSend(&localVariableRequest) + } + } + + public enum PlaceOrder { + case http200(value: Order, raw: ClientResponse) + case http400(raw: ClientResponse) + case http0(raw: ClientResponse) + } + + /** + Place an order for a pet + POST /store/order + - parameter body: (body) order placed for purchasing the pet + - returns: `EventLoopFuture` of `PlaceOrder` + */ + open class func placeOrder(body: Order, headers: HTTPHeaders = PetstoreClient.customHeaders, beforeSend: (inout ClientRequest) throws -> () = { _ in }) -> EventLoopFuture { + return placeOrderRaw(body: body, headers: headers, beforeSend: beforeSend).flatMapThrowing { response -> PlaceOrder in + switch response.status.code { + case 200: + return .http200(value: try response.content.decode(Order.self, using: Configuration.contentConfiguration.requireDecoder(for: Order.defaultContentType)), raw: response) + case 400: + return .http400(raw: response) + default: + return .http0(raw: response) + } + } + } + +} diff --git a/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/APIs/UserAPI.swift b/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/APIs/UserAPI.swift new file mode 100644 index 00000000000..a0d83204e50 --- /dev/null +++ b/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/APIs/UserAPI.swift @@ -0,0 +1,413 @@ +// +// UserAPI.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +import Vapor +#if canImport(AnyCodable) +import AnyCodable +#endif + +open class UserAPI { + + /** + Create user + POST /user + This can only be done by the logged in user. + - parameter body: (body) Created user object + - returns: `EventLoopFuture` of `ClientResponse` + */ + open class func createUserRaw(body: User, headers: HTTPHeaders = PetstoreClient.customHeaders, beforeSend: (inout ClientRequest) throws -> () = { _ in }) -> EventLoopFuture { + let localVariablePath = "/user" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + + guard let localVariableApiClient = Configuration.apiClient else { + fatalError("Configuration.apiClient is not set.") + } + + return localVariableApiClient.send(.POST, headers: headers, to: URI(string: localVariableURLString)) { localVariableRequest in + try Configuration.apiWrapper(&localVariableRequest) + + + try localVariableRequest.content.encode(body, using: Configuration.contentConfiguration.requireEncoder(for: User.defaultContentType)) + + try beforeSend(&localVariableRequest) + } + } + + public enum CreateUser { + case http0(raw: ClientResponse) + } + + /** + Create user + POST /user + This can only be done by the logged in user. + - parameter body: (body) Created user object + - returns: `EventLoopFuture` of `CreateUser` + */ + open class func createUser(body: User, headers: HTTPHeaders = PetstoreClient.customHeaders, beforeSend: (inout ClientRequest) throws -> () = { _ in }) -> EventLoopFuture { + return createUserRaw(body: body, headers: headers, beforeSend: beforeSend).flatMapThrowing { response -> CreateUser in + switch response.status.code { + default: + return .http0(raw: response) + } + } + } + + + /** + Creates list of users with given input array + POST /user/createWithArray + - parameter body: (body) List of user object + - returns: `EventLoopFuture` of `ClientResponse` + */ + open class func createUsersWithArrayInputRaw(body: [User], headers: HTTPHeaders = PetstoreClient.customHeaders, beforeSend: (inout ClientRequest) throws -> () = { _ in }) -> EventLoopFuture { + let localVariablePath = "/user/createWithArray" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + + guard let localVariableApiClient = Configuration.apiClient else { + fatalError("Configuration.apiClient is not set.") + } + + return localVariableApiClient.send(.POST, headers: headers, to: URI(string: localVariableURLString)) { localVariableRequest in + try Configuration.apiWrapper(&localVariableRequest) + + + try localVariableRequest.content.encode(body, using: Configuration.contentConfiguration.requireEncoder(for: [User].defaultContentType)) + + try beforeSend(&localVariableRequest) + } + } + + public enum CreateUsersWithArrayInput { + case http0(raw: ClientResponse) + } + + /** + Creates list of users with given input array + POST /user/createWithArray + - parameter body: (body) List of user object + - returns: `EventLoopFuture` of `CreateUsersWithArrayInput` + */ + open class func createUsersWithArrayInput(body: [User], headers: HTTPHeaders = PetstoreClient.customHeaders, beforeSend: (inout ClientRequest) throws -> () = { _ in }) -> EventLoopFuture { + return createUsersWithArrayInputRaw(body: body, headers: headers, beforeSend: beforeSend).flatMapThrowing { response -> CreateUsersWithArrayInput in + switch response.status.code { + default: + return .http0(raw: response) + } + } + } + + + /** + Creates list of users with given input array + POST /user/createWithList + - parameter body: (body) List of user object + - returns: `EventLoopFuture` of `ClientResponse` + */ + open class func createUsersWithListInputRaw(body: [User], headers: HTTPHeaders = PetstoreClient.customHeaders, beforeSend: (inout ClientRequest) throws -> () = { _ in }) -> EventLoopFuture { + let localVariablePath = "/user/createWithList" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + + guard let localVariableApiClient = Configuration.apiClient else { + fatalError("Configuration.apiClient is not set.") + } + + return localVariableApiClient.send(.POST, headers: headers, to: URI(string: localVariableURLString)) { localVariableRequest in + try Configuration.apiWrapper(&localVariableRequest) + + + try localVariableRequest.content.encode(body, using: Configuration.contentConfiguration.requireEncoder(for: [User].defaultContentType)) + + try beforeSend(&localVariableRequest) + } + } + + public enum CreateUsersWithListInput { + case http0(raw: ClientResponse) + } + + /** + Creates list of users with given input array + POST /user/createWithList + - parameter body: (body) List of user object + - returns: `EventLoopFuture` of `CreateUsersWithListInput` + */ + open class func createUsersWithListInput(body: [User], headers: HTTPHeaders = PetstoreClient.customHeaders, beforeSend: (inout ClientRequest) throws -> () = { _ in }) -> EventLoopFuture { + return createUsersWithListInputRaw(body: body, headers: headers, beforeSend: beforeSend).flatMapThrowing { response -> CreateUsersWithListInput in + switch response.status.code { + default: + return .http0(raw: response) + } + } + } + + + /** + Delete user + DELETE /user/{username} + This can only be done by the logged in user. + - parameter username: (path) The name that needs to be deleted + - returns: `EventLoopFuture` of `ClientResponse` + */ + open class func deleteUserRaw(username: String, headers: HTTPHeaders = PetstoreClient.customHeaders, beforeSend: (inout ClientRequest) throws -> () = { _ in }) -> EventLoopFuture { + var localVariablePath = "/user/{username}" + let usernamePreEscape = String(describing: username) + let usernamePostEscape = usernamePreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + localVariablePath = localVariablePath.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClient.basePath + localVariablePath + + guard let localVariableApiClient = Configuration.apiClient else { + fatalError("Configuration.apiClient is not set.") + } + + return localVariableApiClient.send(.DELETE, headers: headers, to: URI(string: localVariableURLString)) { localVariableRequest in + try Configuration.apiWrapper(&localVariableRequest) + + + + try beforeSend(&localVariableRequest) + } + } + + public enum DeleteUser { + case http400(raw: ClientResponse) + case http404(raw: ClientResponse) + case http0(raw: ClientResponse) + } + + /** + Delete user + DELETE /user/{username} + This can only be done by the logged in user. + - parameter username: (path) The name that needs to be deleted + - returns: `EventLoopFuture` of `DeleteUser` + */ + open class func deleteUser(username: String, headers: HTTPHeaders = PetstoreClient.customHeaders, beforeSend: (inout ClientRequest) throws -> () = { _ in }) -> EventLoopFuture { + return deleteUserRaw(username: username, headers: headers, beforeSend: beforeSend).flatMapThrowing { response -> DeleteUser in + switch response.status.code { + case 400: + return .http400(raw: response) + case 404: + return .http404(raw: response) + default: + return .http0(raw: response) + } + } + } + + + /** + Get user by user name + GET /user/{username} + - parameter username: (path) The name that needs to be fetched. Use user1 for testing. + - returns: `EventLoopFuture` of `ClientResponse` + */ + open class func getUserByNameRaw(username: String, headers: HTTPHeaders = PetstoreClient.customHeaders, beforeSend: (inout ClientRequest) throws -> () = { _ in }) -> EventLoopFuture { + var localVariablePath = "/user/{username}" + let usernamePreEscape = String(describing: username) + let usernamePostEscape = usernamePreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + localVariablePath = localVariablePath.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClient.basePath + localVariablePath + + guard let localVariableApiClient = Configuration.apiClient else { + fatalError("Configuration.apiClient is not set.") + } + + return localVariableApiClient.send(.GET, headers: headers, to: URI(string: localVariableURLString)) { localVariableRequest in + try Configuration.apiWrapper(&localVariableRequest) + + + + try beforeSend(&localVariableRequest) + } + } + + public enum GetUserByName { + case http200(value: User, raw: ClientResponse) + case http400(raw: ClientResponse) + case http404(raw: ClientResponse) + case http0(raw: ClientResponse) + } + + /** + Get user by user name + GET /user/{username} + - parameter username: (path) The name that needs to be fetched. Use user1 for testing. + - returns: `EventLoopFuture` of `GetUserByName` + */ + open class func getUserByName(username: String, headers: HTTPHeaders = PetstoreClient.customHeaders, beforeSend: (inout ClientRequest) throws -> () = { _ in }) -> EventLoopFuture { + return getUserByNameRaw(username: username, headers: headers, beforeSend: beforeSend).flatMapThrowing { response -> GetUserByName in + switch response.status.code { + case 200: + return .http200(value: try response.content.decode(User.self, using: Configuration.contentConfiguration.requireDecoder(for: User.defaultContentType)), raw: response) + case 400: + return .http400(raw: response) + case 404: + return .http404(raw: response) + default: + return .http0(raw: response) + } + } + } + + + /** + Logs user into the system + GET /user/login + - responseHeaders: [X-Rate-Limit(Int), X-Expires-After(Date)] + - parameter username: (query) The user name for login + - parameter password: (query) The password for login in clear text + - returns: `EventLoopFuture` of `ClientResponse` + */ + open class func loginUserRaw(username: String, password: String, headers: HTTPHeaders = PetstoreClient.customHeaders, beforeSend: (inout ClientRequest) throws -> () = { _ in }) -> EventLoopFuture { + let localVariablePath = "/user/login" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + + guard let localVariableApiClient = Configuration.apiClient else { + fatalError("Configuration.apiClient is not set.") + } + + return localVariableApiClient.send(.GET, headers: headers, to: URI(string: localVariableURLString)) { localVariableRequest in + try Configuration.apiWrapper(&localVariableRequest) + + struct QueryParams: Content { + var username: String + var password: String + } + try localVariableRequest.query.encode(QueryParams(username: username, password: password)) + + try beforeSend(&localVariableRequest) + } + } + + public enum LoginUser { + case http200(value: String, raw: ClientResponse) + case http400(raw: ClientResponse) + case http0(raw: ClientResponse) + } + + /** + Logs user into the system + GET /user/login + - responseHeaders: [X-Rate-Limit(Int), X-Expires-After(Date)] + - parameter username: (query) The user name for login + - parameter password: (query) The password for login in clear text + - returns: `EventLoopFuture` of `LoginUser` + */ + open class func loginUser(username: String, password: String, headers: HTTPHeaders = PetstoreClient.customHeaders, beforeSend: (inout ClientRequest) throws -> () = { _ in }) -> EventLoopFuture { + return loginUserRaw(username: username, password: password, headers: headers, beforeSend: beforeSend).flatMapThrowing { response -> LoginUser in + switch response.status.code { + case 200: + return .http200(value: try response.content.decode(String.self, using: Configuration.contentConfiguration.requireDecoder(for: String.defaultContentType)), raw: response) + case 400: + return .http400(raw: response) + default: + return .http0(raw: response) + } + } + } + + + /** + Logs out current logged in user session + GET /user/logout + - returns: `EventLoopFuture` of `ClientResponse` + */ + open class func logoutUserRaw(headers: HTTPHeaders = PetstoreClient.customHeaders, beforeSend: (inout ClientRequest) throws -> () = { _ in }) -> EventLoopFuture { + let localVariablePath = "/user/logout" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + + guard let localVariableApiClient = Configuration.apiClient else { + fatalError("Configuration.apiClient is not set.") + } + + return localVariableApiClient.send(.GET, headers: headers, to: URI(string: localVariableURLString)) { localVariableRequest in + try Configuration.apiWrapper(&localVariableRequest) + + + + try beforeSend(&localVariableRequest) + } + } + + public enum LogoutUser { + case http0(raw: ClientResponse) + } + + /** + Logs out current logged in user session + GET /user/logout + - returns: `EventLoopFuture` of `LogoutUser` + */ + open class func logoutUser(headers: HTTPHeaders = PetstoreClient.customHeaders, beforeSend: (inout ClientRequest) throws -> () = { _ in }) -> EventLoopFuture { + return logoutUserRaw(headers: headers, beforeSend: beforeSend).flatMapThrowing { response -> LogoutUser in + switch response.status.code { + default: + return .http0(raw: response) + } + } + } + + + /** + Updated user + PUT /user/{username} + This can only be done by the logged in user. + - parameter username: (path) name that need to be deleted + - parameter body: (body) Updated user object + - returns: `EventLoopFuture` of `ClientResponse` + */ + open class func updateUserRaw(username: String, body: User, headers: HTTPHeaders = PetstoreClient.customHeaders, beforeSend: (inout ClientRequest) throws -> () = { _ in }) -> EventLoopFuture { + var localVariablePath = "/user/{username}" + let usernamePreEscape = String(describing: username) + let usernamePostEscape = usernamePreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + localVariablePath = localVariablePath.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClient.basePath + localVariablePath + + guard let localVariableApiClient = Configuration.apiClient else { + fatalError("Configuration.apiClient is not set.") + } + + return localVariableApiClient.send(.PUT, headers: headers, to: URI(string: localVariableURLString)) { localVariableRequest in + try Configuration.apiWrapper(&localVariableRequest) + + + try localVariableRequest.content.encode(body, using: Configuration.contentConfiguration.requireEncoder(for: User.defaultContentType)) + + try beforeSend(&localVariableRequest) + } + } + + public enum UpdateUser { + case http400(raw: ClientResponse) + case http404(raw: ClientResponse) + case http0(raw: ClientResponse) + } + + /** + Updated user + PUT /user/{username} + This can only be done by the logged in user. + - parameter username: (path) name that need to be deleted + - parameter body: (body) Updated user object + - returns: `EventLoopFuture` of `UpdateUser` + */ + open class func updateUser(username: String, body: User, headers: HTTPHeaders = PetstoreClient.customHeaders, beforeSend: (inout ClientRequest) throws -> () = { _ in }) -> EventLoopFuture { + return updateUserRaw(username: username, body: body, headers: headers, beforeSend: beforeSend).flatMapThrowing { response -> UpdateUser in + switch response.status.code { + case 400: + return .http400(raw: response) + case 404: + return .http404(raw: response) + default: + return .http0(raw: response) + } + } + } + +} diff --git a/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Configuration.swift b/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Configuration.swift new file mode 100644 index 00000000000..db8707ad7a7 --- /dev/null +++ b/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Configuration.swift @@ -0,0 +1,14 @@ +// Configuration.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +import Vapor + +open class Configuration { + public static var apiClient: Vapor.Client? = nil + public static var apiWrapper: (inout Vapor.ClientRequest) throws -> () = { _ in } + public static var contentConfiguration = ContentConfiguration.default() +} diff --git a/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Extensions.swift b/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Extensions.swift new file mode 100644 index 00000000000..b212303ae1d --- /dev/null +++ b/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Extensions.swift @@ -0,0 +1,131 @@ +// Extensions.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif +import Vapor + +extension String: CodingKey { + + public var stringValue: String { + return self + } + + public init?(stringValue: String) { + self.init(stringLiteral: stringValue) + } + + public var intValue: Int? { + return nil + } + + public init?(intValue: Int) { + return nil + } + +} + +extension KeyedEncodingContainerProtocol { + + public mutating func encodeArray(_ values: [T], forKey key: Self.Key) throws where T: Encodable { + var arrayContainer = nestedUnkeyedContainer(forKey: key) + try arrayContainer.encode(contentsOf: values) + } + + public mutating func encodeArrayIfPresent(_ values: [T]?, forKey key: Self.Key) throws where T: Encodable { + if let values = values { + try encodeArray(values, forKey: key) + } + } + + public mutating func encodeMap(_ pairs: [Self.Key: T]) throws where T: Encodable { + for (key, value) in pairs { + try encode(value, forKey: key) + } + } + + public mutating func encodeMapIfPresent(_ pairs: [Self.Key: T]?) throws where T: Encodable { + if let pairs = pairs { + try encodeMap(pairs) + } + } + +} + +extension KeyedDecodingContainerProtocol { + + public func decodeArray(_ type: T.Type, forKey key: Self.Key) throws -> [T] where T: Decodable { + var tmpArray = [T]() + + var nestedContainer = try nestedUnkeyedContainer(forKey: key) + while !nestedContainer.isAtEnd { + let arrayValue = try nestedContainer.decode(T.self) + tmpArray.append(arrayValue) + } + + return tmpArray + } + + public func decodeArrayIfPresent(_ type: T.Type, forKey key: Self.Key) throws -> [T]? where T: Decodable { + var tmpArray: [T]? + + if contains(key) { + tmpArray = try decodeArray(T.self, forKey: key) + } + + return tmpArray + } + + public func decodeMap(_ type: T.Type, excludedKeys: Set) throws -> [Self.Key: T] where T: Decodable { + var map: [Self.Key: T] = [:] + + for key in allKeys { + if !excludedKeys.contains(key) { + let value = try decode(T.self, forKey: key) + map[key] = value + } + } + + return map + } + +} + +extension UUID: Content { } + +extension URL: Content { } + +extension Bool: Content { } + +extension Set: ResponseEncodable where Element: Content { + public func encodeResponse(for request: Vapor.Request) -> EventLoopFuture { + let response = Vapor.Response() + do { + try response.content.encode(Array(self)) + } catch { + return request.eventLoop.makeFailedFuture(error) + } + return request.eventLoop.makeSucceededFuture(response) + } +} + +extension Set: RequestDecodable where Element: Content { + public static func decodeRequest(_ request: Vapor.Request) -> EventLoopFuture { + do { + let content = try request.content.decode([Element].self) + return request.eventLoop.makeSucceededFuture(Set(content)) + } catch { + return request.eventLoop.makeFailedFuture(error) + } + } +} + +extension Set: Content where Element: Content { } + +extension AnyCodable: Content {} + diff --git a/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/AdditionalPropertiesAnyType.swift b/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/AdditionalPropertiesAnyType.swift new file mode 100644 index 00000000000..2f18010d237 --- /dev/null +++ b/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/AdditionalPropertiesAnyType.swift @@ -0,0 +1,72 @@ +// +// AdditionalPropertiesAnyType.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif +import Vapor + +public final class AdditionalPropertiesAnyType: Content, Hashable { + + public var name: String? + + public init(name: String? = nil) { + self.name = name + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case name + } + + public var additionalProperties: [String: AnyCodable] = [:] + + public subscript(key: String) -> AnyCodable? { + get { + if let value = additionalProperties[key] { + return value + } + return nil + } + + set { + additionalProperties[key] = newValue + } + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(name, forKey: .name) + var additionalPropertiesContainer = encoder.container(keyedBy: String.self) + try additionalPropertiesContainer.encodeMap(additionalProperties) + } + + // Decodable protocol methods + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + + name = try container.decodeIfPresent(String.self, forKey: .name) + var nonAdditionalPropertyKeys = Set() + nonAdditionalPropertyKeys.insert("name") + let additionalPropertiesContainer = try decoder.container(keyedBy: String.self) + additionalProperties = try additionalPropertiesContainer.decodeMap(AnyCodable.self, excludedKeys: nonAdditionalPropertyKeys) + } + + public static func == (lhs: AdditionalPropertiesAnyType, rhs: AdditionalPropertiesAnyType) -> Bool { + lhs.name == rhs.name + && lhs.additionalProperties == rhs.additionalProperties + } + + public func hash(into hasher: inout Hasher) { + hasher.combine(name?.hashValue) + hasher.combine(additionalProperties.hashValue) + } +} + diff --git a/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/AdditionalPropertiesArray.swift b/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/AdditionalPropertiesArray.swift new file mode 100644 index 00000000000..d590cb3a390 --- /dev/null +++ b/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/AdditionalPropertiesArray.swift @@ -0,0 +1,72 @@ +// +// AdditionalPropertiesArray.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif +import Vapor + +public final class AdditionalPropertiesArray: Content, Hashable { + + public var name: String? + + public init(name: String? = nil) { + self.name = name + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case name + } + + public var additionalProperties: [String: [AnyCodable]] = [:] + + public subscript(key: String) -> [AnyCodable]? { + get { + if let value = additionalProperties[key] { + return value + } + return nil + } + + set { + additionalProperties[key] = newValue + } + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(name, forKey: .name) + var additionalPropertiesContainer = encoder.container(keyedBy: String.self) + try additionalPropertiesContainer.encodeMap(additionalProperties) + } + + // Decodable protocol methods + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + + name = try container.decodeIfPresent(String.self, forKey: .name) + var nonAdditionalPropertyKeys = Set() + nonAdditionalPropertyKeys.insert("name") + let additionalPropertiesContainer = try decoder.container(keyedBy: String.self) + additionalProperties = try additionalPropertiesContainer.decodeMap([AnyCodable].self, excludedKeys: nonAdditionalPropertyKeys) + } + + public static func == (lhs: AdditionalPropertiesArray, rhs: AdditionalPropertiesArray) -> Bool { + lhs.name == rhs.name + && lhs.additionalProperties == rhs.additionalProperties + } + + public func hash(into hasher: inout Hasher) { + hasher.combine(name?.hashValue) + hasher.combine(additionalProperties.hashValue) + } +} + diff --git a/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/AdditionalPropertiesBoolean.swift b/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/AdditionalPropertiesBoolean.swift new file mode 100644 index 00000000000..8dc293a604e --- /dev/null +++ b/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/AdditionalPropertiesBoolean.swift @@ -0,0 +1,72 @@ +// +// AdditionalPropertiesBoolean.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif +import Vapor + +public final class AdditionalPropertiesBoolean: Content, Hashable { + + public var name: String? + + public init(name: String? = nil) { + self.name = name + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case name + } + + public var additionalProperties: [String: Bool] = [:] + + public subscript(key: String) -> Bool? { + get { + if let value = additionalProperties[key] { + return value + } + return nil + } + + set { + additionalProperties[key] = newValue + } + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(name, forKey: .name) + var additionalPropertiesContainer = encoder.container(keyedBy: String.self) + try additionalPropertiesContainer.encodeMap(additionalProperties) + } + + // Decodable protocol methods + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + + name = try container.decodeIfPresent(String.self, forKey: .name) + var nonAdditionalPropertyKeys = Set() + nonAdditionalPropertyKeys.insert("name") + let additionalPropertiesContainer = try decoder.container(keyedBy: String.self) + additionalProperties = try additionalPropertiesContainer.decodeMap(Bool.self, excludedKeys: nonAdditionalPropertyKeys) + } + + public static func == (lhs: AdditionalPropertiesBoolean, rhs: AdditionalPropertiesBoolean) -> Bool { + lhs.name == rhs.name + && lhs.additionalProperties == rhs.additionalProperties + } + + public func hash(into hasher: inout Hasher) { + hasher.combine(name?.hashValue) + hasher.combine(additionalProperties.hashValue) + } +} + diff --git a/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/AdditionalPropertiesClass.swift b/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/AdditionalPropertiesClass.swift new file mode 100644 index 00000000000..de9ef459a05 --- /dev/null +++ b/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/AdditionalPropertiesClass.swift @@ -0,0 +1,103 @@ +// +// AdditionalPropertiesClass.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif +import Vapor + +public final class AdditionalPropertiesClass: Content, Hashable { + + public var mapString: [String: String]? + public var mapNumber: [String: Double]? + public var mapInteger: [String: Int]? + public var mapBoolean: [String: Bool]? + public var mapArrayInteger: [String: [Int]]? + public var mapArrayAnytype: [String: [AnyCodable]]? + public var mapMapString: [String: [String: String]]? + public var mapMapAnytype: [String: [String: AnyCodable]]? + public var anytype1: AnyCodable? + public var anytype2: AnyCodable? + public var anytype3: AnyCodable? + + public init(mapString: [String: String]? = nil, mapNumber: [String: Double]? = nil, mapInteger: [String: Int]? = nil, mapBoolean: [String: Bool]? = nil, mapArrayInteger: [String: [Int]]? = nil, mapArrayAnytype: [String: [AnyCodable]]? = nil, mapMapString: [String: [String: String]]? = nil, mapMapAnytype: [String: [String: AnyCodable]]? = nil, anytype1: AnyCodable? = nil, anytype2: AnyCodable? = nil, anytype3: AnyCodable? = nil) { + self.mapString = mapString + self.mapNumber = mapNumber + self.mapInteger = mapInteger + self.mapBoolean = mapBoolean + self.mapArrayInteger = mapArrayInteger + self.mapArrayAnytype = mapArrayAnytype + self.mapMapString = mapMapString + self.mapMapAnytype = mapMapAnytype + self.anytype1 = anytype1 + self.anytype2 = anytype2 + self.anytype3 = anytype3 + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case mapString = "map_string" + case mapNumber = "map_number" + case mapInteger = "map_integer" + case mapBoolean = "map_boolean" + case mapArrayInteger = "map_array_integer" + case mapArrayAnytype = "map_array_anytype" + case mapMapString = "map_map_string" + case mapMapAnytype = "map_map_anytype" + case anytype1 = "anytype_1" + case anytype2 = "anytype_2" + case anytype3 = "anytype_3" + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(mapString, forKey: .mapString) + try container.encodeIfPresent(mapNumber, forKey: .mapNumber) + try container.encodeIfPresent(mapInteger, forKey: .mapInteger) + try container.encodeIfPresent(mapBoolean, forKey: .mapBoolean) + try container.encodeIfPresent(mapArrayInteger, forKey: .mapArrayInteger) + try container.encodeIfPresent(mapArrayAnytype, forKey: .mapArrayAnytype) + try container.encodeIfPresent(mapMapString, forKey: .mapMapString) + try container.encodeIfPresent(mapMapAnytype, forKey: .mapMapAnytype) + try container.encodeIfPresent(anytype1, forKey: .anytype1) + try container.encodeIfPresent(anytype2, forKey: .anytype2) + try container.encodeIfPresent(anytype3, forKey: .anytype3) + } + + public static func == (lhs: AdditionalPropertiesClass, rhs: AdditionalPropertiesClass) -> Bool { + lhs.mapString == rhs.mapString && + lhs.mapNumber == rhs.mapNumber && + lhs.mapInteger == rhs.mapInteger && + lhs.mapBoolean == rhs.mapBoolean && + lhs.mapArrayInteger == rhs.mapArrayInteger && + lhs.mapArrayAnytype == rhs.mapArrayAnytype && + lhs.mapMapString == rhs.mapMapString && + lhs.mapMapAnytype == rhs.mapMapAnytype && + lhs.anytype1 == rhs.anytype1 && + lhs.anytype2 == rhs.anytype2 && + lhs.anytype3 == rhs.anytype3 + + } + + public func hash(into hasher: inout Hasher) { + hasher.combine(mapString?.hashValue) + hasher.combine(mapNumber?.hashValue) + hasher.combine(mapInteger?.hashValue) + hasher.combine(mapBoolean?.hashValue) + hasher.combine(mapArrayInteger?.hashValue) + hasher.combine(mapArrayAnytype?.hashValue) + hasher.combine(mapMapString?.hashValue) + hasher.combine(mapMapAnytype?.hashValue) + hasher.combine(anytype1?.hashValue) + hasher.combine(anytype2?.hashValue) + hasher.combine(anytype3?.hashValue) + + } +} + diff --git a/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/AdditionalPropertiesInteger.swift b/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/AdditionalPropertiesInteger.swift new file mode 100644 index 00000000000..5a7c412958a --- /dev/null +++ b/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/AdditionalPropertiesInteger.swift @@ -0,0 +1,72 @@ +// +// AdditionalPropertiesInteger.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif +import Vapor + +public final class AdditionalPropertiesInteger: Content, Hashable { + + public var name: String? + + public init(name: String? = nil) { + self.name = name + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case name + } + + public var additionalProperties: [String: Int] = [:] + + public subscript(key: String) -> Int? { + get { + if let value = additionalProperties[key] { + return value + } + return nil + } + + set { + additionalProperties[key] = newValue + } + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(name, forKey: .name) + var additionalPropertiesContainer = encoder.container(keyedBy: String.self) + try additionalPropertiesContainer.encodeMap(additionalProperties) + } + + // Decodable protocol methods + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + + name = try container.decodeIfPresent(String.self, forKey: .name) + var nonAdditionalPropertyKeys = Set() + nonAdditionalPropertyKeys.insert("name") + let additionalPropertiesContainer = try decoder.container(keyedBy: String.self) + additionalProperties = try additionalPropertiesContainer.decodeMap(Int.self, excludedKeys: nonAdditionalPropertyKeys) + } + + public static func == (lhs: AdditionalPropertiesInteger, rhs: AdditionalPropertiesInteger) -> Bool { + lhs.name == rhs.name + && lhs.additionalProperties == rhs.additionalProperties + } + + public func hash(into hasher: inout Hasher) { + hasher.combine(name?.hashValue) + hasher.combine(additionalProperties.hashValue) + } +} + diff --git a/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/AdditionalPropertiesNumber.swift b/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/AdditionalPropertiesNumber.swift new file mode 100644 index 00000000000..259b29dae57 --- /dev/null +++ b/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/AdditionalPropertiesNumber.swift @@ -0,0 +1,72 @@ +// +// AdditionalPropertiesNumber.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif +import Vapor + +public final class AdditionalPropertiesNumber: Content, Hashable { + + public var name: String? + + public init(name: String? = nil) { + self.name = name + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case name + } + + public var additionalProperties: [String: Double] = [:] + + public subscript(key: String) -> Double? { + get { + if let value = additionalProperties[key] { + return value + } + return nil + } + + set { + additionalProperties[key] = newValue + } + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(name, forKey: .name) + var additionalPropertiesContainer = encoder.container(keyedBy: String.self) + try additionalPropertiesContainer.encodeMap(additionalProperties) + } + + // Decodable protocol methods + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + + name = try container.decodeIfPresent(String.self, forKey: .name) + var nonAdditionalPropertyKeys = Set() + nonAdditionalPropertyKeys.insert("name") + let additionalPropertiesContainer = try decoder.container(keyedBy: String.self) + additionalProperties = try additionalPropertiesContainer.decodeMap(Double.self, excludedKeys: nonAdditionalPropertyKeys) + } + + public static func == (lhs: AdditionalPropertiesNumber, rhs: AdditionalPropertiesNumber) -> Bool { + lhs.name == rhs.name + && lhs.additionalProperties == rhs.additionalProperties + } + + public func hash(into hasher: inout Hasher) { + hasher.combine(name?.hashValue) + hasher.combine(additionalProperties.hashValue) + } +} + diff --git a/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/AdditionalPropertiesObject.swift b/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/AdditionalPropertiesObject.swift new file mode 100644 index 00000000000..c8c0052c00c --- /dev/null +++ b/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/AdditionalPropertiesObject.swift @@ -0,0 +1,72 @@ +// +// AdditionalPropertiesObject.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif +import Vapor + +public final class AdditionalPropertiesObject: Content, Hashable { + + public var name: String? + + public init(name: String? = nil) { + self.name = name + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case name + } + + public var additionalProperties: [String: [String: AnyCodable]] = [:] + + public subscript(key: String) -> [String: AnyCodable]? { + get { + if let value = additionalProperties[key] { + return value + } + return nil + } + + set { + additionalProperties[key] = newValue + } + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(name, forKey: .name) + var additionalPropertiesContainer = encoder.container(keyedBy: String.self) + try additionalPropertiesContainer.encodeMap(additionalProperties) + } + + // Decodable protocol methods + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + + name = try container.decodeIfPresent(String.self, forKey: .name) + var nonAdditionalPropertyKeys = Set() + nonAdditionalPropertyKeys.insert("name") + let additionalPropertiesContainer = try decoder.container(keyedBy: String.self) + additionalProperties = try additionalPropertiesContainer.decodeMap([String: AnyCodable].self, excludedKeys: nonAdditionalPropertyKeys) + } + + public static func == (lhs: AdditionalPropertiesObject, rhs: AdditionalPropertiesObject) -> Bool { + lhs.name == rhs.name + && lhs.additionalProperties == rhs.additionalProperties + } + + public func hash(into hasher: inout Hasher) { + hasher.combine(name?.hashValue) + hasher.combine(additionalProperties.hashValue) + } +} + diff --git a/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/AdditionalPropertiesString.swift b/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/AdditionalPropertiesString.swift new file mode 100644 index 00000000000..13456e89d1b --- /dev/null +++ b/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/AdditionalPropertiesString.swift @@ -0,0 +1,72 @@ +// +// AdditionalPropertiesString.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif +import Vapor + +public final class AdditionalPropertiesString: Content, Hashable { + + public var name: String? + + public init(name: String? = nil) { + self.name = name + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case name + } + + public var additionalProperties: [String: String] = [:] + + public subscript(key: String) -> String? { + get { + if let value = additionalProperties[key] { + return value + } + return nil + } + + set { + additionalProperties[key] = newValue + } + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(name, forKey: .name) + var additionalPropertiesContainer = encoder.container(keyedBy: String.self) + try additionalPropertiesContainer.encodeMap(additionalProperties) + } + + // Decodable protocol methods + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + + name = try container.decodeIfPresent(String.self, forKey: .name) + var nonAdditionalPropertyKeys = Set() + nonAdditionalPropertyKeys.insert("name") + let additionalPropertiesContainer = try decoder.container(keyedBy: String.self) + additionalProperties = try additionalPropertiesContainer.decodeMap(String.self, excludedKeys: nonAdditionalPropertyKeys) + } + + public static func == (lhs: AdditionalPropertiesString, rhs: AdditionalPropertiesString) -> Bool { + lhs.name == rhs.name + && lhs.additionalProperties == rhs.additionalProperties + } + + public func hash(into hasher: inout Hasher) { + hasher.combine(name?.hashValue) + hasher.combine(additionalProperties.hashValue) + } +} + diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/Models/Animal.swift b/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/Animal.swift similarity index 91% rename from samples/client/petstore/swift5/urlsessionLibrary/Sources/Models/Animal.swift rename to samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/Animal.swift index 6bae9f2d0ec..344d5b13b1f 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/Sources/Models/Animal.swift +++ b/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/Animal.swift @@ -6,9 +6,12 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif +import Vapor -public final class Animal: Codable, Hashable { +public final class Animal: Content, Hashable { public var className: String public var color: String? = "red" @@ -17,6 +20,7 @@ public final class Animal: Codable, Hashable { self.className = className self.color = color } + public enum CodingKeys: String, CodingKey, CaseIterable { case className case color @@ -30,8 +34,6 @@ public final class Animal: Codable, Hashable { try container.encodeIfPresent(color, forKey: .color) } - - public static func == (lhs: Animal, rhs: Animal) -> Bool { lhs.className == rhs.className && lhs.color == rhs.color @@ -43,5 +45,5 @@ public final class Animal: Codable, Hashable { hasher.combine(color?.hashValue) } - } + diff --git a/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/AnimalFarm.swift b/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/AnimalFarm.swift new file mode 100644 index 00000000000..1b3a286f089 --- /dev/null +++ b/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/AnimalFarm.swift @@ -0,0 +1,14 @@ +// +// AnimalFarm.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif +import Vapor + +public typealias AnimalFarm = [Animal] diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/Models/ApiResponse.swift b/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/ApiResponse.swift similarity index 92% rename from samples/client/petstore/swift5/urlsessionLibrary/Sources/Models/ApiResponse.swift rename to samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/ApiResponse.swift index a0f3a24a8ee..4323130668e 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/Sources/Models/ApiResponse.swift +++ b/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/ApiResponse.swift @@ -6,9 +6,12 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif +import Vapor -public final class ApiResponse: Codable, Hashable { +public final class ApiResponse: Content, Hashable { public var code: Int? public var type: String? @@ -19,6 +22,7 @@ public final class ApiResponse: Codable, Hashable { self.type = type self.message = message } + public enum CodingKeys: String, CodingKey, CaseIterable { case code case type @@ -34,8 +38,6 @@ public final class ApiResponse: Codable, Hashable { try container.encodeIfPresent(message, forKey: .message) } - - public static func == (lhs: ApiResponse, rhs: ApiResponse) -> Bool { lhs.code == rhs.code && lhs.type == rhs.type && @@ -49,5 +51,5 @@ public final class ApiResponse: Codable, Hashable { hasher.combine(message?.hashValue) } - } + diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/Models/ArrayOfArrayOfNumberOnly.swift b/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/ArrayOfArrayOfNumberOnly.swift similarity index 89% rename from samples/client/petstore/swift5/urlsessionLibrary/Sources/Models/ArrayOfArrayOfNumberOnly.swift rename to samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/ArrayOfArrayOfNumberOnly.swift index b4b66b37be5..cd3669774bf 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/Sources/Models/ArrayOfArrayOfNumberOnly.swift +++ b/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/ArrayOfArrayOfNumberOnly.swift @@ -6,15 +6,19 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif +import Vapor -public final class ArrayOfArrayOfNumberOnly: Codable, Hashable { +public final class ArrayOfArrayOfNumberOnly: Content, Hashable { public var arrayArrayNumber: [[Double]]? public init(arrayArrayNumber: [[Double]]? = nil) { self.arrayArrayNumber = arrayArrayNumber } + public enum CodingKeys: String, CodingKey, CaseIterable { case arrayArrayNumber = "ArrayArrayNumber" } @@ -26,8 +30,6 @@ public final class ArrayOfArrayOfNumberOnly: Codable, Hashable { try container.encodeIfPresent(arrayArrayNumber, forKey: .arrayArrayNumber) } - - public static func == (lhs: ArrayOfArrayOfNumberOnly, rhs: ArrayOfArrayOfNumberOnly) -> Bool { lhs.arrayArrayNumber == rhs.arrayArrayNumber @@ -37,5 +39,5 @@ public final class ArrayOfArrayOfNumberOnly: Codable, Hashable { hasher.combine(arrayArrayNumber?.hashValue) } - } + diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/Models/ArrayOfNumberOnly.swift b/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/ArrayOfNumberOnly.swift similarity index 89% rename from samples/client/petstore/swift5/urlsessionLibrary/Sources/Models/ArrayOfNumberOnly.swift rename to samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/ArrayOfNumberOnly.swift index 1efbc2aa9e4..e222fdd2adb 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/Sources/Models/ArrayOfNumberOnly.swift +++ b/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/ArrayOfNumberOnly.swift @@ -6,15 +6,19 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif +import Vapor -public final class ArrayOfNumberOnly: Codable, Hashable { +public final class ArrayOfNumberOnly: Content, Hashable { public var arrayNumber: [Double]? public init(arrayNumber: [Double]? = nil) { self.arrayNumber = arrayNumber } + public enum CodingKeys: String, CodingKey, CaseIterable { case arrayNumber = "ArrayNumber" } @@ -26,8 +30,6 @@ public final class ArrayOfNumberOnly: Codable, Hashable { try container.encodeIfPresent(arrayNumber, forKey: .arrayNumber) } - - public static func == (lhs: ArrayOfNumberOnly, rhs: ArrayOfNumberOnly) -> Bool { lhs.arrayNumber == rhs.arrayNumber @@ -37,5 +39,5 @@ public final class ArrayOfNumberOnly: Codable, Hashable { hasher.combine(arrayNumber?.hashValue) } - } + diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/Models/ArrayTest.swift b/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/ArrayTest.swift similarity index 94% rename from samples/client/petstore/swift5/urlsessionLibrary/Sources/Models/ArrayTest.swift rename to samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/ArrayTest.swift index 6ca479263d3..87d4e0b8239 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/Sources/Models/ArrayTest.swift +++ b/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/ArrayTest.swift @@ -6,9 +6,12 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif +import Vapor -public final class ArrayTest: Codable, Hashable { +public final class ArrayTest: Content, Hashable { public var arrayOfString: [String]? public var arrayArrayOfInteger: [[Int64]]? @@ -19,6 +22,7 @@ public final class ArrayTest: Codable, Hashable { self.arrayArrayOfInteger = arrayArrayOfInteger self.arrayArrayOfModel = arrayArrayOfModel } + public enum CodingKeys: String, CodingKey, CaseIterable { case arrayOfString = "array_of_string" case arrayArrayOfInteger = "array_array_of_integer" @@ -34,8 +38,6 @@ public final class ArrayTest: Codable, Hashable { try container.encodeIfPresent(arrayArrayOfModel, forKey: .arrayArrayOfModel) } - - public static func == (lhs: ArrayTest, rhs: ArrayTest) -> Bool { lhs.arrayOfString == rhs.arrayOfString && lhs.arrayArrayOfInteger == rhs.arrayArrayOfInteger && @@ -49,5 +51,5 @@ public final class ArrayTest: Codable, Hashable { hasher.combine(arrayArrayOfModel?.hashValue) } - } + diff --git a/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/BigCat.swift b/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/BigCat.swift new file mode 100644 index 00000000000..f68dcec1d65 --- /dev/null +++ b/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/BigCat.swift @@ -0,0 +1,49 @@ +// +// BigCat.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif +import Vapor + +public final class BigCat: Content, Hashable { + + public enum Kind: String, Content, Hashable, CaseIterable { + case lions = "lions" + case tigers = "tigers" + case leopards = "leopards" + case jaguars = "jaguars" + } + public var kind: Kind? + + public init(kind: Kind? = nil) { + self.kind = kind + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case kind + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(kind, forKey: .kind) + } + + public static func == (lhs: BigCat, rhs: BigCat) -> Bool { + lhs.kind == rhs.kind + + } + + public func hash(into hasher: inout Hasher) { + hasher.combine(kind?.hashValue) + + } +} + diff --git a/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/BigCatAllOf.swift b/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/BigCatAllOf.swift new file mode 100644 index 00000000000..0945e87ed9c --- /dev/null +++ b/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/BigCatAllOf.swift @@ -0,0 +1,49 @@ +// +// BigCatAllOf.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif +import Vapor + +public final class BigCatAllOf: Content, Hashable { + + public enum Kind: String, Content, Hashable, CaseIterable { + case lions = "lions" + case tigers = "tigers" + case leopards = "leopards" + case jaguars = "jaguars" + } + public var kind: Kind? + + public init(kind: Kind? = nil) { + self.kind = kind + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case kind + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(kind, forKey: .kind) + } + + public static func == (lhs: BigCatAllOf, rhs: BigCatAllOf) -> Bool { + lhs.kind == rhs.kind + + } + + public func hash(into hasher: inout Hasher) { + hasher.combine(kind?.hashValue) + + } +} + diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/Models/Capitalization.swift b/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/Capitalization.swift similarity index 96% rename from samples/client/petstore/swift5/urlsessionLibrary/Sources/Models/Capitalization.swift rename to samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/Capitalization.swift index fd148a09d29..3cc1d9d4cf3 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/Sources/Models/Capitalization.swift +++ b/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/Capitalization.swift @@ -6,9 +6,12 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif +import Vapor -public final class Capitalization: Codable, Hashable { +public final class Capitalization: Content, Hashable { public var smallCamel: String? public var capitalCamel: String? @@ -26,6 +29,7 @@ public final class Capitalization: Codable, Hashable { self.sCAETHFlowPoints = sCAETHFlowPoints self.ATT_NAME = ATT_NAME } + public enum CodingKeys: String, CodingKey, CaseIterable { case smallCamel case capitalCamel = "CapitalCamel" @@ -47,8 +51,6 @@ public final class Capitalization: Codable, Hashable { try container.encodeIfPresent(ATT_NAME, forKey: .ATT_NAME) } - - public static func == (lhs: Capitalization, rhs: Capitalization) -> Bool { lhs.smallCamel == rhs.smallCamel && lhs.capitalCamel == rhs.capitalCamel && @@ -68,5 +70,5 @@ public final class Capitalization: Codable, Hashable { hasher.combine(ATT_NAME?.hashValue) } - } + diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/Models/Cat.swift b/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/Cat.swift similarity index 93% rename from samples/client/petstore/swift5/urlsessionLibrary/Sources/Models/Cat.swift rename to samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/Cat.swift index 54b81364f35..6c0d6f303c5 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/Sources/Models/Cat.swift +++ b/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/Cat.swift @@ -6,9 +6,12 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif +import Vapor -public final class Cat: Codable, Hashable { +public final class Cat: Content, Hashable { public var className: String public var color: String? = "red" @@ -19,6 +22,7 @@ public final class Cat: Codable, Hashable { self.color = color self.declawed = declawed } + public enum CodingKeys: String, CodingKey, CaseIterable { case className case color @@ -34,8 +38,6 @@ public final class Cat: Codable, Hashable { try container.encodeIfPresent(declawed, forKey: .declawed) } - - public static func == (lhs: Cat, rhs: Cat) -> Bool { lhs.className == rhs.className && lhs.color == rhs.color && @@ -49,5 +51,5 @@ public final class Cat: Codable, Hashable { hasher.combine(declawed?.hashValue) } - } + diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/Models/CatAllOf.swift b/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/CatAllOf.swift similarity index 89% rename from samples/client/petstore/swift5/urlsessionLibrary/Sources/Models/CatAllOf.swift rename to samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/CatAllOf.swift index 5074d59cb5d..2cfbd9fd02d 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/Sources/Models/CatAllOf.swift +++ b/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/CatAllOf.swift @@ -6,15 +6,19 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif +import Vapor -public final class CatAllOf: Codable, Hashable { +public final class CatAllOf: Content, Hashable { public var declawed: Bool? public init(declawed: Bool? = nil) { self.declawed = declawed } + public enum CodingKeys: String, CodingKey, CaseIterable { case declawed } @@ -26,8 +30,6 @@ public final class CatAllOf: Codable, Hashable { try container.encodeIfPresent(declawed, forKey: .declawed) } - - public static func == (lhs: CatAllOf, rhs: CatAllOf) -> Bool { lhs.declawed == rhs.declawed @@ -37,5 +39,5 @@ public final class CatAllOf: Codable, Hashable { hasher.combine(declawed?.hashValue) } - } + diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/Models/Category.swift b/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/Category.swift similarity index 80% rename from samples/client/petstore/swift5/urlsessionLibrary/Sources/Models/Category.swift rename to samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/Category.swift index 242fc578d45..ca2a487b438 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/Sources/Models/Category.swift +++ b/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/Category.swift @@ -6,17 +6,21 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif +import Vapor -public final class Category: Codable, Hashable { +public final class Category: Content, Hashable { public var id: Int64? - public var name: String? = "default-name" + public var name: String = "default-name" - public init(id: Int64? = nil, name: String? = "default-name") { + public init(id: Int64? = nil, name: String = "default-name") { self.id = id self.name = name } + public enum CodingKeys: String, CodingKey, CaseIterable { case id case name @@ -30,8 +34,6 @@ public final class Category: Codable, Hashable { try container.encode(name, forKey: .name) } - - public static func == (lhs: Category, rhs: Category) -> Bool { lhs.id == rhs.id && lhs.name == rhs.name @@ -43,5 +45,5 @@ public final class Category: Codable, Hashable { hasher.combine(name.hashValue) } - } + diff --git a/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/ClassModel.swift b/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/ClassModel.swift new file mode 100644 index 00000000000..a50bdf9ffd1 --- /dev/null +++ b/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/ClassModel.swift @@ -0,0 +1,44 @@ +// +// ClassModel.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif +import Vapor + +/** Model for testing model with \"_class\" property */ +public final class ClassModel: Content, Hashable { + + public var `class`: String? + + public init(`class`: String? = nil) { + self.`class` = `class` + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case `class` = "_class" + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(`class`, forKey: .`class`) + } + + public static func == (lhs: ClassModel, rhs: ClassModel) -> Bool { + lhs.`class` == rhs.`class` + + } + + public func hash(into hasher: inout Hasher) { + hasher.combine(`class`?.hashValue) + + } +} + diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/Models/Client.swift b/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/Client.swift similarity index 89% rename from samples/client/petstore/swift5/urlsessionLibrary/Sources/Models/Client.swift rename to samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/Client.swift index 323ab20082d..1ac630b90e9 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/Sources/Models/Client.swift +++ b/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/Client.swift @@ -6,15 +6,19 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif +import Vapor -public final class Client: Codable, Hashable { +public final class Client: Content, Hashable { public var client: String? public init(client: String? = nil) { self.client = client } + public enum CodingKeys: String, CodingKey, CaseIterable { case client } @@ -26,8 +30,6 @@ public final class Client: Codable, Hashable { try container.encodeIfPresent(client, forKey: .client) } - - public static func == (lhs: Client, rhs: Client) -> Bool { lhs.client == rhs.client @@ -37,5 +39,5 @@ public final class Client: Codable, Hashable { hasher.combine(client?.hashValue) } - } + diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/Models/Dog.swift b/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/Dog.swift similarity index 93% rename from samples/client/petstore/swift5/urlsessionLibrary/Sources/Models/Dog.swift rename to samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/Dog.swift index ec8a6748035..71a8002b754 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/Sources/Models/Dog.swift +++ b/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/Dog.swift @@ -6,9 +6,12 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif +import Vapor -public final class Dog: Codable, Hashable { +public final class Dog: Content, Hashable { public var className: String public var color: String? = "red" @@ -19,6 +22,7 @@ public final class Dog: Codable, Hashable { self.color = color self.breed = breed } + public enum CodingKeys: String, CodingKey, CaseIterable { case className case color @@ -34,8 +38,6 @@ public final class Dog: Codable, Hashable { try container.encodeIfPresent(breed, forKey: .breed) } - - public static func == (lhs: Dog, rhs: Dog) -> Bool { lhs.className == rhs.className && lhs.color == rhs.color && @@ -49,5 +51,5 @@ public final class Dog: Codable, Hashable { hasher.combine(breed?.hashValue) } - } + diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/Models/DogAllOf.swift b/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/DogAllOf.swift similarity index 89% rename from samples/client/petstore/swift5/urlsessionLibrary/Sources/Models/DogAllOf.swift rename to samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/DogAllOf.swift index 82d185f1a42..69352b02b13 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/Sources/Models/DogAllOf.swift +++ b/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/DogAllOf.swift @@ -6,15 +6,19 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif +import Vapor -public final class DogAllOf: Codable, Hashable { +public final class DogAllOf: Content, Hashable { public var breed: String? public init(breed: String? = nil) { self.breed = breed } + public enum CodingKeys: String, CodingKey, CaseIterable { case breed } @@ -26,8 +30,6 @@ public final class DogAllOf: Codable, Hashable { try container.encodeIfPresent(breed, forKey: .breed) } - - public static func == (lhs: DogAllOf, rhs: DogAllOf) -> Bool { lhs.breed == rhs.breed @@ -37,5 +39,5 @@ public final class DogAllOf: Codable, Hashable { hasher.combine(breed?.hashValue) } - } + diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/Models/EnumArrays.swift b/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/EnumArrays.swift similarity index 84% rename from samples/client/petstore/swift5/urlsessionLibrary/Sources/Models/EnumArrays.swift rename to samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/EnumArrays.swift index 573cb86e1ba..0b2b8c32844 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/Sources/Models/EnumArrays.swift +++ b/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/EnumArrays.swift @@ -6,15 +6,18 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif +import Vapor -public final class EnumArrays: Codable, Hashable { +public final class EnumArrays: Content, Hashable { - public enum JustSymbol: String, Codable, CaseIterable { + public enum JustSymbol: String, Content, Hashable, CaseIterable { case greaterThanOrEqualTo = ">=" case dollar = "$" } - public enum ArrayEnum: String, Codable, CaseIterable { + public enum ArrayEnum: String, Content, Hashable, CaseIterable { case fish = "fish" case crab = "crab" } @@ -25,6 +28,7 @@ public final class EnumArrays: Codable, Hashable { self.justSymbol = justSymbol self.arrayEnum = arrayEnum } + public enum CodingKeys: String, CodingKey, CaseIterable { case justSymbol = "just_symbol" case arrayEnum = "array_enum" @@ -38,8 +42,6 @@ public final class EnumArrays: Codable, Hashable { try container.encodeIfPresent(arrayEnum, forKey: .arrayEnum) } - - public static func == (lhs: EnumArrays, rhs: EnumArrays) -> Bool { lhs.justSymbol == rhs.justSymbol && lhs.arrayEnum == rhs.arrayEnum @@ -51,5 +53,5 @@ public final class EnumArrays: Codable, Hashable { hasher.combine(arrayEnum?.hashValue) } - } + diff --git a/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/EnumClass.swift b/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/EnumClass.swift new file mode 100644 index 00000000000..26c121d1543 --- /dev/null +++ b/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/EnumClass.swift @@ -0,0 +1,18 @@ +// +// EnumClass.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif +import Vapor + +public enum EnumClass: String, Content, Hashable, CaseIterable { + case abc = "_abc" + case efg = "-efg" + case xyz = "(xyz)" +} diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/Models/EnumTest.swift b/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/EnumTest.swift similarity index 86% rename from samples/client/petstore/swift5/urlsessionLibrary/Sources/Models/EnumTest.swift rename to samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/EnumTest.swift index ca04771171b..044d121b9f3 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/Sources/Models/EnumTest.swift +++ b/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/EnumTest.swift @@ -6,25 +6,28 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif +import Vapor -public final class EnumTest: Codable, Hashable { +public final class EnumTest: Content, Hashable { - public enum EnumString: String, Codable, CaseIterable { + public enum EnumString: String, Content, Hashable, CaseIterable { case upper = "UPPER" case lower = "lower" case empty = "" } - public enum EnumStringRequired: String, Codable, CaseIterable { + public enum EnumStringRequired: String, Content, Hashable, CaseIterable { case upper = "UPPER" case lower = "lower" case empty = "" } - public enum EnumInteger: Int, Codable, CaseIterable { + public enum EnumInteger: Int, Content, Hashable, CaseIterable { case _1 = 1 case number1 = -1 } - public enum EnumNumber: Double, Codable, CaseIterable { + public enum EnumNumber: Double, Content, Hashable, CaseIterable { case _11 = 1.1 case number12 = -1.2 } @@ -41,6 +44,7 @@ public final class EnumTest: Codable, Hashable { self.enumNumber = enumNumber self.outerEnum = outerEnum } + public enum CodingKeys: String, CodingKey, CaseIterable { case enumString = "enum_string" case enumStringRequired = "enum_string_required" @@ -60,8 +64,6 @@ public final class EnumTest: Codable, Hashable { try container.encodeIfPresent(outerEnum, forKey: .outerEnum) } - - public static func == (lhs: EnumTest, rhs: EnumTest) -> Bool { lhs.enumString == rhs.enumString && lhs.enumStringRequired == rhs.enumStringRequired && @@ -79,5 +81,5 @@ public final class EnumTest: Codable, Hashable { hasher.combine(outerEnum?.hashValue) } - } + diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/Models/File.swift b/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/File.swift similarity index 90% rename from samples/client/petstore/swift5/urlsessionLibrary/Sources/Models/File.swift rename to samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/File.swift index a899d021b87..d7505802943 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/Sources/Models/File.swift +++ b/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/File.swift @@ -6,10 +6,13 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif +import Vapor /** Must be named `File` for test. */ -public final class File: Codable, Hashable { +public final class File: Content, Hashable { /** Test capitalization */ public var sourceURI: String? @@ -17,6 +20,7 @@ public final class File: Codable, Hashable { public init(sourceURI: String? = nil) { self.sourceURI = sourceURI } + public enum CodingKeys: String, CodingKey, CaseIterable { case sourceURI } @@ -28,8 +32,6 @@ public final class File: Codable, Hashable { try container.encodeIfPresent(sourceURI, forKey: .sourceURI) } - - public static func == (lhs: File, rhs: File) -> Bool { lhs.sourceURI == rhs.sourceURI @@ -39,5 +41,5 @@ public final class File: Codable, Hashable { hasher.combine(sourceURI?.hashValue) } - } + diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/Models/FileSchemaTestClass.swift b/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/FileSchemaTestClass.swift similarity index 90% rename from samples/client/petstore/swift5/urlsessionLibrary/Sources/Models/FileSchemaTestClass.swift rename to samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/FileSchemaTestClass.swift index 2465bd5103f..c2426485fe6 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/Sources/Models/FileSchemaTestClass.swift +++ b/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/FileSchemaTestClass.swift @@ -6,9 +6,12 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif +import Vapor -public final class FileSchemaTestClass: Codable, Hashable { +public final class FileSchemaTestClass: Content, Hashable { public var file: File? public var files: [File]? @@ -17,6 +20,7 @@ public final class FileSchemaTestClass: Codable, Hashable { self.file = file self.files = files } + public enum CodingKeys: String, CodingKey, CaseIterable { case file case files @@ -30,8 +34,6 @@ public final class FileSchemaTestClass: Codable, Hashable { try container.encodeIfPresent(files, forKey: .files) } - - public static func == (lhs: FileSchemaTestClass, rhs: FileSchemaTestClass) -> Bool { lhs.file == rhs.file && lhs.files == rhs.files @@ -43,5 +45,5 @@ public final class FileSchemaTestClass: Codable, Hashable { hasher.combine(files?.hashValue) } - } + diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/Models/FormatTest.swift b/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/FormatTest.swift similarity index 84% rename from samples/client/petstore/swift5/urlsessionLibrary/Sources/Models/FormatTest.swift rename to samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/FormatTest.swift index 52c9d58241f..dfdf6ae588c 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/Sources/Models/FormatTest.swift +++ b/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/FormatTest.swift @@ -6,9 +6,12 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif +import Vapor -public final class FormatTest: Codable, Hashable { +public final class FormatTest: Content, Hashable { public var integer: Int? public var int32: Int? @@ -18,13 +21,14 @@ public final class FormatTest: Codable, Hashable { public var double: Double? public var string: String? public var byte: Data - public var binary: URL? + public var binary: Data? public var date: Date public var dateTime: Date? public var uuid: UUID? public var password: String + public var bigDecimal: Decimal? - public init(integer: Int? = nil, int32: Int? = nil, int64: Int64? = nil, number: Double, float: Float? = nil, double: Double? = nil, string: String? = nil, byte: Data, binary: URL? = nil, date: Date, dateTime: Date? = nil, uuid: UUID? = nil, password: String) { + public init(integer: Int? = nil, int32: Int? = nil, int64: Int64? = nil, number: Double, float: Float? = nil, double: Double? = nil, string: String? = nil, byte: Data, binary: Data? = nil, date: Date, dateTime: Date? = nil, uuid: UUID? = nil, password: String, bigDecimal: Decimal? = nil) { self.integer = integer self.int32 = int32 self.int64 = int64 @@ -38,7 +42,9 @@ public final class FormatTest: Codable, Hashable { self.dateTime = dateTime self.uuid = uuid self.password = password + self.bigDecimal = bigDecimal } + public enum CodingKeys: String, CodingKey, CaseIterable { case integer case int32 @@ -53,6 +59,7 @@ public final class FormatTest: Codable, Hashable { case dateTime case uuid case password + case bigDecimal = "BigDecimal" } // Encodable protocol methods @@ -72,10 +79,9 @@ public final class FormatTest: Codable, Hashable { try container.encodeIfPresent(dateTime, forKey: .dateTime) try container.encodeIfPresent(uuid, forKey: .uuid) try container.encode(password, forKey: .password) + try container.encodeIfPresent(bigDecimal, forKey: .bigDecimal) } - - public static func == (lhs: FormatTest, rhs: FormatTest) -> Bool { lhs.integer == rhs.integer && lhs.int32 == rhs.int32 && @@ -89,7 +95,8 @@ public final class FormatTest: Codable, Hashable { lhs.date == rhs.date && lhs.dateTime == rhs.dateTime && lhs.uuid == rhs.uuid && - lhs.password == rhs.password + lhs.password == rhs.password && + lhs.bigDecimal == rhs.bigDecimal } @@ -107,7 +114,8 @@ public final class FormatTest: Codable, Hashable { hasher.combine(dateTime?.hashValue) hasher.combine(uuid?.hashValue) hasher.combine(password.hashValue) + hasher.combine(bigDecimal?.hashValue) } - } + diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/Models/HasOnlyReadOnly.swift b/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/HasOnlyReadOnly.swift similarity index 90% rename from samples/client/petstore/swift5/urlsessionLibrary/Sources/Models/HasOnlyReadOnly.swift rename to samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/HasOnlyReadOnly.swift index 4044065d4f8..fd0e1532b04 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/Sources/Models/HasOnlyReadOnly.swift +++ b/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/HasOnlyReadOnly.swift @@ -6,9 +6,12 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif +import Vapor -public final class HasOnlyReadOnly: Codable, Hashable { +public final class HasOnlyReadOnly: Content, Hashable { public var bar: String? public var foo: String? @@ -17,6 +20,7 @@ public final class HasOnlyReadOnly: Codable, Hashable { self.bar = bar self.foo = foo } + public enum CodingKeys: String, CodingKey, CaseIterable { case bar case foo @@ -30,8 +34,6 @@ public final class HasOnlyReadOnly: Codable, Hashable { try container.encodeIfPresent(foo, forKey: .foo) } - - public static func == (lhs: HasOnlyReadOnly, rhs: HasOnlyReadOnly) -> Bool { lhs.bar == rhs.bar && lhs.foo == rhs.foo @@ -43,5 +45,5 @@ public final class HasOnlyReadOnly: Codable, Hashable { hasher.combine(foo?.hashValue) } - } + diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/Models/List.swift b/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/List.swift similarity index 89% rename from samples/client/petstore/swift5/urlsessionLibrary/Sources/Models/List.swift rename to samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/List.swift index c2457325b5b..fd15761ab8a 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/Sources/Models/List.swift +++ b/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/List.swift @@ -6,15 +6,19 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif +import Vapor -public final class List: Codable, Hashable { +public final class List: Content, Hashable { public var _123list: String? public init(_123list: String? = nil) { self._123list = _123list } + public enum CodingKeys: String, CodingKey, CaseIterable { case _123list = "123-list" } @@ -26,8 +30,6 @@ public final class List: Codable, Hashable { try container.encodeIfPresent(_123list, forKey: ._123list) } - - public static func == (lhs: List, rhs: List) -> Bool { lhs._123list == rhs._123list @@ -37,5 +39,5 @@ public final class List: Codable, Hashable { hasher.combine(_123list?.hashValue) } - } + diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/Models/MapTest.swift b/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/MapTest.swift similarity index 92% rename from samples/client/petstore/swift5/urlsessionLibrary/Sources/Models/MapTest.swift rename to samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/MapTest.swift index 83a6f77e76e..2726af8cb65 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/Sources/Models/MapTest.swift +++ b/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/MapTest.swift @@ -6,11 +6,14 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif +import Vapor -public final class MapTest: Codable, Hashable { +public final class MapTest: Content, Hashable { - public enum MapOfEnumString: String, Codable, CaseIterable { + public enum MapOfEnumString: String, Content, Hashable, CaseIterable { case upper = "UPPER" case lower = "lower" } @@ -25,6 +28,7 @@ public final class MapTest: Codable, Hashable { self.directMap = directMap self.indirectMap = indirectMap } + public enum CodingKeys: String, CodingKey, CaseIterable { case mapMapOfString = "map_map_of_string" case mapOfEnumString = "map_of_enum_string" @@ -42,8 +46,6 @@ public final class MapTest: Codable, Hashable { try container.encodeIfPresent(indirectMap, forKey: .indirectMap) } - - public static func == (lhs: MapTest, rhs: MapTest) -> Bool { lhs.mapMapOfString == rhs.mapMapOfString && lhs.mapOfEnumString == rhs.mapOfEnumString && @@ -59,5 +61,5 @@ public final class MapTest: Codable, Hashable { hasher.combine(indirectMap?.hashValue) } - } + diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/Models/MixedPropertiesAndAdditionalPropertiesClass.swift b/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/MixedPropertiesAndAdditionalPropertiesClass.swift similarity index 95% rename from samples/client/petstore/swift5/urlsessionLibrary/Sources/Models/MixedPropertiesAndAdditionalPropertiesClass.swift rename to samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/MixedPropertiesAndAdditionalPropertiesClass.swift index 08222b23f5c..a98efe737a2 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/Sources/Models/MixedPropertiesAndAdditionalPropertiesClass.swift +++ b/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/MixedPropertiesAndAdditionalPropertiesClass.swift @@ -6,9 +6,12 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif +import Vapor -public final class MixedPropertiesAndAdditionalPropertiesClass: Codable, Hashable { +public final class MixedPropertiesAndAdditionalPropertiesClass: Content, Hashable { public var uuid: UUID? public var dateTime: Date? @@ -19,6 +22,7 @@ public final class MixedPropertiesAndAdditionalPropertiesClass: Codable, Hashabl self.dateTime = dateTime self.map = map } + public enum CodingKeys: String, CodingKey, CaseIterable { case uuid case dateTime @@ -34,8 +38,6 @@ public final class MixedPropertiesAndAdditionalPropertiesClass: Codable, Hashabl try container.encodeIfPresent(map, forKey: .map) } - - public static func == (lhs: MixedPropertiesAndAdditionalPropertiesClass, rhs: MixedPropertiesAndAdditionalPropertiesClass) -> Bool { lhs.uuid == rhs.uuid && lhs.dateTime == rhs.dateTime && @@ -49,5 +51,5 @@ public final class MixedPropertiesAndAdditionalPropertiesClass: Codable, Hashabl hasher.combine(map?.hashValue) } - } + diff --git a/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/Model200Response.swift b/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/Model200Response.swift new file mode 100644 index 00000000000..1c9c6154700 --- /dev/null +++ b/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/Model200Response.swift @@ -0,0 +1,50 @@ +// +// Model200Response.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif +import Vapor + +/** Model for testing model name starting with number */ +public final class Model200Response: Content, Hashable { + + public var name: Int? + public var `class`: String? + + public init(name: Int? = nil, `class`: String? = nil) { + self.name = name + self.`class` = `class` + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case name + case `class` = "class" + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(name, forKey: .name) + try container.encodeIfPresent(`class`, forKey: .`class`) + } + + public static func == (lhs: Model200Response, rhs: Model200Response) -> Bool { + lhs.name == rhs.name && + lhs.`class` == rhs.`class` + + } + + public func hash(into hasher: inout Hasher) { + hasher.combine(name?.hashValue) + hasher.combine(`class`?.hashValue) + + } +} + diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/Models/Name.swift b/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/Name.swift similarity index 94% rename from samples/client/petstore/swift5/urlsessionLibrary/Sources/Models/Name.swift rename to samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/Name.swift index 533e5f2aea3..86a8d6bbe83 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/Sources/Models/Name.swift +++ b/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/Name.swift @@ -6,10 +6,13 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif +import Vapor /** Model for testing model name same as property name */ -public final class Name: Codable, Hashable { +public final class Name: Content, Hashable { public var name: Int public var snakeCase: Int? @@ -22,6 +25,7 @@ public final class Name: Codable, Hashable { self.property = property self._123number = _123number } + public enum CodingKeys: String, CodingKey, CaseIterable { case name case snakeCase = "snake_case" @@ -39,8 +43,6 @@ public final class Name: Codable, Hashable { try container.encodeIfPresent(_123number, forKey: ._123number) } - - public static func == (lhs: Name, rhs: Name) -> Bool { lhs.name == rhs.name && lhs.snakeCase == rhs.snakeCase && @@ -56,5 +58,5 @@ public final class Name: Codable, Hashable { hasher.combine(_123number?.hashValue) } - } + diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/Models/NumberOnly.swift b/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/NumberOnly.swift similarity index 89% rename from samples/client/petstore/swift5/urlsessionLibrary/Sources/Models/NumberOnly.swift rename to samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/NumberOnly.swift index be9925066ce..b88d51e3b12 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/Sources/Models/NumberOnly.swift +++ b/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/NumberOnly.swift @@ -6,15 +6,19 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif +import Vapor -public final class NumberOnly: Codable, Hashable { +public final class NumberOnly: Content, Hashable { public var justNumber: Double? public init(justNumber: Double? = nil) { self.justNumber = justNumber } + public enum CodingKeys: String, CodingKey, CaseIterable { case justNumber = "JustNumber" } @@ -26,8 +30,6 @@ public final class NumberOnly: Codable, Hashable { try container.encodeIfPresent(justNumber, forKey: .justNumber) } - - public static func == (lhs: NumberOnly, rhs: NumberOnly) -> Bool { lhs.justNumber == rhs.justNumber @@ -37,5 +39,5 @@ public final class NumberOnly: Codable, Hashable { hasher.combine(justNumber?.hashValue) } - } + diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/Models/Order.swift b/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/Order.swift similarity index 93% rename from samples/client/petstore/swift5/urlsessionLibrary/Sources/Models/Order.swift rename to samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/Order.swift index cfce5645a20..7a7b357cd46 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/Sources/Models/Order.swift +++ b/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/Order.swift @@ -6,11 +6,14 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif +import Vapor -public final class Order: Codable, Hashable { +public final class Order: Content, Hashable { - public enum Status: String, Codable, CaseIterable { + public enum Status: String, Content, Hashable, CaseIterable { case placed = "placed" case approved = "approved" case delivered = "delivered" @@ -31,6 +34,7 @@ public final class Order: Codable, Hashable { self.status = status self.complete = complete } + public enum CodingKeys: String, CodingKey, CaseIterable { case id case petId @@ -52,8 +56,6 @@ public final class Order: Codable, Hashable { try container.encodeIfPresent(complete, forKey: .complete) } - - public static func == (lhs: Order, rhs: Order) -> Bool { lhs.id == rhs.id && lhs.petId == rhs.petId && @@ -73,5 +75,5 @@ public final class Order: Codable, Hashable { hasher.combine(complete?.hashValue) } - } + diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/Models/OuterComposite.swift b/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/OuterComposite.swift similarity index 93% rename from samples/client/petstore/swift5/urlsessionLibrary/Sources/Models/OuterComposite.swift rename to samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/OuterComposite.swift index d238c4c13dd..7fd8d9254a6 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/Sources/Models/OuterComposite.swift +++ b/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/OuterComposite.swift @@ -6,9 +6,12 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif +import Vapor -public final class OuterComposite: Codable, Hashable { +public final class OuterComposite: Content, Hashable { public var myNumber: Double? public var myString: String? @@ -19,6 +22,7 @@ public final class OuterComposite: Codable, Hashable { self.myString = myString self.myBoolean = myBoolean } + public enum CodingKeys: String, CodingKey, CaseIterable { case myNumber = "my_number" case myString = "my_string" @@ -34,8 +38,6 @@ public final class OuterComposite: Codable, Hashable { try container.encodeIfPresent(myBoolean, forKey: .myBoolean) } - - public static func == (lhs: OuterComposite, rhs: OuterComposite) -> Bool { lhs.myNumber == rhs.myNumber && lhs.myString == rhs.myString && @@ -49,5 +51,5 @@ public final class OuterComposite: Codable, Hashable { hasher.combine(myBoolean?.hashValue) } - } + diff --git a/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/OuterEnum.swift b/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/OuterEnum.swift new file mode 100644 index 00000000000..3ea0e73af37 --- /dev/null +++ b/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/OuterEnum.swift @@ -0,0 +1,18 @@ +// +// OuterEnum.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif +import Vapor + +public enum OuterEnum: String, Content, Hashable, CaseIterable { + case placed = "placed" + case approved = "approved" + case delivered = "delivered" +} diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/Models/Pet.swift b/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/Pet.swift similarity index 87% rename from samples/client/petstore/swift5/urlsessionLibrary/Sources/Models/Pet.swift rename to samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/Pet.swift index c036d6d0cfb..90481c91ece 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/Sources/Models/Pet.swift +++ b/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/Pet.swift @@ -6,11 +6,14 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif +import Vapor -public final class Pet: Codable, Hashable { +public final class Pet: Content, Hashable { - public enum Status: String, Codable, CaseIterable { + public enum Status: String, Content, Hashable, CaseIterable { case available = "available" case pending = "pending" case sold = "sold" @@ -18,12 +21,12 @@ public final class Pet: Codable, Hashable { public var id: Int64? public var category: Category? public var name: String - public var photoUrls: [String] + public var photoUrls: Set public var tags: [Tag]? /** pet status in the store */ public var status: Status? - public init(id: Int64? = nil, category: Category? = nil, name: String, photoUrls: [String], tags: [Tag]? = nil, status: Status? = nil) { + public init(id: Int64? = nil, category: Category? = nil, name: String, photoUrls: Set, tags: [Tag]? = nil, status: Status? = nil) { self.id = id self.category = category self.name = name @@ -31,6 +34,7 @@ public final class Pet: Codable, Hashable { self.tags = tags self.status = status } + public enum CodingKeys: String, CodingKey, CaseIterable { case id case category @@ -52,8 +56,6 @@ public final class Pet: Codable, Hashable { try container.encodeIfPresent(status, forKey: .status) } - - public static func == (lhs: Pet, rhs: Pet) -> Bool { lhs.id == rhs.id && lhs.category == rhs.category && @@ -73,5 +75,5 @@ public final class Pet: Codable, Hashable { hasher.combine(status?.hashValue) } - } + diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/Models/ReadOnlyFirst.swift b/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/ReadOnlyFirst.swift similarity index 90% rename from samples/client/petstore/swift5/urlsessionLibrary/Sources/Models/ReadOnlyFirst.swift rename to samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/ReadOnlyFirst.swift index 1e2cdb966f2..05402ceb4d7 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/Sources/Models/ReadOnlyFirst.swift +++ b/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/ReadOnlyFirst.swift @@ -6,9 +6,12 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif +import Vapor -public final class ReadOnlyFirst: Codable, Hashable { +public final class ReadOnlyFirst: Content, Hashable { public var bar: String? public var baz: String? @@ -17,6 +20,7 @@ public final class ReadOnlyFirst: Codable, Hashable { self.bar = bar self.baz = baz } + public enum CodingKeys: String, CodingKey, CaseIterable { case bar case baz @@ -30,8 +34,6 @@ public final class ReadOnlyFirst: Codable, Hashable { try container.encodeIfPresent(baz, forKey: .baz) } - - public static func == (lhs: ReadOnlyFirst, rhs: ReadOnlyFirst) -> Bool { lhs.bar == rhs.bar && lhs.baz == rhs.baz @@ -43,5 +45,5 @@ public final class ReadOnlyFirst: Codable, Hashable { hasher.combine(baz?.hashValue) } - } + diff --git a/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/Return.swift b/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/Return.swift new file mode 100644 index 00000000000..05e4d06219a --- /dev/null +++ b/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/Return.swift @@ -0,0 +1,44 @@ +// +// Return.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif +import Vapor + +/** Model for testing reserved words */ +public final class Return: Content, Hashable { + + public var `return`: Int? + + public init(`return`: Int? = nil) { + self.`return` = `return` + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case `return` = "return" + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(`return`, forKey: .`return`) + } + + public static func == (lhs: Return, rhs: Return) -> Bool { + lhs.`return` == rhs.`return` + + } + + public func hash(into hasher: inout Hasher) { + hasher.combine(`return`?.hashValue) + + } +} + diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/Models/SpecialModelName.swift b/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/SpecialModelName.swift similarity index 90% rename from samples/client/petstore/swift5/urlsessionLibrary/Sources/Models/SpecialModelName.swift rename to samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/SpecialModelName.swift index 3fd24733174..8ad4aa608ea 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/Sources/Models/SpecialModelName.swift +++ b/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/SpecialModelName.swift @@ -6,15 +6,19 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif +import Vapor -public final class SpecialModelName: Codable, Hashable { +public final class SpecialModelName: Content, Hashable { public var specialPropertyName: Int64? public init(specialPropertyName: Int64? = nil) { self.specialPropertyName = specialPropertyName } + public enum CodingKeys: String, CodingKey, CaseIterable { case specialPropertyName = "$special[property.name]" } @@ -26,8 +30,6 @@ public final class SpecialModelName: Codable, Hashable { try container.encodeIfPresent(specialPropertyName, forKey: .specialPropertyName) } - - public static func == (lhs: SpecialModelName, rhs: SpecialModelName) -> Bool { lhs.specialPropertyName == rhs.specialPropertyName @@ -37,5 +39,5 @@ public final class SpecialModelName: Codable, Hashable { hasher.combine(specialPropertyName?.hashValue) } - } + diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/Models/StringBooleanMap.swift b/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/StringBooleanMap.swift similarity index 76% rename from samples/client/petstore/swift5/urlsessionLibrary/Sources/Models/StringBooleanMap.swift rename to samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/StringBooleanMap.swift index 9e90edf7be9..59d76476f8b 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/Sources/Models/StringBooleanMap.swift +++ b/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/StringBooleanMap.swift @@ -6,12 +6,17 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif +import Vapor + +public final class StringBooleanMap: Content, Hashable { -public final class StringBooleanMap: Codable, Hashable { public enum CodingKeys: CodingKey, CaseIterable { } + public var additionalProperties: [String: Bool] = [:] public subscript(key: String) -> Bool? { @@ -38,13 +43,13 @@ public final class StringBooleanMap: Codable, Hashable { // Decodable protocol methods public init(from decoder: Decoder) throws { - let container = try decoder.container(keyedBy: String.self) + let container = try decoder.container(keyedBy: CodingKeys.self) var nonAdditionalPropertyKeys = Set() - additionalProperties = try container.decodeMap(Bool.self, excludedKeys: nonAdditionalPropertyKeys) + let additionalPropertiesContainer = try decoder.container(keyedBy: String.self) + additionalProperties = try additionalPropertiesContainer.decodeMap(Bool.self, excludedKeys: nonAdditionalPropertyKeys) } - public static func == (lhs: StringBooleanMap, rhs: StringBooleanMap) -> Bool { lhs.additionalProperties == rhs.additionalProperties } @@ -52,5 +57,5 @@ public final class StringBooleanMap: Codable, Hashable { public func hash(into hasher: inout Hasher) { hasher.combine(additionalProperties.hashValue) } - } + diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/Models/Tag.swift b/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/Tag.swift similarity index 91% rename from samples/client/petstore/swift5/urlsessionLibrary/Sources/Models/Tag.swift rename to samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/Tag.swift index b30b0f62ace..b6ec1244243 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/Sources/Models/Tag.swift +++ b/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/Tag.swift @@ -6,9 +6,12 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif +import Vapor -public final class Tag: Codable, Hashable { +public final class Tag: Content, Hashable { public var id: Int64? public var name: String? @@ -17,6 +20,7 @@ public final class Tag: Codable, Hashable { self.id = id self.name = name } + public enum CodingKeys: String, CodingKey, CaseIterable { case id case name @@ -30,8 +34,6 @@ public final class Tag: Codable, Hashable { try container.encodeIfPresent(name, forKey: .name) } - - public static func == (lhs: Tag, rhs: Tag) -> Bool { lhs.id == rhs.id && lhs.name == rhs.name @@ -43,5 +45,5 @@ public final class Tag: Codable, Hashable { hasher.combine(name?.hashValue) } - } + diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/Models/TypeHolderDefault.swift b/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/TypeHolderDefault.swift similarity index 94% rename from samples/client/petstore/swift5/urlsessionLibrary/Sources/Models/TypeHolderDefault.swift rename to samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/TypeHolderDefault.swift index f99b86d1d64..f0d5c3ad313 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/Sources/Models/TypeHolderDefault.swift +++ b/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/TypeHolderDefault.swift @@ -6,9 +6,12 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif +import Vapor -public final class TypeHolderDefault: Codable, Hashable { +public final class TypeHolderDefault: Content, Hashable { public var stringItem: String = "what" public var numberItem: Double @@ -23,6 +26,7 @@ public final class TypeHolderDefault: Codable, Hashable { self.boolItem = boolItem self.arrayItem = arrayItem } + public enum CodingKeys: String, CodingKey, CaseIterable { case stringItem = "string_item" case numberItem = "number_item" @@ -42,8 +46,6 @@ public final class TypeHolderDefault: Codable, Hashable { try container.encode(arrayItem, forKey: .arrayItem) } - - public static func == (lhs: TypeHolderDefault, rhs: TypeHolderDefault) -> Bool { lhs.stringItem == rhs.stringItem && lhs.numberItem == rhs.numberItem && @@ -61,5 +63,5 @@ public final class TypeHolderDefault: Codable, Hashable { hasher.combine(arrayItem.hashValue) } - } + diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/Models/TypeHolderExample.swift b/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/TypeHolderExample.swift similarity index 79% rename from samples/client/petstore/swift5/urlsessionLibrary/Sources/Models/TypeHolderExample.swift rename to samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/TypeHolderExample.swift index d266ad2f0d1..cdefaad66d2 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/Sources/Models/TypeHolderExample.swift +++ b/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/TypeHolderExample.swift @@ -6,26 +6,33 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif +import Vapor -public final class TypeHolderExample: Codable, Hashable { +public final class TypeHolderExample: Content, Hashable { public var stringItem: String public var numberItem: Double + public var floatItem: Float public var integerItem: Int public var boolItem: Bool public var arrayItem: [Int] - public init(stringItem: String, numberItem: Double, integerItem: Int, boolItem: Bool, arrayItem: [Int]) { + public init(stringItem: String, numberItem: Double, floatItem: Float, integerItem: Int, boolItem: Bool, arrayItem: [Int]) { self.stringItem = stringItem self.numberItem = numberItem + self.floatItem = floatItem self.integerItem = integerItem self.boolItem = boolItem self.arrayItem = arrayItem } + public enum CodingKeys: String, CodingKey, CaseIterable { case stringItem = "string_item" case numberItem = "number_item" + case floatItem = "float_item" case integerItem = "integer_item" case boolItem = "bool_item" case arrayItem = "array_item" @@ -37,16 +44,16 @@ public final class TypeHolderExample: Codable, Hashable { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(stringItem, forKey: .stringItem) try container.encode(numberItem, forKey: .numberItem) + try container.encode(floatItem, forKey: .floatItem) try container.encode(integerItem, forKey: .integerItem) try container.encode(boolItem, forKey: .boolItem) try container.encode(arrayItem, forKey: .arrayItem) } - - public static func == (lhs: TypeHolderExample, rhs: TypeHolderExample) -> Bool { lhs.stringItem == rhs.stringItem && lhs.numberItem == rhs.numberItem && + lhs.floatItem == rhs.floatItem && lhs.integerItem == rhs.integerItem && lhs.boolItem == rhs.boolItem && lhs.arrayItem == rhs.arrayItem @@ -56,10 +63,11 @@ public final class TypeHolderExample: Codable, Hashable { public func hash(into hasher: inout Hasher) { hasher.combine(stringItem.hashValue) hasher.combine(numberItem.hashValue) + hasher.combine(floatItem.hashValue) hasher.combine(integerItem.hashValue) hasher.combine(boolItem.hashValue) hasher.combine(arrayItem.hashValue) } - } + diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/Models/User.swift b/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/User.swift similarity index 96% rename from samples/client/petstore/swift5/urlsessionLibrary/Sources/Models/User.swift rename to samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/User.swift index dcbecdf498d..47e3f6fbcb3 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/Sources/Models/User.swift +++ b/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/User.swift @@ -6,9 +6,12 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif +import Vapor -public final class User: Codable, Hashable { +public final class User: Content, Hashable { public var id: Int64? public var username: String? @@ -30,6 +33,7 @@ public final class User: Codable, Hashable { self.phone = phone self.userStatus = userStatus } + public enum CodingKeys: String, CodingKey, CaseIterable { case id case username @@ -55,8 +59,6 @@ public final class User: Codable, Hashable { try container.encodeIfPresent(userStatus, forKey: .userStatus) } - - public static func == (lhs: User, rhs: User) -> Bool { lhs.id == rhs.id && lhs.username == rhs.username && @@ -80,5 +82,5 @@ public final class User: Codable, Hashable { hasher.combine(userStatus?.hashValue) } - } + diff --git a/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/XmlItem.swift b/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/XmlItem.swift new file mode 100644 index 00000000000..85003560b37 --- /dev/null +++ b/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Models/XmlItem.swift @@ -0,0 +1,211 @@ +// +// XmlItem.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif +import Vapor + +public final class XmlItem: Content, Hashable { + + public var attributeString: String? + public var attributeNumber: Double? + public var attributeInteger: Int? + public var attributeBoolean: Bool? + public var wrappedArray: [Int]? + public var nameString: String? + public var nameNumber: Double? + public var nameInteger: Int? + public var nameBoolean: Bool? + public var nameArray: [Int]? + public var nameWrappedArray: [Int]? + public var prefixString: String? + public var prefixNumber: Double? + public var prefixInteger: Int? + public var prefixBoolean: Bool? + public var prefixArray: [Int]? + public var prefixWrappedArray: [Int]? + public var namespaceString: String? + public var namespaceNumber: Double? + public var namespaceInteger: Int? + public var namespaceBoolean: Bool? + public var namespaceArray: [Int]? + public var namespaceWrappedArray: [Int]? + public var prefixNsString: String? + public var prefixNsNumber: Double? + public var prefixNsInteger: Int? + public var prefixNsBoolean: Bool? + public var prefixNsArray: [Int]? + public var prefixNsWrappedArray: [Int]? + + public init(attributeString: String? = nil, attributeNumber: Double? = nil, attributeInteger: Int? = nil, attributeBoolean: Bool? = nil, wrappedArray: [Int]? = nil, nameString: String? = nil, nameNumber: Double? = nil, nameInteger: Int? = nil, nameBoolean: Bool? = nil, nameArray: [Int]? = nil, nameWrappedArray: [Int]? = nil, prefixString: String? = nil, prefixNumber: Double? = nil, prefixInteger: Int? = nil, prefixBoolean: Bool? = nil, prefixArray: [Int]? = nil, prefixWrappedArray: [Int]? = nil, namespaceString: String? = nil, namespaceNumber: Double? = nil, namespaceInteger: Int? = nil, namespaceBoolean: Bool? = nil, namespaceArray: [Int]? = nil, namespaceWrappedArray: [Int]? = nil, prefixNsString: String? = nil, prefixNsNumber: Double? = nil, prefixNsInteger: Int? = nil, prefixNsBoolean: Bool? = nil, prefixNsArray: [Int]? = nil, prefixNsWrappedArray: [Int]? = nil) { + self.attributeString = attributeString + self.attributeNumber = attributeNumber + self.attributeInteger = attributeInteger + self.attributeBoolean = attributeBoolean + self.wrappedArray = wrappedArray + self.nameString = nameString + self.nameNumber = nameNumber + self.nameInteger = nameInteger + self.nameBoolean = nameBoolean + self.nameArray = nameArray + self.nameWrappedArray = nameWrappedArray + self.prefixString = prefixString + self.prefixNumber = prefixNumber + self.prefixInteger = prefixInteger + self.prefixBoolean = prefixBoolean + self.prefixArray = prefixArray + self.prefixWrappedArray = prefixWrappedArray + self.namespaceString = namespaceString + self.namespaceNumber = namespaceNumber + self.namespaceInteger = namespaceInteger + self.namespaceBoolean = namespaceBoolean + self.namespaceArray = namespaceArray + self.namespaceWrappedArray = namespaceWrappedArray + self.prefixNsString = prefixNsString + self.prefixNsNumber = prefixNsNumber + self.prefixNsInteger = prefixNsInteger + self.prefixNsBoolean = prefixNsBoolean + self.prefixNsArray = prefixNsArray + self.prefixNsWrappedArray = prefixNsWrappedArray + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case attributeString = "attribute_string" + case attributeNumber = "attribute_number" + case attributeInteger = "attribute_integer" + case attributeBoolean = "attribute_boolean" + case wrappedArray = "wrapped_array" + case nameString = "name_string" + case nameNumber = "name_number" + case nameInteger = "name_integer" + case nameBoolean = "name_boolean" + case nameArray = "name_array" + case nameWrappedArray = "name_wrapped_array" + case prefixString = "prefix_string" + case prefixNumber = "prefix_number" + case prefixInteger = "prefix_integer" + case prefixBoolean = "prefix_boolean" + case prefixArray = "prefix_array" + case prefixWrappedArray = "prefix_wrapped_array" + case namespaceString = "namespace_string" + case namespaceNumber = "namespace_number" + case namespaceInteger = "namespace_integer" + case namespaceBoolean = "namespace_boolean" + case namespaceArray = "namespace_array" + case namespaceWrappedArray = "namespace_wrapped_array" + case prefixNsString = "prefix_ns_string" + case prefixNsNumber = "prefix_ns_number" + case prefixNsInteger = "prefix_ns_integer" + case prefixNsBoolean = "prefix_ns_boolean" + case prefixNsArray = "prefix_ns_array" + case prefixNsWrappedArray = "prefix_ns_wrapped_array" + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(attributeString, forKey: .attributeString) + try container.encodeIfPresent(attributeNumber, forKey: .attributeNumber) + try container.encodeIfPresent(attributeInteger, forKey: .attributeInteger) + try container.encodeIfPresent(attributeBoolean, forKey: .attributeBoolean) + try container.encodeIfPresent(wrappedArray, forKey: .wrappedArray) + try container.encodeIfPresent(nameString, forKey: .nameString) + try container.encodeIfPresent(nameNumber, forKey: .nameNumber) + try container.encodeIfPresent(nameInteger, forKey: .nameInteger) + try container.encodeIfPresent(nameBoolean, forKey: .nameBoolean) + try container.encodeIfPresent(nameArray, forKey: .nameArray) + try container.encodeIfPresent(nameWrappedArray, forKey: .nameWrappedArray) + try container.encodeIfPresent(prefixString, forKey: .prefixString) + try container.encodeIfPresent(prefixNumber, forKey: .prefixNumber) + try container.encodeIfPresent(prefixInteger, forKey: .prefixInteger) + try container.encodeIfPresent(prefixBoolean, forKey: .prefixBoolean) + try container.encodeIfPresent(prefixArray, forKey: .prefixArray) + try container.encodeIfPresent(prefixWrappedArray, forKey: .prefixWrappedArray) + try container.encodeIfPresent(namespaceString, forKey: .namespaceString) + try container.encodeIfPresent(namespaceNumber, forKey: .namespaceNumber) + try container.encodeIfPresent(namespaceInteger, forKey: .namespaceInteger) + try container.encodeIfPresent(namespaceBoolean, forKey: .namespaceBoolean) + try container.encodeIfPresent(namespaceArray, forKey: .namespaceArray) + try container.encodeIfPresent(namespaceWrappedArray, forKey: .namespaceWrappedArray) + try container.encodeIfPresent(prefixNsString, forKey: .prefixNsString) + try container.encodeIfPresent(prefixNsNumber, forKey: .prefixNsNumber) + try container.encodeIfPresent(prefixNsInteger, forKey: .prefixNsInteger) + try container.encodeIfPresent(prefixNsBoolean, forKey: .prefixNsBoolean) + try container.encodeIfPresent(prefixNsArray, forKey: .prefixNsArray) + try container.encodeIfPresent(prefixNsWrappedArray, forKey: .prefixNsWrappedArray) + } + + public static func == (lhs: XmlItem, rhs: XmlItem) -> Bool { + lhs.attributeString == rhs.attributeString && + lhs.attributeNumber == rhs.attributeNumber && + lhs.attributeInteger == rhs.attributeInteger && + lhs.attributeBoolean == rhs.attributeBoolean && + lhs.wrappedArray == rhs.wrappedArray && + lhs.nameString == rhs.nameString && + lhs.nameNumber == rhs.nameNumber && + lhs.nameInteger == rhs.nameInteger && + lhs.nameBoolean == rhs.nameBoolean && + lhs.nameArray == rhs.nameArray && + lhs.nameWrappedArray == rhs.nameWrappedArray && + lhs.prefixString == rhs.prefixString && + lhs.prefixNumber == rhs.prefixNumber && + lhs.prefixInteger == rhs.prefixInteger && + lhs.prefixBoolean == rhs.prefixBoolean && + lhs.prefixArray == rhs.prefixArray && + lhs.prefixWrappedArray == rhs.prefixWrappedArray && + lhs.namespaceString == rhs.namespaceString && + lhs.namespaceNumber == rhs.namespaceNumber && + lhs.namespaceInteger == rhs.namespaceInteger && + lhs.namespaceBoolean == rhs.namespaceBoolean && + lhs.namespaceArray == rhs.namespaceArray && + lhs.namespaceWrappedArray == rhs.namespaceWrappedArray && + lhs.prefixNsString == rhs.prefixNsString && + lhs.prefixNsNumber == rhs.prefixNsNumber && + lhs.prefixNsInteger == rhs.prefixNsInteger && + lhs.prefixNsBoolean == rhs.prefixNsBoolean && + lhs.prefixNsArray == rhs.prefixNsArray && + lhs.prefixNsWrappedArray == rhs.prefixNsWrappedArray + + } + + public func hash(into hasher: inout Hasher) { + hasher.combine(attributeString?.hashValue) + hasher.combine(attributeNumber?.hashValue) + hasher.combine(attributeInteger?.hashValue) + hasher.combine(attributeBoolean?.hashValue) + hasher.combine(wrappedArray?.hashValue) + hasher.combine(nameString?.hashValue) + hasher.combine(nameNumber?.hashValue) + hasher.combine(nameInteger?.hashValue) + hasher.combine(nameBoolean?.hashValue) + hasher.combine(nameArray?.hashValue) + hasher.combine(nameWrappedArray?.hashValue) + hasher.combine(prefixString?.hashValue) + hasher.combine(prefixNumber?.hashValue) + hasher.combine(prefixInteger?.hashValue) + hasher.combine(prefixBoolean?.hashValue) + hasher.combine(prefixArray?.hashValue) + hasher.combine(prefixWrappedArray?.hashValue) + hasher.combine(namespaceString?.hashValue) + hasher.combine(namespaceNumber?.hashValue) + hasher.combine(namespaceInteger?.hashValue) + hasher.combine(namespaceBoolean?.hashValue) + hasher.combine(namespaceArray?.hashValue) + hasher.combine(namespaceWrappedArray?.hashValue) + hasher.combine(prefixNsString?.hashValue) + hasher.combine(prefixNsNumber?.hashValue) + hasher.combine(prefixNsInteger?.hashValue) + hasher.combine(prefixNsBoolean?.hashValue) + hasher.combine(prefixNsArray?.hashValue) + hasher.combine(prefixNsWrappedArray?.hashValue) + + } +} + diff --git a/samples/client/petstore/swift5/vaporLibrary/docs/AdditionalPropertiesAnyType.md b/samples/client/petstore/swift5/vaporLibrary/docs/AdditionalPropertiesAnyType.md new file mode 100644 index 00000000000..bae60ab148f --- /dev/null +++ b/samples/client/petstore/swift5/vaporLibrary/docs/AdditionalPropertiesAnyType.md @@ -0,0 +1,10 @@ +# AdditionalPropertiesAnyType + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **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/swift5/vaporLibrary/docs/AdditionalPropertiesArray.md b/samples/client/petstore/swift5/vaporLibrary/docs/AdditionalPropertiesArray.md new file mode 100644 index 00000000000..a371b5e28f3 --- /dev/null +++ b/samples/client/petstore/swift5/vaporLibrary/docs/AdditionalPropertiesArray.md @@ -0,0 +1,10 @@ +# AdditionalPropertiesArray + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **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/swift5/vaporLibrary/docs/AdditionalPropertiesBoolean.md b/samples/client/petstore/swift5/vaporLibrary/docs/AdditionalPropertiesBoolean.md new file mode 100644 index 00000000000..d5f0d6da11e --- /dev/null +++ b/samples/client/petstore/swift5/vaporLibrary/docs/AdditionalPropertiesBoolean.md @@ -0,0 +1,10 @@ +# AdditionalPropertiesBoolean + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **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/swift5/vaporLibrary/docs/AdditionalPropertiesClass.md b/samples/client/petstore/swift5/vaporLibrary/docs/AdditionalPropertiesClass.md new file mode 100644 index 00000000000..1cffcdd8484 --- /dev/null +++ b/samples/client/petstore/swift5/vaporLibrary/docs/AdditionalPropertiesClass.md @@ -0,0 +1,20 @@ +# AdditionalPropertiesClass + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**mapString** | **[String: String]** | | [optional] +**mapNumber** | **[String: Double]** | | [optional] +**mapInteger** | **[String: Int]** | | [optional] +**mapBoolean** | **[String: Bool]** | | [optional] +**mapArrayInteger** | [String: [Int]] | | [optional] +**mapArrayAnytype** | [String: [AnyCodable]] | | [optional] +**mapMapString** | [String: [String: String]] | | [optional] +**mapMapAnytype** | [String: [String: AnyCodable]] | | [optional] +**anytype1** | [**AnyCodable**](.md) | | [optional] +**anytype2** | [**AnyCodable**](.md) | | [optional] +**anytype3** | [**AnyCodable**](.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/swift5/vaporLibrary/docs/AdditionalPropertiesInteger.md b/samples/client/petstore/swift5/vaporLibrary/docs/AdditionalPropertiesInteger.md new file mode 100644 index 00000000000..629293abdfe --- /dev/null +++ b/samples/client/petstore/swift5/vaporLibrary/docs/AdditionalPropertiesInteger.md @@ -0,0 +1,10 @@ +# AdditionalPropertiesInteger + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **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/swift5/vaporLibrary/docs/AdditionalPropertiesNumber.md b/samples/client/petstore/swift5/vaporLibrary/docs/AdditionalPropertiesNumber.md new file mode 100644 index 00000000000..65adfe78137 --- /dev/null +++ b/samples/client/petstore/swift5/vaporLibrary/docs/AdditionalPropertiesNumber.md @@ -0,0 +1,10 @@ +# AdditionalPropertiesNumber + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **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/swift5/vaporLibrary/docs/AdditionalPropertiesObject.md b/samples/client/petstore/swift5/vaporLibrary/docs/AdditionalPropertiesObject.md new file mode 100644 index 00000000000..99d69b7aae6 --- /dev/null +++ b/samples/client/petstore/swift5/vaporLibrary/docs/AdditionalPropertiesObject.md @@ -0,0 +1,10 @@ +# AdditionalPropertiesObject + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **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/swift5/vaporLibrary/docs/AdditionalPropertiesString.md b/samples/client/petstore/swift5/vaporLibrary/docs/AdditionalPropertiesString.md new file mode 100644 index 00000000000..5bb8122887c --- /dev/null +++ b/samples/client/petstore/swift5/vaporLibrary/docs/AdditionalPropertiesString.md @@ -0,0 +1,10 @@ +# AdditionalPropertiesString + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **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/swift5/vaporLibrary/docs/Animal.md b/samples/client/petstore/swift5/vaporLibrary/docs/Animal.md new file mode 100644 index 00000000000..69c601455cd --- /dev/null +++ b/samples/client/petstore/swift5/vaporLibrary/docs/Animal.md @@ -0,0 +1,11 @@ +# Animal + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**className** | **String** | | +**color** | **String** | | [optional] [default to "red"] + +[[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/swift5/vaporLibrary/docs/AnimalFarm.md b/samples/client/petstore/swift5/vaporLibrary/docs/AnimalFarm.md new file mode 100644 index 00000000000..df6bab21dae --- /dev/null +++ b/samples/client/petstore/swift5/vaporLibrary/docs/AnimalFarm.md @@ -0,0 +1,9 @@ +# AnimalFarm + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +[[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/swift5/vaporLibrary/docs/AnotherFakeAPI.md b/samples/client/petstore/swift5/vaporLibrary/docs/AnotherFakeAPI.md new file mode 100644 index 00000000000..1e71f1db871 --- /dev/null +++ b/samples/client/petstore/swift5/vaporLibrary/docs/AnotherFakeAPI.md @@ -0,0 +1,68 @@ +# AnotherFakeAPI + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**call123testSpecialTags**](AnotherFakeAPI.md#call123testspecialtags) | **PATCH** /another-fake/dummy | To test special tags + + +# **call123testSpecialTags** +```swift + open class func call123testSpecialTags(body: Client, headers: HTTPHeaders = PetstoreClient.customHeaders, beforeSend: (inout ClientRequest) throws -> () = { _ in }) -> EventLoopFuture +``` + +To test special tags + +To test special tags and operation ID starting with number + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let body = Client(client: "client_example") // Client | client model + +// To test special tags +AnotherFakeAPI.call123testSpecialTags(body: body).whenComplete { result in + switch result { + case .failure(let error): + // process error + case .success(let response): + switch response { + // process decoded response value or raw ClientResponse + case .http200(let value, let raw): + case .http0(let value, let raw): + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**Client**](Client.md) | client model | + +### Return type + +#### Call123testSpecialTags + +```swift +public enum Call123testSpecialTags { + case http200(value: Client?, raw: ClientResponse) + case http0(value: Client?, raw: ClientResponse) +} +``` + +### 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/petstore/swift5/vaporLibrary/docs/ApiResponse.md b/samples/client/petstore/swift5/vaporLibrary/docs/ApiResponse.md new file mode 100644 index 00000000000..c6d9768fe9b --- /dev/null +++ b/samples/client/petstore/swift5/vaporLibrary/docs/ApiResponse.md @@ -0,0 +1,12 @@ +# ApiResponse + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**code** | **Int** | | [optional] +**type** | **String** | | [optional] +**message** | **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/swift5/vaporLibrary/docs/ArrayOfArrayOfNumberOnly.md b/samples/client/petstore/swift5/vaporLibrary/docs/ArrayOfArrayOfNumberOnly.md new file mode 100644 index 00000000000..c6fceff5e08 --- /dev/null +++ b/samples/client/petstore/swift5/vaporLibrary/docs/ArrayOfArrayOfNumberOnly.md @@ -0,0 +1,10 @@ +# ArrayOfArrayOfNumberOnly + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**arrayArrayNumber** | [[Double]] | | [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/swift5/vaporLibrary/docs/ArrayOfNumberOnly.md b/samples/client/petstore/swift5/vaporLibrary/docs/ArrayOfNumberOnly.md new file mode 100644 index 00000000000..f09f8fa6f70 --- /dev/null +++ b/samples/client/petstore/swift5/vaporLibrary/docs/ArrayOfNumberOnly.md @@ -0,0 +1,10 @@ +# ArrayOfNumberOnly + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**arrayNumber** | **[Double]** | | [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/swift5/vaporLibrary/docs/ArrayTest.md b/samples/client/petstore/swift5/vaporLibrary/docs/ArrayTest.md new file mode 100644 index 00000000000..bf416b8330c --- /dev/null +++ b/samples/client/petstore/swift5/vaporLibrary/docs/ArrayTest.md @@ -0,0 +1,12 @@ +# ArrayTest + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**arrayOfString** | **[String]** | | [optional] +**arrayArrayOfInteger** | [[Int64]] | | [optional] +**arrayArrayOfModel** | [[ReadOnlyFirst]] | | [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/swift5/vaporLibrary/docs/BigCat.md b/samples/client/petstore/swift5/vaporLibrary/docs/BigCat.md new file mode 100644 index 00000000000..cd904c7381a --- /dev/null +++ b/samples/client/petstore/swift5/vaporLibrary/docs/BigCat.md @@ -0,0 +1,10 @@ +# BigCat + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**kind** | **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/swift5/vaporLibrary/docs/BigCatAllOf.md b/samples/client/petstore/swift5/vaporLibrary/docs/BigCatAllOf.md new file mode 100644 index 00000000000..20da4caf5d0 --- /dev/null +++ b/samples/client/petstore/swift5/vaporLibrary/docs/BigCatAllOf.md @@ -0,0 +1,10 @@ +# BigCatAllOf + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**kind** | **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/swift5/vaporLibrary/docs/Capitalization.md b/samples/client/petstore/swift5/vaporLibrary/docs/Capitalization.md new file mode 100644 index 00000000000..95374216c77 --- /dev/null +++ b/samples/client/petstore/swift5/vaporLibrary/docs/Capitalization.md @@ -0,0 +1,15 @@ +# Capitalization + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**smallCamel** | **String** | | [optional] +**capitalCamel** | **String** | | [optional] +**smallSnake** | **String** | | [optional] +**capitalSnake** | **String** | | [optional] +**sCAETHFlowPoints** | **String** | | [optional] +**ATT_NAME** | **String** | Name of the pet | [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/swift5/vaporLibrary/docs/Cat.md b/samples/client/petstore/swift5/vaporLibrary/docs/Cat.md new file mode 100644 index 00000000000..fb5949b1576 --- /dev/null +++ b/samples/client/petstore/swift5/vaporLibrary/docs/Cat.md @@ -0,0 +1,10 @@ +# Cat + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**declawed** | **Bool** | | [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/swift5/vaporLibrary/docs/CatAllOf.md b/samples/client/petstore/swift5/vaporLibrary/docs/CatAllOf.md new file mode 100644 index 00000000000..79789be61c0 --- /dev/null +++ b/samples/client/petstore/swift5/vaporLibrary/docs/CatAllOf.md @@ -0,0 +1,10 @@ +# CatAllOf + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**declawed** | **Bool** | | [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/swift5/vaporLibrary/docs/Category.md b/samples/client/petstore/swift5/vaporLibrary/docs/Category.md new file mode 100644 index 00000000000..5ca5408c0f9 --- /dev/null +++ b/samples/client/petstore/swift5/vaporLibrary/docs/Category.md @@ -0,0 +1,11 @@ +# Category + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **Int64** | | [optional] +**name** | **String** | | [default to "default-name"] + +[[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/swift5/vaporLibrary/docs/ClassModel.md b/samples/client/petstore/swift5/vaporLibrary/docs/ClassModel.md new file mode 100644 index 00000000000..60989bb6b64 --- /dev/null +++ b/samples/client/petstore/swift5/vaporLibrary/docs/ClassModel.md @@ -0,0 +1,10 @@ +# ClassModel + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**`class`** | **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/swift5/vaporLibrary/docs/Client.md b/samples/client/petstore/swift5/vaporLibrary/docs/Client.md new file mode 100644 index 00000000000..0de1b238c36 --- /dev/null +++ b/samples/client/petstore/swift5/vaporLibrary/docs/Client.md @@ -0,0 +1,10 @@ +# Client + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**client** | **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/swift5/vaporLibrary/docs/Dog.md b/samples/client/petstore/swift5/vaporLibrary/docs/Dog.md new file mode 100644 index 00000000000..4824786da04 --- /dev/null +++ b/samples/client/petstore/swift5/vaporLibrary/docs/Dog.md @@ -0,0 +1,10 @@ +# Dog + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**breed** | **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/swift5/vaporLibrary/docs/DogAllOf.md b/samples/client/petstore/swift5/vaporLibrary/docs/DogAllOf.md new file mode 100644 index 00000000000..9302ef52e93 --- /dev/null +++ b/samples/client/petstore/swift5/vaporLibrary/docs/DogAllOf.md @@ -0,0 +1,10 @@ +# DogAllOf + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**breed** | **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/swift5/vaporLibrary/docs/EnumArrays.md b/samples/client/petstore/swift5/vaporLibrary/docs/EnumArrays.md new file mode 100644 index 00000000000..b9a9807d3c8 --- /dev/null +++ b/samples/client/petstore/swift5/vaporLibrary/docs/EnumArrays.md @@ -0,0 +1,11 @@ +# EnumArrays + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**justSymbol** | **String** | | [optional] +**arrayEnum** | **[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/swift5/vaporLibrary/docs/EnumClass.md b/samples/client/petstore/swift5/vaporLibrary/docs/EnumClass.md new file mode 100644 index 00000000000..67f017becd0 --- /dev/null +++ b/samples/client/petstore/swift5/vaporLibrary/docs/EnumClass.md @@ -0,0 +1,9 @@ +# EnumClass + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +[[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/swift5/vaporLibrary/docs/EnumTest.md b/samples/client/petstore/swift5/vaporLibrary/docs/EnumTest.md new file mode 100644 index 00000000000..bc9b036dd76 --- /dev/null +++ b/samples/client/petstore/swift5/vaporLibrary/docs/EnumTest.md @@ -0,0 +1,14 @@ +# EnumTest + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**enumString** | **String** | | [optional] +**enumStringRequired** | **String** | | +**enumInteger** | **Int** | | [optional] +**enumNumber** | **Double** | | [optional] +**outerEnum** | [**OuterEnum**](OuterEnum.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/swift5/vaporLibrary/docs/FakeAPI.md b/samples/client/petstore/swift5/vaporLibrary/docs/FakeAPI.md new file mode 100644 index 00000000000..1883af3085c --- /dev/null +++ b/samples/client/petstore/swift5/vaporLibrary/docs/FakeAPI.md @@ -0,0 +1,901 @@ +# FakeAPI + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**createXmlItem**](FakeAPI.md#createxmlitem) | **POST** /fake/create_xml_item | creates an XmlItem +[**fakeOuterBooleanSerialize**](FakeAPI.md#fakeouterbooleanserialize) | **POST** /fake/outer/boolean | +[**fakeOuterCompositeSerialize**](FakeAPI.md#fakeoutercompositeserialize) | **POST** /fake/outer/composite | +[**fakeOuterNumberSerialize**](FakeAPI.md#fakeouternumberserialize) | **POST** /fake/outer/number | +[**fakeOuterStringSerialize**](FakeAPI.md#fakeouterstringserialize) | **POST** /fake/outer/string | +[**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 +[**testEndpointParameters**](FakeAPI.md#testendpointparameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 +[**testEnumParameters**](FakeAPI.md#testenumparameters) | **GET** /fake | To test enum parameters +[**testGroupParameters**](FakeAPI.md#testgroupparameters) | **DELETE** /fake | Fake endpoint to test group parameters (optional) +[**testInlineAdditionalProperties**](FakeAPI.md#testinlineadditionalproperties) | **POST** /fake/inline-additionalProperties | test inline additionalProperties +[**testJsonFormData**](FakeAPI.md#testjsonformdata) | **GET** /fake/jsonFormData | test json serialization of form data +[**testQueryParameterCollectionFormat**](FakeAPI.md#testqueryparametercollectionformat) | **PUT** /fake/test-query-paramters | + + +# **createXmlItem** +```swift + open class func createXmlItem(xmlItem: XmlItem, headers: HTTPHeaders = PetstoreClient.customHeaders, beforeSend: (inout ClientRequest) throws -> () = { _ in }) -> EventLoopFuture +``` + +creates an XmlItem + +this route creates an XmlItem + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let xmlItem = XmlItem(attributeString: "attributeString_example", attributeNumber: 123, attributeInteger: 123, attributeBoolean: true, wrappedArray: [123], nameString: "nameString_example", nameNumber: 123, nameInteger: 123, nameBoolean: true, nameArray: [123], nameWrappedArray: [123], prefixString: "prefixString_example", prefixNumber: 123, prefixInteger: 123, prefixBoolean: true, prefixArray: [123], prefixWrappedArray: [123], namespaceString: "namespaceString_example", namespaceNumber: 123, namespaceInteger: 123, namespaceBoolean: true, namespaceArray: [123], namespaceWrappedArray: [123], prefixNsString: "prefixNsString_example", prefixNsNumber: 123, prefixNsInteger: 123, prefixNsBoolean: true, prefixNsArray: [123], prefixNsWrappedArray: [123]) // XmlItem | XmlItem Body + +// creates an XmlItem +FakeAPI.createXmlItem(xmlItem: xmlItem).whenComplete { result in + switch result { + case .failure(let error): + // process error + case .success(let response): + switch response { + // process decoded response value or raw ClientResponse + case .http200(let value, let raw): + case .http0(let value, let raw): + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **xmlItem** | [**XmlItem**](XmlItem.md) | XmlItem Body | + +### Return type + +#### CreateXmlItem + +```swift +public enum CreateXmlItem { + case http200(value: Void?, raw: ClientResponse) + case http0(value: Void?, raw: ClientResponse) +} +``` + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/xml, application/xml; charset=utf-8, application/xml; charset=utf-16, text/xml, text/xml; charset=utf-8, text/xml; charset=utf-16 + - **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) + +# **fakeOuterBooleanSerialize** +```swift + open class func fakeOuterBooleanSerialize(body: Bool? = nil, headers: HTTPHeaders = PetstoreClient.customHeaders, beforeSend: (inout ClientRequest) throws -> () = { _ in }) -> EventLoopFuture +``` + + + +Test serialization of outer boolean types + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let body = true // Bool | Input boolean as post body (optional) + +FakeAPI.fakeOuterBooleanSerialize(body: body).whenComplete { result in + switch result { + case .failure(let error): + // process error + case .success(let response): + switch response { + // process decoded response value or raw ClientResponse + case .http200(let value, let raw): + case .http0(let value, let raw): + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | **Bool** | Input boolean as post body | [optional] + +### Return type + +#### FakeOuterBooleanSerialize + +```swift +public enum FakeOuterBooleanSerialize { + case http200(value: Bool?, raw: ClientResponse) + case http0(value: Bool?, raw: ClientResponse) +} +``` + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: */* + +[[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) + +# **fakeOuterCompositeSerialize** +```swift + open class func fakeOuterCompositeSerialize(body: OuterComposite? = nil, headers: HTTPHeaders = PetstoreClient.customHeaders, beforeSend: (inout ClientRequest) throws -> () = { _ in }) -> EventLoopFuture +``` + + + +Test serialization of object with outer number type + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let body = OuterComposite(myNumber: 123, myString: "myString_example", myBoolean: false) // OuterComposite | Input composite as post body (optional) + +FakeAPI.fakeOuterCompositeSerialize(body: body).whenComplete { result in + switch result { + case .failure(let error): + // process error + case .success(let response): + switch response { + // process decoded response value or raw ClientResponse + case .http200(let value, let raw): + case .http0(let value, let raw): + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**OuterComposite**](OuterComposite.md) | Input composite as post body | [optional] + +### Return type + +#### FakeOuterCompositeSerialize + +```swift +public enum FakeOuterCompositeSerialize { + case http200(value: OuterComposite?, raw: ClientResponse) + case http0(value: OuterComposite?, raw: ClientResponse) +} +``` + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: */* + +[[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) + +# **fakeOuterNumberSerialize** +```swift + open class func fakeOuterNumberSerialize(body: Double? = nil, headers: HTTPHeaders = PetstoreClient.customHeaders, beforeSend: (inout ClientRequest) throws -> () = { _ in }) -> EventLoopFuture +``` + + + +Test serialization of outer number types + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let body = 987 // Double | Input number as post body (optional) + +FakeAPI.fakeOuterNumberSerialize(body: body).whenComplete { result in + switch result { + case .failure(let error): + // process error + case .success(let response): + switch response { + // process decoded response value or raw ClientResponse + case .http200(let value, let raw): + case .http0(let value, let raw): + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | **Double** | Input number as post body | [optional] + +### Return type + +#### FakeOuterNumberSerialize + +```swift +public enum FakeOuterNumberSerialize { + case http200(value: Double?, raw: ClientResponse) + case http0(value: Double?, raw: ClientResponse) +} +``` + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: */* + +[[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) + +# **fakeOuterStringSerialize** +```swift + open class func fakeOuterStringSerialize(body: String? = nil, headers: HTTPHeaders = PetstoreClient.customHeaders, beforeSend: (inout ClientRequest) throws -> () = { _ in }) -> EventLoopFuture +``` + + + +Test serialization of outer string types + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let body = "body_example" // String | Input string as post body (optional) + +FakeAPI.fakeOuterStringSerialize(body: body).whenComplete { result in + switch result { + case .failure(let error): + // process error + case .success(let response): + switch response { + // process decoded response value or raw ClientResponse + case .http200(let value, let raw): + case .http0(let value, let raw): + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | **String** | Input string as post body | [optional] + +### Return type + +#### FakeOuterStringSerialize + +```swift +public enum FakeOuterStringSerialize { + case http200(value: String?, raw: ClientResponse) + case http0(value: String?, raw: ClientResponse) +} +``` + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: */* + +[[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** +```swift + open class func testBodyWithFileSchema(body: FileSchemaTestClass, headers: HTTPHeaders = PetstoreClient.customHeaders, beforeSend: (inout ClientRequest) throws -> () = { _ in }) -> EventLoopFuture +``` + + + +For this test, the body for this request much reference a schema named `File`. + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let body = FileSchemaTestClass(file: File(sourceURI: "sourceURI_example"), files: [nil]) // FileSchemaTestClass | + +FakeAPI.testBodyWithFileSchema(body: body).whenComplete { result in + switch result { + case .failure(let error): + // process error + case .success(let response): + switch response { + // process decoded response value or raw ClientResponse + case .http200(let value, let raw): + case .http0(let value, let raw): + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**FileSchemaTestClass**](FileSchemaTestClass.md) | | + +### Return type + +#### TestBodyWithFileSchema + +```swift +public enum TestBodyWithFileSchema { + case http200(value: Void?, raw: ClientResponse) + case http0(value: Void?, raw: ClientResponse) +} +``` + +### 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) + +# **testBodyWithQueryParams** +```swift + open class func testBodyWithQueryParams(query: String, body: User, headers: HTTPHeaders = PetstoreClient.customHeaders, beforeSend: (inout ClientRequest) throws -> () = { _ in }) -> EventLoopFuture +``` + + + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let query = "query_example" // String | +let body = User(id: 123, username: "username_example", firstName: "firstName_example", lastName: "lastName_example", email: "email_example", password: "password_example", phone: "phone_example", userStatus: 123) // User | + +FakeAPI.testBodyWithQueryParams(query: query, body: body).whenComplete { result in + switch result { + case .failure(let error): + // process error + case .success(let response): + switch response { + // process decoded response value or raw ClientResponse + case .http200(let value, let raw): + case .http0(let value, let raw): + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **query** | **String** | | + **body** | [**User**](User.md) | | + +### Return type + +#### TestBodyWithQueryParams + +```swift +public enum TestBodyWithQueryParams { + case http200(value: Void?, raw: ClientResponse) + case http0(value: Void?, raw: ClientResponse) +} +``` + +### 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) + +# **testClientModel** +```swift + open class func testClientModel(body: Client, headers: HTTPHeaders = PetstoreClient.customHeaders, beforeSend: (inout ClientRequest) throws -> () = { _ in }) -> EventLoopFuture +``` + +To test \"client\" model + +To test \"client\" model + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let body = Client(client: "client_example") // Client | client model + +// To test \"client\" model +FakeAPI.testClientModel(body: body).whenComplete { result in + switch result { + case .failure(let error): + // process error + case .success(let response): + switch response { + // process decoded response value or raw ClientResponse + case .http200(let value, let raw): + case .http0(let value, let raw): + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**Client**](Client.md) | client model | + +### Return type + +#### TestClientModel + +```swift +public enum TestClientModel { + case http200(value: Client?, raw: ClientResponse) + case http0(value: Client?, raw: ClientResponse) +} +``` + +### 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) + +# **testEndpointParameters** +```swift + open class func testEndpointParameters(number: Double, double: Double, patternWithoutDelimiter: String, byte: Data, integer: Int? = nil, int32: Int? = nil, int64: Int64? = nil, float: Float? = nil, string: String? = nil, binary: Data? = nil, date: Date? = nil, dateTime: Date? = nil, password: String? = nil, callback: String? = nil, headers: HTTPHeaders = PetstoreClient.customHeaders, beforeSend: (inout ClientRequest) throws -> () = { _ in }) -> EventLoopFuture +``` + +Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + +Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let number = 987 // Double | None +let double = 987 // Double | None +let patternWithoutDelimiter = "patternWithoutDelimiter_example" // String | None +let byte = Data([9, 8, 7]) // Data | None +let integer = 987 // Int | None (optional) +let int32 = 987 // Int | None (optional) +let int64 = 987 // Int64 | None (optional) +let float = 987 // Float | None (optional) +let string = "string_example" // String | None (optional) +let binary = Data([9, 8, 7]) // Data | None (optional) +let date = Date() // Date | None (optional) +let dateTime = Date() // Date | None (optional) +let password = "password_example" // String | None (optional) +let callback = "callback_example" // String | None (optional) + +// Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 +FakeAPI.testEndpointParameters(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).whenComplete { result in + switch result { + case .failure(let error): + // process error + case .success(let response): + switch response { + // process decoded response value or raw ClientResponse + case .http400(let value, let raw): + case .http404(let value, let raw): + case .http0(let value, let raw): + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **number** | **Double** | None | + **double** | **Double** | None | + **patternWithoutDelimiter** | **String** | None | + **byte** | **Data** | None | + **integer** | **Int** | None | [optional] + **int32** | **Int** | None | [optional] + **int64** | **Int64** | None | [optional] + **float** | **Float** | None | [optional] + **string** | **String** | None | [optional] + **binary** | **Data** | None | [optional] + **date** | **Date** | None | [optional] + **dateTime** | **Date** | None | [optional] + **password** | **String** | None | [optional] + **callback** | **String** | None | [optional] + +### Return type + +#### TestEndpointParameters + +```swift +public enum TestEndpointParameters { + case http400(value: Void?, raw: ClientResponse) + case http404(value: Void?, raw: ClientResponse) + case http0(value: Void?, raw: ClientResponse) +} +``` + +### Authorization + +[http_basic_test](../README.md#http_basic_test) + +### HTTP request headers + + - **Content-Type**: application/x-www-form-urlencoded + - **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) + +# **testEnumParameters** +```swift + open class func testEnumParameters(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, headers: HTTPHeaders = PetstoreClient.customHeaders, beforeSend: (inout ClientRequest) throws -> () = { _ in }) -> EventLoopFuture +``` + +To test enum parameters + +To test enum parameters + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let enumHeaderStringArray = ["enumHeaderStringArray_example"] // [String] | Header parameter enum test (string array) (optional) +let enumHeaderString = "enumHeaderString_example" // String | Header parameter enum test (string) (optional) (default to .efg) +let enumQueryStringArray = ["enumQueryStringArray_example"] // [String] | Query parameter enum test (string array) (optional) +let enumQueryString = "enumQueryString_example" // String | Query parameter enum test (string) (optional) (default to .efg) +let enumQueryInteger = 987 // Int | Query parameter enum test (double) (optional) +let enumQueryDouble = 987 // Double | Query parameter enum test (double) (optional) +let enumFormStringArray = ["inner_example"] // [String] | Form parameter enum test (string array) (optional) (default to .dollar) +let enumFormString = "enumFormString_example" // String | Form parameter enum test (string) (optional) (default to .efg) + +// To test enum parameters +FakeAPI.testEnumParameters(enumHeaderStringArray: enumHeaderStringArray, enumHeaderString: enumHeaderString, enumQueryStringArray: enumQueryStringArray, enumQueryString: enumQueryString, enumQueryInteger: enumQueryInteger, enumQueryDouble: enumQueryDouble, enumFormStringArray: enumFormStringArray, enumFormString: enumFormString).whenComplete { result in + switch result { + case .failure(let error): + // process error + case .success(let response): + switch response { + // process decoded response value or raw ClientResponse + case .http400(let value, let raw): + case .http404(let value, let raw): + case .http0(let value, let raw): + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **enumHeaderStringArray** | [**[String]**](String.md) | Header parameter enum test (string array) | [optional] + **enumHeaderString** | **String** | Header parameter enum test (string) | [optional] [default to .efg] + **enumQueryStringArray** | [**[String]**](String.md) | Query parameter enum test (string array) | [optional] + **enumQueryString** | **String** | Query parameter enum test (string) | [optional] [default to .efg] + **enumQueryInteger** | **Int** | Query parameter enum test (double) | [optional] + **enumQueryDouble** | **Double** | Query parameter enum test (double) | [optional] + **enumFormStringArray** | [**[String]**](String.md) | Form parameter enum test (string array) | [optional] [default to .dollar] + **enumFormString** | **String** | Form parameter enum test (string) | [optional] [default to .efg] + +### Return type + +#### TestEnumParameters + +```swift +public enum TestEnumParameters { + case http400(value: Void?, raw: ClientResponse) + case http404(value: Void?, raw: ClientResponse) + case http0(value: Void?, raw: ClientResponse) +} +``` + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/x-www-form-urlencoded + - **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) + +# **testGroupParameters** +```swift + open class func testGroupParameters(requiredStringGroup: Int, requiredBooleanGroup: Bool, requiredInt64Group: Int64, stringGroup: Int? = nil, booleanGroup: Bool? = nil, int64Group: Int64? = nil, headers: HTTPHeaders = PetstoreClient.customHeaders, beforeSend: (inout ClientRequest) throws -> () = { _ in }) -> EventLoopFuture +``` + +Fake endpoint to test group parameters (optional) + +Fake endpoint to test group parameters (optional) + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let requiredStringGroup = 987 // Int | Required String in group parameters +let requiredBooleanGroup = true // Bool | Required Boolean in group parameters +let requiredInt64Group = 987 // Int64 | Required Integer in group parameters +let stringGroup = 987 // Int | String in group parameters (optional) +let booleanGroup = true // Bool | Boolean in group parameters (optional) +let int64Group = 987 // Int64 | Integer in group parameters (optional) + +// Fake endpoint to test group parameters (optional) +FakeAPI.testGroupParameters(requiredStringGroup: requiredStringGroup, requiredBooleanGroup: requiredBooleanGroup, requiredInt64Group: requiredInt64Group, stringGroup: stringGroup, booleanGroup: booleanGroup, int64Group: int64Group).whenComplete { result in + switch result { + case .failure(let error): + // process error + case .success(let response): + switch response { + // process decoded response value or raw ClientResponse + case .http400(let value, let raw): + case .http0(let value, let raw): + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **requiredStringGroup** | **Int** | Required String in group parameters | + **requiredBooleanGroup** | **Bool** | Required Boolean in group parameters | + **requiredInt64Group** | **Int64** | Required Integer in group parameters | + **stringGroup** | **Int** | String in group parameters | [optional] + **booleanGroup** | **Bool** | Boolean in group parameters | [optional] + **int64Group** | **Int64** | Integer in group parameters | [optional] + +### Return type + +#### TestGroupParameters + +```swift +public enum TestGroupParameters { + case http400(value: Void?, raw: ClientResponse) + case http0(value: Void?, raw: ClientResponse) +} +``` + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **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) + +# **testInlineAdditionalProperties** +```swift + open class func testInlineAdditionalProperties(param: [String: String], headers: HTTPHeaders = PetstoreClient.customHeaders, beforeSend: (inout ClientRequest) throws -> () = { _ in }) -> EventLoopFuture +``` + +test inline additionalProperties + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let param = "TODO" // [String: String] | request body + +// test inline additionalProperties +FakeAPI.testInlineAdditionalProperties(param: param).whenComplete { result in + switch result { + case .failure(let error): + // process error + case .success(let response): + switch response { + // process decoded response value or raw ClientResponse + case .http200(let value, let raw): + case .http0(let value, let raw): + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **param** | [**[String: String]**](String.md) | request body | + +### Return type + +#### TestInlineAdditionalProperties + +```swift +public enum TestInlineAdditionalProperties { + case http200(value: Void?, raw: ClientResponse) + case http0(value: Void?, raw: ClientResponse) +} +``` + +### 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) + +# **testJsonFormData** +```swift + open class func testJsonFormData(param: String, param2: String, headers: HTTPHeaders = PetstoreClient.customHeaders, beforeSend: (inout ClientRequest) throws -> () = { _ in }) -> EventLoopFuture +``` + +test json serialization of form data + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let param = "param_example" // String | field1 +let param2 = "param2_example" // String | field2 + +// test json serialization of form data +FakeAPI.testJsonFormData(param: param, param2: param2).whenComplete { result in + switch result { + case .failure(let error): + // process error + case .success(let response): + switch response { + // process decoded response value or raw ClientResponse + case .http200(let value, let raw): + case .http0(let value, let raw): + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **param** | **String** | field1 | + **param2** | **String** | field2 | + +### Return type + +#### TestJsonFormData + +```swift +public enum TestJsonFormData { + case http200(value: Void?, raw: ClientResponse) + case http0(value: Void?, raw: ClientResponse) +} +``` + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/x-www-form-urlencoded + - **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) + +# **testQueryParameterCollectionFormat** +```swift + open class func testQueryParameterCollectionFormat(pipe: [String], ioutil: [String], http: [String], url: [String], context: [String], headers: HTTPHeaders = PetstoreClient.customHeaders, beforeSend: (inout ClientRequest) throws -> () = { _ in }) -> EventLoopFuture +``` + + + +To test the collection format in query parameters + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let pipe = ["inner_example"] // [String] | +let ioutil = ["inner_example"] // [String] | +let http = ["inner_example"] // [String] | +let url = ["inner_example"] // [String] | +let context = ["inner_example"] // [String] | + +FakeAPI.testQueryParameterCollectionFormat(pipe: pipe, ioutil: ioutil, http: http, url: url, context: context).whenComplete { result in + switch result { + case .failure(let error): + // process error + case .success(let response): + switch response { + // process decoded response value or raw ClientResponse + case .http200(let value, let raw): + case .http0(let value, let raw): + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **pipe** | [**[String]**](String.md) | | + **ioutil** | [**[String]**](String.md) | | + **http** | [**[String]**](String.md) | | + **url** | [**[String]**](String.md) | | + **context** | [**[String]**](String.md) | | + +### Return type + +#### TestQueryParameterCollectionFormat + +```swift +public enum TestQueryParameterCollectionFormat { + case http200(value: Void?, raw: ClientResponse) + case http0(value: Void?, raw: ClientResponse) +} +``` + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **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) + diff --git a/samples/client/petstore/swift5/vaporLibrary/docs/FakeClassnameTags123API.md b/samples/client/petstore/swift5/vaporLibrary/docs/FakeClassnameTags123API.md new file mode 100644 index 00000000000..1aebe78f145 --- /dev/null +++ b/samples/client/petstore/swift5/vaporLibrary/docs/FakeClassnameTags123API.md @@ -0,0 +1,68 @@ +# FakeClassnameTags123API + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**testClassname**](FakeClassnameTags123API.md#testclassname) | **PATCH** /fake_classname_test | To test class name in snake case + + +# **testClassname** +```swift + open class func testClassname(body: Client, headers: HTTPHeaders = PetstoreClient.customHeaders, beforeSend: (inout ClientRequest) throws -> () = { _ in }) -> EventLoopFuture +``` + +To test class name in snake case + +To test class name in snake case + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let body = Client(client: "client_example") // Client | client model + +// To test class name in snake case +FakeClassnameTags123API.testClassname(body: body).whenComplete { result in + switch result { + case .failure(let error): + // process error + case .success(let response): + switch response { + // process decoded response value or raw ClientResponse + case .http200(let value, let raw): + case .http0(let value, let raw): + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**Client**](Client.md) | client model | + +### Return type + +#### TestClassname + +```swift +public enum TestClassname { + case http200(value: Client?, raw: ClientResponse) + case http0(value: Client?, raw: ClientResponse) +} +``` + +### Authorization + +[api_key_query](../README.md#api_key_query) + +### 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/petstore/swift5/vaporLibrary/docs/File.md b/samples/client/petstore/swift5/vaporLibrary/docs/File.md new file mode 100644 index 00000000000..3edfef17b79 --- /dev/null +++ b/samples/client/petstore/swift5/vaporLibrary/docs/File.md @@ -0,0 +1,10 @@ +# File + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**sourceURI** | **String** | Test capitalization | [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/swift5/vaporLibrary/docs/FileSchemaTestClass.md b/samples/client/petstore/swift5/vaporLibrary/docs/FileSchemaTestClass.md new file mode 100644 index 00000000000..afdacc60b2c --- /dev/null +++ b/samples/client/petstore/swift5/vaporLibrary/docs/FileSchemaTestClass.md @@ -0,0 +1,11 @@ +# FileSchemaTestClass + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**file** | [**File**](File.md) | | [optional] +**files** | [File] | | [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/swift5/vaporLibrary/docs/FormatTest.md b/samples/client/petstore/swift5/vaporLibrary/docs/FormatTest.md new file mode 100644 index 00000000000..6e6c67b2a4f --- /dev/null +++ b/samples/client/petstore/swift5/vaporLibrary/docs/FormatTest.md @@ -0,0 +1,23 @@ +# FormatTest + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**integer** | **Int** | | [optional] +**int32** | **Int** | | [optional] +**int64** | **Int64** | | [optional] +**number** | **Double** | | +**float** | **Float** | | [optional] +**double** | **Double** | | [optional] +**string** | **String** | | [optional] +**byte** | **Data** | | +**binary** | **Data** | | [optional] +**date** | **Date** | | +**dateTime** | **Date** | | [optional] +**uuid** | **UUID** | | [optional] +**password** | **String** | | +**bigDecimal** | **Decimal** | | [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/swift5/vaporLibrary/docs/HasOnlyReadOnly.md b/samples/client/petstore/swift5/vaporLibrary/docs/HasOnlyReadOnly.md new file mode 100644 index 00000000000..57b6e3a17e6 --- /dev/null +++ b/samples/client/petstore/swift5/vaporLibrary/docs/HasOnlyReadOnly.md @@ -0,0 +1,11 @@ +# HasOnlyReadOnly + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**bar** | **String** | | [optional] [readonly] +**foo** | **String** | | [optional] [readonly] + +[[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/swift5/vaporLibrary/docs/List.md b/samples/client/petstore/swift5/vaporLibrary/docs/List.md new file mode 100644 index 00000000000..b77718302ed --- /dev/null +++ b/samples/client/petstore/swift5/vaporLibrary/docs/List.md @@ -0,0 +1,10 @@ +# List + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**_123list** | **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/swift5/vaporLibrary/docs/MapTest.md b/samples/client/petstore/swift5/vaporLibrary/docs/MapTest.md new file mode 100644 index 00000000000..73f9e0d50ac --- /dev/null +++ b/samples/client/petstore/swift5/vaporLibrary/docs/MapTest.md @@ -0,0 +1,13 @@ +# MapTest + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**mapMapOfString** | [String: [String: String]] | | [optional] +**mapOfEnumString** | **[String: String]** | | [optional] +**directMap** | **[String: Bool]** | | [optional] +**indirectMap** | [**StringBooleanMap**](StringBooleanMap.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/swift5/vaporLibrary/docs/MixedPropertiesAndAdditionalPropertiesClass.md b/samples/client/petstore/swift5/vaporLibrary/docs/MixedPropertiesAndAdditionalPropertiesClass.md new file mode 100644 index 00000000000..3fdfd03f0e3 --- /dev/null +++ b/samples/client/petstore/swift5/vaporLibrary/docs/MixedPropertiesAndAdditionalPropertiesClass.md @@ -0,0 +1,12 @@ +# MixedPropertiesAndAdditionalPropertiesClass + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**uuid** | **UUID** | | [optional] +**dateTime** | **Date** | | [optional] +**map** | [String: Animal] | | [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/swift5/vaporLibrary/docs/Model200Response.md b/samples/client/petstore/swift5/vaporLibrary/docs/Model200Response.md new file mode 100644 index 00000000000..e064d9d0111 --- /dev/null +++ b/samples/client/petstore/swift5/vaporLibrary/docs/Model200Response.md @@ -0,0 +1,11 @@ +# Model200Response + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **Int** | | [optional] +**`class`** | **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/swift5/vaporLibrary/docs/Name.md b/samples/client/petstore/swift5/vaporLibrary/docs/Name.md new file mode 100644 index 00000000000..f7b180292cd --- /dev/null +++ b/samples/client/petstore/swift5/vaporLibrary/docs/Name.md @@ -0,0 +1,13 @@ +# Name + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **Int** | | +**snakeCase** | **Int** | | [optional] [readonly] +**property** | **String** | | [optional] +**_123number** | **Int** | | [optional] [readonly] + +[[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/swift5/vaporLibrary/docs/NumberOnly.md b/samples/client/petstore/swift5/vaporLibrary/docs/NumberOnly.md new file mode 100644 index 00000000000..72bd361168b --- /dev/null +++ b/samples/client/petstore/swift5/vaporLibrary/docs/NumberOnly.md @@ -0,0 +1,10 @@ +# NumberOnly + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**justNumber** | **Double** | | [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/swift5/vaporLibrary/docs/Order.md b/samples/client/petstore/swift5/vaporLibrary/docs/Order.md new file mode 100644 index 00000000000..15487f01175 --- /dev/null +++ b/samples/client/petstore/swift5/vaporLibrary/docs/Order.md @@ -0,0 +1,15 @@ +# Order + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **Int64** | | [optional] +**petId** | **Int64** | | [optional] +**quantity** | **Int** | | [optional] +**shipDate** | **Date** | | [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/swift5/vaporLibrary/docs/OuterComposite.md b/samples/client/petstore/swift5/vaporLibrary/docs/OuterComposite.md new file mode 100644 index 00000000000..d6b3583bc3f --- /dev/null +++ b/samples/client/petstore/swift5/vaporLibrary/docs/OuterComposite.md @@ -0,0 +1,12 @@ +# OuterComposite + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**myNumber** | **Double** | | [optional] +**myString** | **String** | | [optional] +**myBoolean** | **Bool** | | [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/swift5/vaporLibrary/docs/OuterEnum.md b/samples/client/petstore/swift5/vaporLibrary/docs/OuterEnum.md new file mode 100644 index 00000000000..06d413b0168 --- /dev/null +++ b/samples/client/petstore/swift5/vaporLibrary/docs/OuterEnum.md @@ -0,0 +1,9 @@ +# OuterEnum + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +[[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/swift5/vaporLibrary/docs/Pet.md b/samples/client/petstore/swift5/vaporLibrary/docs/Pet.md new file mode 100644 index 00000000000..36e8e488439 --- /dev/null +++ b/samples/client/petstore/swift5/vaporLibrary/docs/Pet.md @@ -0,0 +1,15 @@ +# Pet + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **Int64** | | [optional] +**category** | [**Category**](Category.md) | | [optional] +**name** | **String** | | +**photoUrls** | **Set** | | +**tags** | [Tag] | | [optional] +**status** | **String** | pet status in the store | [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/swift5/vaporLibrary/docs/PetAPI.md b/samples/client/petstore/swift5/vaporLibrary/docs/PetAPI.md new file mode 100644 index 00000000000..88f6a377038 --- /dev/null +++ b/samples/client/petstore/swift5/vaporLibrary/docs/PetAPI.md @@ -0,0 +1,568 @@ +# PetAPI + +All URIs are relative to *http://petstore.swagger.io:80/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 +[**uploadFileWithRequiredFile**](PetAPI.md#uploadfilewithrequiredfile) | **POST** /fake/{petId}/uploadImageWithRequiredFile | uploads an image (required) + + +# **addPet** +```swift + open class func addPet(body: Pet, headers: HTTPHeaders = PetstoreClient.customHeaders, beforeSend: (inout ClientRequest) throws -> () = { _ in }) -> EventLoopFuture +``` + +Add a new pet to the store + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let body = Pet(id: 123, category: Category(id: 123, name: "name_example"), name: "name_example", photoUrls: ["photoUrls_example"], tags: [Tag(id: 123, name: "name_example")], status: "status_example") // Pet | Pet object that needs to be added to the store + +// Add a new pet to the store +PetAPI.addPet(body: body).whenComplete { result in + switch result { + case .failure(let error): + // process error + case .success(let response): + switch response { + // process decoded response value or raw ClientResponse + case .http200(let value, let raw): + case .http405(let value, let raw): + case .http0(let value, let raw): + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**Pet**](Pet.md) | Pet object that needs to be added to the store | + +### Return type + +#### AddPet + +```swift +public enum AddPet { + case http200(value: Void?, raw: ClientResponse) + case http405(value: Void?, raw: ClientResponse) + case http0(value: Void?, raw: ClientResponse) +} +``` + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: application/json, application/xml + - **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) + +# **deletePet** +```swift + open class func deletePet(petId: Int64, apiKey: String? = nil, headers: HTTPHeaders = PetstoreClient.customHeaders, beforeSend: (inout ClientRequest) throws -> () = { _ in }) -> EventLoopFuture +``` + +Deletes a pet + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let petId = 987 // Int64 | Pet id to delete +let apiKey = "apiKey_example" // String | (optional) + +// Deletes a pet +PetAPI.deletePet(petId: petId, apiKey: apiKey).whenComplete { result in + switch result { + case .failure(let error): + // process error + case .success(let response): + switch response { + // process decoded response value or raw ClientResponse + case .http200(let value, let raw): + case .http400(let value, let raw): + case .http0(let value, let raw): + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **Int64** | Pet id to delete | + **apiKey** | **String** | | [optional] + +### Return type + +#### DeletePet + +```swift +public enum DeletePet { + case http200(value: Void?, raw: ClientResponse) + case http400(value: Void?, raw: ClientResponse) + case http0(value: Void?, raw: ClientResponse) +} +``` + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: Not defined + - **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) + +# **findPetsByStatus** +```swift + open class func findPetsByStatus(status: [String], headers: HTTPHeaders = PetstoreClient.customHeaders, beforeSend: (inout ClientRequest) throws -> () = { _ in }) -> EventLoopFuture +``` + +Finds Pets by status + +Multiple status values can be provided with comma separated strings + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let status = ["status_example"] // [String] | Status values that need to be considered for filter + +// Finds Pets by status +PetAPI.findPetsByStatus(status: status).whenComplete { result in + switch result { + case .failure(let error): + // process error + case .success(let response): + switch response { + // process decoded response value or raw ClientResponse + case .http200(let value, let raw): + case .http400(let value, let raw): + case .http0(let value, let raw): + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **status** | [**[String]**](String.md) | Status values that need to be considered for filter | + +### Return type + +#### FindPetsByStatus + +```swift +public enum FindPetsByStatus { + case http200(value: [Pet]?, raw: ClientResponse) + case http400(value: Void?, raw: ClientResponse) + case http0(value: [Pet]?, raw: ClientResponse) +} +``` + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: Not defined + - **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) + +# **findPetsByTags** +```swift + open class func findPetsByTags(tags: Set, headers: HTTPHeaders = PetstoreClient.customHeaders, beforeSend: (inout ClientRequest) throws -> () = { _ in }) -> EventLoopFuture +``` + +Finds Pets by tags + +Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let tags = ["inner_example"] // Set | Tags to filter by + +// Finds Pets by tags +PetAPI.findPetsByTags(tags: tags).whenComplete { result in + switch result { + case .failure(let error): + // process error + case .success(let response): + switch response { + // process decoded response value or raw ClientResponse + case .http200(let value, let raw): + case .http400(let value, let raw): + case .http0(let value, let raw): + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **tags** | [**Set<String>**](String.md) | Tags to filter by | + +### Return type + +#### FindPetsByTags + +```swift +public enum FindPetsByTags { + case http200(value: Set<Pet>?, raw: ClientResponse) + case http400(value: Void?, raw: ClientResponse) + case http0(value: Set<Pet>?, raw: ClientResponse) +} +``` + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: Not defined + - **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) + +# **getPetById** +```swift + open class func getPetById(petId: Int64, headers: HTTPHeaders = PetstoreClient.customHeaders, beforeSend: (inout ClientRequest) throws -> () = { _ in }) -> EventLoopFuture +``` + +Find pet by ID + +Returns a single pet + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let petId = 987 // Int64 | ID of pet to return + +// Find pet by ID +PetAPI.getPetById(petId: petId).whenComplete { result in + switch result { + case .failure(let error): + // process error + case .success(let response): + switch response { + // process decoded response value or raw ClientResponse + case .http200(let value, let raw): + case .http400(let value, let raw): + case .http404(let value, let raw): + case .http0(let value, let raw): + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **Int64** | ID of pet to return | + +### Return type + +#### GetPetById + +```swift +public enum GetPetById { + case http200(value: Pet?, raw: ClientResponse) + case http400(value: Void?, raw: ClientResponse) + case http404(value: Void?, raw: ClientResponse) + case http0(value: Pet?, raw: ClientResponse) +} +``` + +### Authorization + +[api_key](../README.md#api_key) + +### HTTP request headers + + - **Content-Type**: Not defined + - **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) + +# **updatePet** +```swift + open class func updatePet(body: Pet, headers: HTTPHeaders = PetstoreClient.customHeaders, beforeSend: (inout ClientRequest) throws -> () = { _ in }) -> EventLoopFuture +``` + +Update an existing pet + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let body = Pet(id: 123, category: Category(id: 123, name: "name_example"), name: "name_example", photoUrls: ["photoUrls_example"], tags: [Tag(id: 123, name: "name_example")], status: "status_example") // Pet | Pet object that needs to be added to the store + +// Update an existing pet +PetAPI.updatePet(body: body).whenComplete { result in + switch result { + case .failure(let error): + // process error + case .success(let response): + switch response { + // process decoded response value or raw ClientResponse + case .http200(let value, let raw): + case .http400(let value, let raw): + case .http404(let value, let raw): + case .http405(let value, let raw): + case .http0(let value, let raw): + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**Pet**](Pet.md) | Pet object that needs to be added to the store | + +### Return type + +#### UpdatePet + +```swift +public enum UpdatePet { + case http200(value: Void?, raw: ClientResponse) + case http400(value: Void?, raw: ClientResponse) + case http404(value: Void?, raw: ClientResponse) + case http405(value: Void?, raw: ClientResponse) + case http0(value: Void?, raw: ClientResponse) +} +``` + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: application/json, application/xml + - **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) + +# **updatePetWithForm** +```swift + open class func updatePetWithForm(petId: Int64, name: String? = nil, status: String? = nil, headers: HTTPHeaders = PetstoreClient.customHeaders, beforeSend: (inout ClientRequest) throws -> () = { _ in }) -> EventLoopFuture +``` + +Updates a pet in the store with form data + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let petId = 987 // Int64 | ID of pet that needs to be updated +let name = "name_example" // String | Updated name of the pet (optional) +let status = "status_example" // String | Updated status of the pet (optional) + +// Updates a pet in the store with form data +PetAPI.updatePetWithForm(petId: petId, name: name, status: status).whenComplete { result in + switch result { + case .failure(let error): + // process error + case .success(let response): + switch response { + // process decoded response value or raw ClientResponse + case .http405(let value, let raw): + case .http0(let value, let raw): + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **Int64** | 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 + +#### UpdatePetWithForm + +```swift +public enum UpdatePetWithForm { + case http405(value: Void?, raw: ClientResponse) + case http0(value: Void?, raw: ClientResponse) +} +``` + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: application/x-www-form-urlencoded + - **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) + +# **uploadFile** +```swift + open class func uploadFile(petId: Int64, additionalMetadata: String? = nil, file: Data? = nil, headers: HTTPHeaders = PetstoreClient.customHeaders, beforeSend: (inout ClientRequest) throws -> () = { _ in }) -> EventLoopFuture +``` + +uploads an image + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let petId = 987 // Int64 | ID of pet to update +let additionalMetadata = "additionalMetadata_example" // String | Additional data to pass to server (optional) +let file = Data([9, 8, 7]) // Data | file to upload (optional) + +// uploads an image +PetAPI.uploadFile(petId: petId, additionalMetadata: additionalMetadata, file: file).whenComplete { result in + switch result { + case .failure(let error): + // process error + case .success(let response): + switch response { + // process decoded response value or raw ClientResponse + case .http200(let value, let raw): + case .http0(let value, let raw): + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **Int64** | ID of pet to update | + **additionalMetadata** | **String** | Additional data to pass to server | [optional] + **file** | **Data** | file to upload | [optional] + +### Return type + +#### UploadFile + +```swift +public enum UploadFile { + case http200(value: ApiResponse?, raw: ClientResponse) + case http0(value: ApiResponse?, raw: ClientResponse) +} +``` + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: multipart/form-data + - **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) + +# **uploadFileWithRequiredFile** +```swift + open class func uploadFileWithRequiredFile(petId: Int64, requiredFile: Data, additionalMetadata: String? = nil, headers: HTTPHeaders = PetstoreClient.customHeaders, beforeSend: (inout ClientRequest) throws -> () = { _ in }) -> EventLoopFuture +``` + +uploads an image (required) + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let petId = 987 // Int64 | ID of pet to update +let requiredFile = Data([9, 8, 7]) // Data | file to upload +let additionalMetadata = "additionalMetadata_example" // String | Additional data to pass to server (optional) + +// uploads an image (required) +PetAPI.uploadFileWithRequiredFile(petId: petId, requiredFile: requiredFile, additionalMetadata: additionalMetadata).whenComplete { result in + switch result { + case .failure(let error): + // process error + case .success(let response): + switch response { + // process decoded response value or raw ClientResponse + case .http200(let value, let raw): + case .http0(let value, let raw): + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **Int64** | ID of pet to update | + **requiredFile** | **Data** | file to upload | + **additionalMetadata** | **String** | Additional data to pass to server | [optional] + +### Return type + +#### UploadFileWithRequiredFile + +```swift +public enum UploadFileWithRequiredFile { + case http200(value: ApiResponse?, raw: ClientResponse) + case http0(value: ApiResponse?, raw: ClientResponse) +} +``` + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: multipart/form-data + - **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/petstore/swift5/vaporLibrary/docs/ReadOnlyFirst.md b/samples/client/petstore/swift5/vaporLibrary/docs/ReadOnlyFirst.md new file mode 100644 index 00000000000..ed537b87598 --- /dev/null +++ b/samples/client/petstore/swift5/vaporLibrary/docs/ReadOnlyFirst.md @@ -0,0 +1,11 @@ +# ReadOnlyFirst + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**bar** | **String** | | [optional] [readonly] +**baz** | **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/swift5/vaporLibrary/docs/Return.md b/samples/client/petstore/swift5/vaporLibrary/docs/Return.md new file mode 100644 index 00000000000..e310b15bb5b --- /dev/null +++ b/samples/client/petstore/swift5/vaporLibrary/docs/Return.md @@ -0,0 +1,10 @@ +# Return + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**`return`** | **Int** | | [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/swift5/vaporLibrary/docs/SpecialModelName.md b/samples/client/petstore/swift5/vaporLibrary/docs/SpecialModelName.md new file mode 100644 index 00000000000..3ec27a38c2a --- /dev/null +++ b/samples/client/petstore/swift5/vaporLibrary/docs/SpecialModelName.md @@ -0,0 +1,10 @@ +# SpecialModelName + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**specialPropertyName** | **Int64** | | [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/swift5/vaporLibrary/docs/StoreAPI.md b/samples/client/petstore/swift5/vaporLibrary/docs/StoreAPI.md new file mode 100644 index 00000000000..d5d5e28833f --- /dev/null +++ b/samples/client/petstore/swift5/vaporLibrary/docs/StoreAPI.md @@ -0,0 +1,250 @@ +# StoreAPI + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**deleteOrder**](StoreAPI.md#deleteorder) | **DELETE** /store/order/{order_id} | Delete purchase order by ID +[**getInventory**](StoreAPI.md#getinventory) | **GET** /store/inventory | Returns pet inventories by status +[**getOrderById**](StoreAPI.md#getorderbyid) | **GET** /store/order/{order_id} | Find purchase order by ID +[**placeOrder**](StoreAPI.md#placeorder) | **POST** /store/order | Place an order for a pet + + +# **deleteOrder** +```swift + open class func deleteOrder(orderId: String, headers: HTTPHeaders = PetstoreClient.customHeaders, beforeSend: (inout ClientRequest) throws -> () = { _ in }) -> EventLoopFuture +``` + +Delete purchase order by ID + +For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let orderId = "orderId_example" // String | ID of the order that needs to be deleted + +// Delete purchase order by ID +StoreAPI.deleteOrder(orderId: orderId).whenComplete { result in + switch result { + case .failure(let error): + // process error + case .success(let response): + switch response { + // process decoded response value or raw ClientResponse + case .http400(let value, let raw): + case .http404(let value, let raw): + case .http0(let value, let raw): + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **orderId** | **String** | ID of the order that needs to be deleted | + +### Return type + +#### DeleteOrder + +```swift +public enum DeleteOrder { + case http400(value: Void?, raw: ClientResponse) + case http404(value: Void?, raw: ClientResponse) + case http0(value: Void?, raw: ClientResponse) +} +``` + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **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) + +# **getInventory** +```swift + open class func getInventory(headers: HTTPHeaders = PetstoreClient.customHeaders, beforeSend: (inout ClientRequest) throws -> () = { _ in }) -> EventLoopFuture +``` + +Returns pet inventories by status + +Returns a map of status codes to quantities + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + + +// Returns pet inventories by status +StoreAPI.getInventory().whenComplete { result in + switch result { + case .failure(let error): + // process error + case .success(let response): + switch response { + // process decoded response value or raw ClientResponse + case .http200(let value, let raw): + case .http0(let value, let raw): + } + } +} +``` + +### Parameters +This endpoint does not need any parameter. + +### Return type + +#### GetInventory + +```swift +public enum GetInventory { + case http200(value: [String: Int]?, raw: ClientResponse) + case http0(value: [String: Int]?, raw: ClientResponse) +} +``` + +### Authorization + +[api_key](../README.md#api_key) + +### HTTP request headers + + - **Content-Type**: Not defined + - **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) + +# **getOrderById** +```swift + open class func getOrderById(orderId: Int64, headers: HTTPHeaders = PetstoreClient.customHeaders, beforeSend: (inout ClientRequest) throws -> () = { _ in }) -> EventLoopFuture +``` + +Find purchase order by ID + +For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let orderId = 987 // Int64 | ID of pet that needs to be fetched + +// Find purchase order by ID +StoreAPI.getOrderById(orderId: orderId).whenComplete { result in + switch result { + case .failure(let error): + // process error + case .success(let response): + switch response { + // process decoded response value or raw ClientResponse + case .http200(let value, let raw): + case .http400(let value, let raw): + case .http404(let value, let raw): + case .http0(let value, let raw): + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **orderId** | **Int64** | ID of pet that needs to be fetched | + +### Return type + +#### GetOrderById + +```swift +public enum GetOrderById { + case http200(value: Order?, raw: ClientResponse) + case http400(value: Void?, raw: ClientResponse) + case http404(value: Void?, raw: ClientResponse) + case http0(value: Order?, raw: ClientResponse) +} +``` + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **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) + +# **placeOrder** +```swift + open class func placeOrder(body: Order, headers: HTTPHeaders = PetstoreClient.customHeaders, beforeSend: (inout ClientRequest) throws -> () = { _ in }) -> EventLoopFuture +``` + +Place an order for a pet + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let body = Order(id: 123, petId: 123, quantity: 123, shipDate: Date(), status: "status_example", complete: false) // Order | order placed for purchasing the pet + +// Place an order for a pet +StoreAPI.placeOrder(body: body).whenComplete { result in + switch result { + case .failure(let error): + // process error + case .success(let response): + switch response { + // process decoded response value or raw ClientResponse + case .http200(let value, let raw): + case .http400(let value, let raw): + case .http0(let value, let raw): + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**Order**](Order.md) | order placed for purchasing the pet | + +### Return type + +#### PlaceOrder + +```swift +public enum PlaceOrder { + case http200(value: Order?, raw: ClientResponse) + case http400(value: Void?, raw: ClientResponse) + case http0(value: Order?, raw: ClientResponse) +} +``` + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **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/client/petstore/swift5/vaporLibrary/docs/StringBooleanMap.md b/samples/client/petstore/swift5/vaporLibrary/docs/StringBooleanMap.md new file mode 100644 index 00000000000..7abf11ec68b --- /dev/null +++ b/samples/client/petstore/swift5/vaporLibrary/docs/StringBooleanMap.md @@ -0,0 +1,9 @@ +# StringBooleanMap + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +[[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/swift5/vaporLibrary/docs/Tag.md b/samples/client/petstore/swift5/vaporLibrary/docs/Tag.md new file mode 100644 index 00000000000..ff4ac8aa451 --- /dev/null +++ b/samples/client/petstore/swift5/vaporLibrary/docs/Tag.md @@ -0,0 +1,11 @@ +# Tag + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **Int64** | | [optional] +**name** | **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/swift5/vaporLibrary/docs/TypeHolderDefault.md b/samples/client/petstore/swift5/vaporLibrary/docs/TypeHolderDefault.md new file mode 100644 index 00000000000..5161394bdc3 --- /dev/null +++ b/samples/client/petstore/swift5/vaporLibrary/docs/TypeHolderDefault.md @@ -0,0 +1,14 @@ +# TypeHolderDefault + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**stringItem** | **String** | | [default to "what"] +**numberItem** | **Double** | | +**integerItem** | **Int** | | +**boolItem** | **Bool** | | [default to true] +**arrayItem** | **[Int]** | | + +[[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/swift5/vaporLibrary/docs/TypeHolderExample.md b/samples/client/petstore/swift5/vaporLibrary/docs/TypeHolderExample.md new file mode 100644 index 00000000000..c0530dc0e5b --- /dev/null +++ b/samples/client/petstore/swift5/vaporLibrary/docs/TypeHolderExample.md @@ -0,0 +1,15 @@ +# TypeHolderExample + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**stringItem** | **String** | | +**numberItem** | **Double** | | +**floatItem** | **Float** | | +**integerItem** | **Int** | | +**boolItem** | **Bool** | | +**arrayItem** | **[Int]** | | + +[[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/swift5/vaporLibrary/docs/User.md b/samples/client/petstore/swift5/vaporLibrary/docs/User.md new file mode 100644 index 00000000000..5a439de0ff9 --- /dev/null +++ b/samples/client/petstore/swift5/vaporLibrary/docs/User.md @@ -0,0 +1,17 @@ +# User + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **Int64** | | [optional] +**username** | **String** | | [optional] +**firstName** | **String** | | [optional] +**lastName** | **String** | | [optional] +**email** | **String** | | [optional] +**password** | **String** | | [optional] +**phone** | **String** | | [optional] +**userStatus** | **Int** | User Status | [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/swift5/vaporLibrary/docs/UserAPI.md b/samples/client/petstore/swift5/vaporLibrary/docs/UserAPI.md new file mode 100644 index 00000000000..1d6e94e0431 --- /dev/null +++ b/samples/client/petstore/swift5/vaporLibrary/docs/UserAPI.md @@ -0,0 +1,480 @@ +# UserAPI + +All URIs are relative to *http://petstore.swagger.io:80/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** +```swift + open class func createUser(body: User, headers: HTTPHeaders = PetstoreClient.customHeaders, beforeSend: (inout ClientRequest) throws -> () = { _ in }) -> EventLoopFuture +``` + +Create user + +This can only be done by the logged in user. + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let body = User(id: 123, username: "username_example", firstName: "firstName_example", lastName: "lastName_example", email: "email_example", password: "password_example", phone: "phone_example", userStatus: 123) // User | Created user object + +// Create user +UserAPI.createUser(body: body).whenComplete { result in + switch result { + case .failure(let error): + // process error + case .success(let response): + switch response { + // process decoded response value or raw ClientResponse + case .http0(let value, let raw): + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**User**](User.md) | Created user object | + +### Return type + +#### CreateUser + +```swift +public enum CreateUser { + case http0(value: Void?, raw: ClientResponse) +} +``` + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **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) + +# **createUsersWithArrayInput** +```swift + open class func createUsersWithArrayInput(body: [User], headers: HTTPHeaders = PetstoreClient.customHeaders, beforeSend: (inout ClientRequest) throws -> () = { _ in }) -> EventLoopFuture +``` + +Creates list of users with given input array + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let body = [User(id: 123, username: "username_example", firstName: "firstName_example", lastName: "lastName_example", email: "email_example", password: "password_example", phone: "phone_example", userStatus: 123)] // [User] | List of user object + +// Creates list of users with given input array +UserAPI.createUsersWithArrayInput(body: body).whenComplete { result in + switch result { + case .failure(let error): + // process error + case .success(let response): + switch response { + // process decoded response value or raw ClientResponse + case .http0(let value, let raw): + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**[User]**](User.md) | List of user object | + +### Return type + +#### CreateUsersWithArrayInput + +```swift +public enum CreateUsersWithArrayInput { + case http0(value: Void?, raw: ClientResponse) +} +``` + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **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) + +# **createUsersWithListInput** +```swift + open class func createUsersWithListInput(body: [User], headers: HTTPHeaders = PetstoreClient.customHeaders, beforeSend: (inout ClientRequest) throws -> () = { _ in }) -> EventLoopFuture +``` + +Creates list of users with given input array + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let body = [User(id: 123, username: "username_example", firstName: "firstName_example", lastName: "lastName_example", email: "email_example", password: "password_example", phone: "phone_example", userStatus: 123)] // [User] | List of user object + +// Creates list of users with given input array +UserAPI.createUsersWithListInput(body: body).whenComplete { result in + switch result { + case .failure(let error): + // process error + case .success(let response): + switch response { + // process decoded response value or raw ClientResponse + case .http0(let value, let raw): + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**[User]**](User.md) | List of user object | + +### Return type + +#### CreateUsersWithListInput + +```swift +public enum CreateUsersWithListInput { + case http0(value: Void?, raw: ClientResponse) +} +``` + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **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) + +# **deleteUser** +```swift + open class func deleteUser(username: String, headers: HTTPHeaders = PetstoreClient.customHeaders, beforeSend: (inout ClientRequest) throws -> () = { _ in }) -> EventLoopFuture +``` + +Delete user + +This can only be done by the logged in user. + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let username = "username_example" // String | The name that needs to be deleted + +// Delete user +UserAPI.deleteUser(username: username).whenComplete { result in + switch result { + case .failure(let error): + // process error + case .success(let response): + switch response { + // process decoded response value or raw ClientResponse + case .http400(let value, let raw): + case .http404(let value, let raw): + case .http0(let value, let raw): + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **String** | The name that needs to be deleted | + +### Return type + +#### DeleteUser + +```swift +public enum DeleteUser { + case http400(value: Void?, raw: ClientResponse) + case http404(value: Void?, raw: ClientResponse) + case http0(value: Void?, raw: ClientResponse) +} +``` + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **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) + +# **getUserByName** +```swift + open class func getUserByName(username: String, headers: HTTPHeaders = PetstoreClient.customHeaders, beforeSend: (inout ClientRequest) throws -> () = { _ in }) -> EventLoopFuture +``` + +Get user by user name + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let username = "username_example" // String | The name that needs to be fetched. Use user1 for testing. + +// Get user by user name +UserAPI.getUserByName(username: username).whenComplete { result in + switch result { + case .failure(let error): + // process error + case .success(let response): + switch response { + // process decoded response value or raw ClientResponse + case .http200(let value, let raw): + case .http400(let value, let raw): + case .http404(let value, let raw): + case .http0(let value, let raw): + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **String** | The name that needs to be fetched. Use user1 for testing. | + +### Return type + +#### GetUserByName + +```swift +public enum GetUserByName { + case http200(value: User?, raw: ClientResponse) + case http400(value: Void?, raw: ClientResponse) + case http404(value: Void?, raw: ClientResponse) + case http0(value: User?, raw: ClientResponse) +} +``` + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **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) + +# **loginUser** +```swift + open class func loginUser(username: String, password: String, headers: HTTPHeaders = PetstoreClient.customHeaders, beforeSend: (inout ClientRequest) throws -> () = { _ in }) -> EventLoopFuture +``` + +Logs user into the system + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let username = "username_example" // String | The user name for login +let password = "password_example" // String | The password for login in clear text + +// Logs user into the system +UserAPI.loginUser(username: username, password: password).whenComplete { result in + switch result { + case .failure(let error): + // process error + case .success(let response): + switch response { + // process decoded response value or raw ClientResponse + case .http200(let value, let raw): + case .http400(let value, let raw): + case .http0(let value, let raw): + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **String** | The user name for login | + **password** | **String** | The password for login in clear text | + +### Return type + +#### LoginUser + +```swift +public enum LoginUser { + case http200(value: String?, raw: ClientResponse) + case http400(value: Void?, raw: ClientResponse) + case http0(value: String?, raw: ClientResponse) +} +``` + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **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) + +# **logoutUser** +```swift + open class func logoutUser(headers: HTTPHeaders = PetstoreClient.customHeaders, beforeSend: (inout ClientRequest) throws -> () = { _ in }) -> EventLoopFuture +``` + +Logs out current logged in user session + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + + +// Logs out current logged in user session +UserAPI.logoutUser().whenComplete { result in + switch result { + case .failure(let error): + // process error + case .success(let response): + switch response { + // process decoded response value or raw ClientResponse + case .http0(let value, let raw): + } + } +} +``` + +### Parameters +This endpoint does not need any parameter. + +### Return type + +#### LogoutUser + +```swift +public enum LogoutUser { + case http0(value: Void?, raw: ClientResponse) +} +``` + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **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) + +# **updateUser** +```swift + open class func updateUser(username: String, body: User, headers: HTTPHeaders = PetstoreClient.customHeaders, beforeSend: (inout ClientRequest) throws -> () = { _ in }) -> EventLoopFuture +``` + +Updated user + +This can only be done by the logged in user. + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let username = "username_example" // String | name that need to be deleted +let body = User(id: 123, username: "username_example", firstName: "firstName_example", lastName: "lastName_example", email: "email_example", password: "password_example", phone: "phone_example", userStatus: 123) // User | Updated user object + +// Updated user +UserAPI.updateUser(username: username, body: body).whenComplete { result in + switch result { + case .failure(let error): + // process error + case .success(let response): + switch response { + // process decoded response value or raw ClientResponse + case .http400(let value, let raw): + case .http404(let value, let raw): + case .http0(let value, let raw): + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **String** | name that need to be deleted | + **body** | [**User**](User.md) | Updated user object | + +### Return type + +#### UpdateUser + +```swift +public enum UpdateUser { + case http400(value: Void?, raw: ClientResponse) + case http404(value: Void?, raw: ClientResponse) + case http0(value: Void?, raw: ClientResponse) +} +``` + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **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) + diff --git a/samples/client/petstore/swift5/vaporLibrary/docs/XmlItem.md b/samples/client/petstore/swift5/vaporLibrary/docs/XmlItem.md new file mode 100644 index 00000000000..1a4eb4e9c83 --- /dev/null +++ b/samples/client/petstore/swift5/vaporLibrary/docs/XmlItem.md @@ -0,0 +1,38 @@ +# XmlItem + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**attributeString** | **String** | | [optional] +**attributeNumber** | **Double** | | [optional] +**attributeInteger** | **Int** | | [optional] +**attributeBoolean** | **Bool** | | [optional] +**wrappedArray** | **[Int]** | | [optional] +**nameString** | **String** | | [optional] +**nameNumber** | **Double** | | [optional] +**nameInteger** | **Int** | | [optional] +**nameBoolean** | **Bool** | | [optional] +**nameArray** | **[Int]** | | [optional] +**nameWrappedArray** | **[Int]** | | [optional] +**prefixString** | **String** | | [optional] +**prefixNumber** | **Double** | | [optional] +**prefixInteger** | **Int** | | [optional] +**prefixBoolean** | **Bool** | | [optional] +**prefixArray** | **[Int]** | | [optional] +**prefixWrappedArray** | **[Int]** | | [optional] +**namespaceString** | **String** | | [optional] +**namespaceNumber** | **Double** | | [optional] +**namespaceInteger** | **Int** | | [optional] +**namespaceBoolean** | **Bool** | | [optional] +**namespaceArray** | **[Int]** | | [optional] +**namespaceWrappedArray** | **[Int]** | | [optional] +**prefixNsString** | **String** | | [optional] +**prefixNsNumber** | **Double** | | [optional] +**prefixNsInteger** | **Int** | | [optional] +**prefixNsBoolean** | **Bool** | | [optional] +**prefixNsArray** | **[Int]** | | [optional] +**prefixNsWrappedArray** | **[Int]** | | [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/swift5/vaporLibrary/pom.xml b/samples/client/petstore/swift5/vaporLibrary/pom.xml new file mode 100644 index 00000000000..c1b201eb3b4 --- /dev/null +++ b/samples/client/petstore/swift5/vaporLibrary/pom.xml @@ -0,0 +1,43 @@ + + 4.0.0 + io.swagger + Swift5PetstoreClientTests + pom + 1.0-SNAPSHOT + Swift5 Swagger Petstore Client + + + + maven-dependency-plugin + + + package + + copy-dependencies + + + ${project.build.directory} + + + + + + org.codehaus.mojo + exec-maven-plugin + 1.2.1 + + + xcodebuild-test + integration-test + + exec + + + ./run_spmbuild.sh + + + + + + + diff --git a/samples/client/petstore/swift5/vaporLibrary/run_spmbuild.sh b/samples/client/petstore/swift5/vaporLibrary/run_spmbuild.sh new file mode 100755 index 00000000000..1a9f585ad05 --- /dev/null +++ b/samples/client/petstore/swift5/vaporLibrary/run_spmbuild.sh @@ -0,0 +1,3 @@ +#!/bin/sh + +swift build && exit ${PIPESTATUS[0]} diff --git a/samples/client/petstore/swift5/x-swift-hashable/.gitignore b/samples/client/petstore/swift5/x-swift-hashable/.gitignore new file mode 100644 index 00000000000..627d360a903 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/.gitignore @@ -0,0 +1,105 @@ +# Created by https://www.toptal.com/developers/gitignore/api/swift,xcode +# Edit at https://www.toptal.com/developers/gitignore?templates=swift,xcode + +### Swift ### +# Xcode +# +# gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore + +## User settings +xcuserdata/ + +## compatibility with Xcode 8 and earlier (ignoring not required starting Xcode 9) +*.xcscmblueprint +*.xccheckout + +## compatibility with Xcode 3 and earlier (ignoring not required starting Xcode 4) +build/ +DerivedData/ +*.moved-aside +*.pbxuser +!default.pbxuser +*.mode1v3 +!default.mode1v3 +*.mode2v3 +!default.mode2v3 +*.perspectivev3 +!default.perspectivev3 + +## Obj-C/Swift specific +*.hmap + +## App packaging +*.ipa +*.dSYM.zip +*.dSYM + +## Playgrounds +timeline.xctimeline +playground.xcworkspace + +# Swift Package Manager +# Add this line if you want to avoid checking in source code from Swift Package Manager dependencies. +# Packages/ +# Package.pins +# Package.resolved +# *.xcodeproj +# Xcode automatically generates this directory with a .xcworkspacedata file and xcuserdata +# hence it is not needed unless you have added a package configuration file to your project +# .swiftpm + +.build/ + +# CocoaPods +# We recommend against adding the Pods directory to your .gitignore. However +# you should judge for yourself, the pros and cons are mentioned at: +# https://guides.cocoapods.org/using/using-cocoapods.html#should-i-check-the-pods-directory-into-source-control +# Pods/ +# Add this line if you want to avoid checking in source code from the Xcode workspace +# *.xcworkspace + +# Carthage +# Add this line if you want to avoid checking in source code from Carthage dependencies. +# Carthage/Checkouts + +Carthage/Build/ + +# Add this lines if you are using Accio dependency management (Deprecated since Xcode 12) +# Dependencies/ +# .accio/ + +# fastlane +# It is recommended to not store the screenshots in the git repo. +# Instead, use fastlane to re-generate the screenshots whenever they are needed. +# For more information about the recommended setup visit: +# https://docs.fastlane.tools/best-practices/source-control/#source-control + +fastlane/report.xml +fastlane/Preview.html +fastlane/screenshots/**/*.png +fastlane/test_output + +# Code Injection +# After new code Injection tools there's a generated folder /iOSInjectionProject +# https://github.com/johnno1962/injectionforxcode + +iOSInjectionProject/ + +### Xcode ### +# Xcode +# gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore + + + + +## Gcc Patch +/*.gcno + +### Xcode Patch ### +*.xcodeproj/* +!*.xcodeproj/project.pbxproj +!*.xcodeproj/xcshareddata/ +!*.xcworkspace/contents.xcworkspacedata +**/xcshareddata/WorkspaceSettings.xcsettings + +# End of https://www.toptal.com/developers/gitignore/api/swift,xcode diff --git a/samples/client/petstore/swift5/x-swift-hashable/.openapi-generator-ignore b/samples/client/petstore/swift5/x-swift-hashable/.openapi-generator-ignore new file mode 100644 index 00000000000..7484ee590a3 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/.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/swift5/x-swift-hashable/.openapi-generator/FILES b/samples/client/petstore/swift5/x-swift-hashable/.openapi-generator/FILES new file mode 100644 index 00000000000..c81943baf2a --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/.openapi-generator/FILES @@ -0,0 +1,110 @@ +.gitignore +Cartfile +Package.swift +PetstoreClient.podspec +PetstoreClient/Classes/OpenAPIs/APIHelper.swift +PetstoreClient/Classes/OpenAPIs/APIs.swift +PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift +PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift +PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift +PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift +PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift +PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift +PetstoreClient/Classes/OpenAPIs/CodableHelper.swift +PetstoreClient/Classes/OpenAPIs/Configuration.swift +PetstoreClient/Classes/OpenAPIs/Extensions.swift +PetstoreClient/Classes/OpenAPIs/JSONDataEncoding.swift +PetstoreClient/Classes/OpenAPIs/JSONEncodingHelper.swift +PetstoreClient/Classes/OpenAPIs/Models.swift +PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesClass.swift +PetstoreClient/Classes/OpenAPIs/Models/Animal.swift +PetstoreClient/Classes/OpenAPIs/Models/AnimalFarm.swift +PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift +PetstoreClient/Classes/OpenAPIs/Models/ArrayOfArrayOfNumberOnly.swift +PetstoreClient/Classes/OpenAPIs/Models/ArrayOfNumberOnly.swift +PetstoreClient/Classes/OpenAPIs/Models/ArrayTest.swift +PetstoreClient/Classes/OpenAPIs/Models/Capitalization.swift +PetstoreClient/Classes/OpenAPIs/Models/Cat.swift +PetstoreClient/Classes/OpenAPIs/Models/CatAllOf.swift +PetstoreClient/Classes/OpenAPIs/Models/Category.swift +PetstoreClient/Classes/OpenAPIs/Models/ClassModel.swift +PetstoreClient/Classes/OpenAPIs/Models/Client.swift +PetstoreClient/Classes/OpenAPIs/Models/Dog.swift +PetstoreClient/Classes/OpenAPIs/Models/DogAllOf.swift +PetstoreClient/Classes/OpenAPIs/Models/EnumArrays.swift +PetstoreClient/Classes/OpenAPIs/Models/EnumClass.swift +PetstoreClient/Classes/OpenAPIs/Models/EnumTest.swift +PetstoreClient/Classes/OpenAPIs/Models/File.swift +PetstoreClient/Classes/OpenAPIs/Models/FileSchemaTestClass.swift +PetstoreClient/Classes/OpenAPIs/Models/FormatTest.swift +PetstoreClient/Classes/OpenAPIs/Models/HasOnlyReadOnly.swift +PetstoreClient/Classes/OpenAPIs/Models/List.swift +PetstoreClient/Classes/OpenAPIs/Models/MapTest.swift +PetstoreClient/Classes/OpenAPIs/Models/MixedPropertiesAndAdditionalPropertiesClass.swift +PetstoreClient/Classes/OpenAPIs/Models/Model200Response.swift +PetstoreClient/Classes/OpenAPIs/Models/Name.swift +PetstoreClient/Classes/OpenAPIs/Models/NumberOnly.swift +PetstoreClient/Classes/OpenAPIs/Models/Order.swift +PetstoreClient/Classes/OpenAPIs/Models/OuterComposite.swift +PetstoreClient/Classes/OpenAPIs/Models/OuterEnum.swift +PetstoreClient/Classes/OpenAPIs/Models/Pet.swift +PetstoreClient/Classes/OpenAPIs/Models/ReadOnlyFirst.swift +PetstoreClient/Classes/OpenAPIs/Models/Return.swift +PetstoreClient/Classes/OpenAPIs/Models/SpecialModelName.swift +PetstoreClient/Classes/OpenAPIs/Models/StringBooleanMap.swift +PetstoreClient/Classes/OpenAPIs/Models/Tag.swift +PetstoreClient/Classes/OpenAPIs/Models/TypeHolderDefault.swift +PetstoreClient/Classes/OpenAPIs/Models/TypeHolderExample.swift +PetstoreClient/Classes/OpenAPIs/Models/User.swift +PetstoreClient/Classes/OpenAPIs/OpenISO8601DateFormatter.swift +PetstoreClient/Classes/OpenAPIs/SynchronizedDictionary.swift +PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift +README.md +docs/AdditionalPropertiesClass.md +docs/Animal.md +docs/AnimalFarm.md +docs/AnotherFakeAPI.md +docs/ApiResponse.md +docs/ArrayOfArrayOfNumberOnly.md +docs/ArrayOfNumberOnly.md +docs/ArrayTest.md +docs/Capitalization.md +docs/Cat.md +docs/CatAllOf.md +docs/Category.md +docs/ClassModel.md +docs/Client.md +docs/Dog.md +docs/DogAllOf.md +docs/EnumArrays.md +docs/EnumClass.md +docs/EnumTest.md +docs/FakeAPI.md +docs/FakeClassnameTags123API.md +docs/File.md +docs/FileSchemaTestClass.md +docs/FormatTest.md +docs/HasOnlyReadOnly.md +docs/List.md +docs/MapTest.md +docs/MixedPropertiesAndAdditionalPropertiesClass.md +docs/Model200Response.md +docs/Name.md +docs/NumberOnly.md +docs/Order.md +docs/OuterComposite.md +docs/OuterEnum.md +docs/Pet.md +docs/PetAPI.md +docs/ReadOnlyFirst.md +docs/Return.md +docs/SpecialModelName.md +docs/StoreAPI.md +docs/StringBooleanMap.md +docs/Tag.md +docs/TypeHolderDefault.md +docs/TypeHolderExample.md +docs/User.md +docs/UserAPI.md +git_push.sh +project.yml diff --git a/samples/client/petstore/swift5/x-swift-hashable/.openapi-generator/VERSION b/samples/client/petstore/swift5/x-swift-hashable/.openapi-generator/VERSION new file mode 100644 index 00000000000..4b448de535c --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/.openapi-generator/VERSION @@ -0,0 +1 @@ +5.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/swift5/x-swift-hashable/.swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata b/samples/client/petstore/swift5/x-swift-hashable/.swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata new file mode 100644 index 00000000000..919434a6254 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/.swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/samples/client/petstore/swift5/x-swift-hashable/Cartfile b/samples/client/petstore/swift5/x-swift-hashable/Cartfile new file mode 100644 index 00000000000..a6a6bcacb1d --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/Cartfile @@ -0,0 +1,2 @@ + +github "Flight-School/AnyCodable" ~> 0.6.1 diff --git a/samples/client/petstore/swift5/x-swift-hashable/Package.resolved b/samples/client/petstore/swift5/x-swift-hashable/Package.resolved new file mode 100644 index 00000000000..79610c3b3b3 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/Package.resolved @@ -0,0 +1,16 @@ +{ + "object": { + "pins": [ + { + "package": "AnyCodable", + "repositoryURL": "https://github.com/Flight-School/AnyCodable", + "state": { + "branch": null, + "revision": "69261f239f0fffaf51495dadc4f8483fbfe97025", + "version": "0.6.1" + } + } + ] + }, + "version": 1 +} diff --git a/samples/client/petstore/swift5/x-swift-hashable/Package.swift b/samples/client/petstore/swift5/x-swift-hashable/Package.swift new file mode 100644 index 00000000000..87bb775fb72 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/Package.swift @@ -0,0 +1,33 @@ +// swift-tools-version:5.1 + +import PackageDescription + +let package = Package( + name: "PetstoreClient", + platforms: [ + .iOS(.v9), + .macOS(.v10_11), + .tvOS(.v9), + .watchOS(.v3), + ], + products: [ + // Products define the executables and libraries produced by a package, and make them visible to other packages. + .library( + name: "PetstoreClient", + targets: ["PetstoreClient"] + ), + ], + dependencies: [ + // Dependencies declare other packages that this package depends on. + .package(url: "https://github.com/Flight-School/AnyCodable", from: "0.6.1"), + ], + targets: [ + // Targets are the basic building blocks of a package. A target can define a module or a test suite. + // Targets can depend on other targets in this package, and on products in packages which this package depends on. + .target( + name: "PetstoreClient", + dependencies: ["AnyCodable", ], + path: "PetstoreClient/Classes" + ), + ] +) diff --git a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient.podspec b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient.podspec new file mode 100644 index 00000000000..0e6bf7ec024 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient.podspec @@ -0,0 +1,15 @@ +Pod::Spec.new do |s| + s.name = 'PetstoreClient' + s.ios.deployment_target = '9.0' + s.osx.deployment_target = '10.11' + s.tvos.deployment_target = '9.0' + s.watchos.deployment_target = '3.0' + s.version = '1.0.0' + s.source = { :git => 'git@github.com:OpenAPITools/openapi-generator.git', :tag => 'v1.0.0' } + s.authors = '' + s.license = 'Proprietary' + s.homepage = 'https://github.com/openapitools/openapi-generator' + s.summary = 'PetstoreClient' + s.source_files = 'PetstoreClient/Classes/**/*.swift' + s.dependency 'AnyCodable-FlightSchool', '~> 0.6.1' +end diff --git a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/APIHelper.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/APIHelper.swift new file mode 100644 index 00000000000..f7bb5274bd9 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/APIHelper.swift @@ -0,0 +1,71 @@ +// APIHelper.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation + +public struct APIHelper { + public static func rejectNil(_ source: [String: Any?]) -> [String: Any]? { + let destination = source.reduce(into: [String: Any]()) { result, item in + if let value = item.value { + result[item.key] = value + } + } + + if destination.isEmpty { + return nil + } + return destination + } + + public static func rejectNilHeaders(_ source: [String: Any?]) -> [String: String] { + return source.reduce(into: [String: String]()) { result, item in + if let collection = item.value as? [Any?] { + result[item.key] = collection.filter { $0 != nil }.map { "\($0!)" }.joined(separator: ",") + } else if let value: Any = item.value { + result[item.key] = "\(value)" + } + } + } + + public static func convertBoolToString(_ source: [String: Any]?) -> [String: Any]? { + guard let source = source else { + return nil + } + + return source.reduce(into: [String: Any]()) { result, item in + switch item.value { + case let x as Bool: + result[item.key] = x.description + default: + result[item.key] = item.value + } + } + } + + public static func mapValueToPathItem(_ source: Any) -> Any { + if let collection = source as? [Any?] { + return collection.filter { $0 != nil }.map { "\($0!)" }.joined(separator: ",") + } + return source + } + + public static func mapValuesToQueryItems(_ source: [String: Any?]) -> [URLQueryItem]? { + let destination = source.filter { $0.value != nil }.reduce(into: [URLQueryItem]()) { result, item in + if let collection = item.value as? [Any?] { + collection.filter { $0 != nil }.map { "\($0!)" }.forEach { value in + result.append(URLQueryItem(name: item.key, value: value)) + } + } else if let value = item.value { + result.append(URLQueryItem(name: item.key, value: "\(value)")) + } + } + + if destination.isEmpty { + return nil + } + return destination + } +} diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/APIs.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/APIs.swift similarity index 85% rename from samples/client/petstore/swift5/urlsessionLibrary/Sources/APIs.swift rename to samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/APIs.swift index dbdab491ff7..941c61b713a 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/Sources/APIs.swift +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/APIs.swift @@ -6,10 +6,13 @@ import Foundation -open class PetstoreClientAPI { +@available(*, deprecated, renamed: "PetstoreClient") +public typealias PetstoreClientAPI = PetstoreClient + +open class PetstoreClient { public static var basePath = "http://petstore.swagger.io:80/v2" - public static var credential: URLCredential? public static var customHeaders: [String: String] = [:] + public static var credential: URLCredential? public static var requestBuilderFactory: RequestBuilderFactory = URLSessionRequestBuilderFactory() public static var apiResponseQueue: DispatchQueue = .main } @@ -32,7 +35,7 @@ open class RequestBuilder { self.parameters = parameters self.headers = headers - addHeaders(PetstoreClientAPI.customHeaders) + addHeaders(PetstoreClient.customHeaders) } open func addHeaders(_ aHeaders: [String: String]) { @@ -41,7 +44,7 @@ open class RequestBuilder { } } - open func execute(_ apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, _ completion: @escaping (_ result: Swift.Result, Error>) -> Void) { } + open func execute(_ apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, _ completion: @escaping (_ result: Swift.Result, Error>) -> Void) { } public func addHeader(name: String, value: String) -> Self { if !value.isEmpty { @@ -51,7 +54,7 @@ open class RequestBuilder { } open func addCredential() -> Self { - credential = PetstoreClientAPI.credential + credential = PetstoreClient.credential return self } } diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/APIs/AnotherFakeAPI.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift similarity index 53% rename from samples/client/petstore/swift5/urlsessionLibrary/Sources/APIs/AnotherFakeAPI.swift rename to samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift index 72b89640eeb..ac9dd9b74f2 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/Sources/APIs/AnotherFakeAPI.swift +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift @@ -6,8 +6,12 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif open class AnotherFakeAPI { + /** To test special tags @@ -15,7 +19,7 @@ open class AnotherFakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func call123testSpecialTags(body: Client, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Client?, _ error: Error?) -> Void)) { + open class func call123testSpecialTags(body: Client, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Client?, _ error: Error?) -> Void)) { call123testSpecialTagsWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -34,21 +38,20 @@ open class AnotherFakeAPI { - returns: RequestBuilder */ open class func call123testSpecialTagsWithRequestBuilder(body: Client) -> RequestBuilder { - let path = "/another-fake/dummy" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/another-fake/dummy" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "PATCH", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "PATCH", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } - } diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/APIs/FakeAPI.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift similarity index 64% rename from samples/client/petstore/swift5/urlsessionLibrary/Sources/APIs/FakeAPI.swift rename to samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift index cf92424d9cc..d7260ca2e3a 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/Sources/APIs/FakeAPI.swift +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift @@ -6,15 +6,19 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif open class FakeAPI { + /** - parameter body: (body) Input boolean as post body (optional) - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func fakeOuterBooleanSerialize(body: Bool? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Bool?, _ error: Error?) -> Void)) { + open class func fakeOuterBooleanSerialize(body: Bool? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Bool?, _ error: Error?) -> Void)) { fakeOuterBooleanSerializeWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -32,21 +36,21 @@ open class FakeAPI { - returns: RequestBuilder */ open class func fakeOuterBooleanSerializeWithRequestBuilder(body: Bool? = nil) -> RequestBuilder { - let path = "/fake/outer/boolean" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/fake/outer/boolean" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -55,7 +59,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func fakeOuterCompositeSerialize(body: OuterComposite? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: OuterComposite?, _ error: Error?) -> Void)) { + open class func fakeOuterCompositeSerialize(body: OuterComposite? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: OuterComposite?, _ error: Error?) -> Void)) { fakeOuterCompositeSerializeWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -73,21 +77,21 @@ open class FakeAPI { - returns: RequestBuilder */ open class func fakeOuterCompositeSerializeWithRequestBuilder(body: OuterComposite? = nil) -> RequestBuilder { - let path = "/fake/outer/composite" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/fake/outer/composite" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -96,7 +100,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func fakeOuterNumberSerialize(body: Double? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Double?, _ error: Error?) -> Void)) { + open class func fakeOuterNumberSerialize(body: Double? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Double?, _ error: Error?) -> Void)) { fakeOuterNumberSerializeWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -114,21 +118,21 @@ open class FakeAPI { - returns: RequestBuilder */ open class func fakeOuterNumberSerializeWithRequestBuilder(body: Double? = nil) -> RequestBuilder { - let path = "/fake/outer/number" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/fake/outer/number" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -137,7 +141,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func fakeOuterStringSerialize(body: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: String?, _ error: Error?) -> Void)) { + open class func fakeOuterStringSerialize(body: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: String?, _ error: Error?) -> Void)) { fakeOuterStringSerializeWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -155,21 +159,21 @@ open class FakeAPI { - returns: RequestBuilder */ open class func fakeOuterStringSerializeWithRequestBuilder(body: String? = nil) -> RequestBuilder { - let path = "/fake/outer/string" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/fake/outer/string" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -178,7 +182,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func testBodyWithFileSchema(body: FileSchemaTestClass, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func testBodyWithFileSchema(body: FileSchemaTestClass, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { testBodyWithFileSchemaWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -196,21 +200,21 @@ open class FakeAPI { - returns: RequestBuilder */ open class func testBodyWithFileSchemaWithRequestBuilder(body: FileSchemaTestClass) -> RequestBuilder { - let path = "/fake/body-with-file-schema" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/fake/body-with-file-schema" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "PUT", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -220,7 +224,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func testBodyWithQueryParams(query: String, body: User, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func testBodyWithQueryParams(query: String, body: User, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { testBodyWithQueryParamsWithRequestBuilder(query: query, body: body).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -238,24 +242,24 @@ open class FakeAPI { - returns: RequestBuilder */ open class func testBodyWithQueryParamsWithRequestBuilder(query: String, body: User) -> RequestBuilder { - let path = "/fake/body-with-query-params" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/fake/body-with-query-params" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - var urlComponents = URLComponents(string: URLString) - urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ + var localVariableUrlComponents = URLComponents(string: localVariableURLString) + localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ "query": query.encodeToJSON(), ]) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "PUT", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -265,7 +269,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func testClientModel(body: Client, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Client?, _ error: Error?) -> Void)) { + open class func testClientModel(body: Client, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Client?, _ error: Error?) -> Void)) { testClientModelWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -284,21 +288,21 @@ open class FakeAPI { - returns: RequestBuilder */ open class func testClientModelWithRequestBuilder(body: Client) -> RequestBuilder { - let path = "/fake" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/fake" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "PATCH", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "PATCH", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -321,7 +325,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func testEndpointParameters(number: Double, double: Double, patternWithoutDelimiter: String, byte: Data, integer: Int? = nil, int32: Int? = nil, int64: Int64? = nil, float: Float? = nil, string: String? = nil, binary: URL? = nil, date: Date? = nil, dateTime: Date? = nil, password: String? = nil, callback: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func testEndpointParameters(number: Double, double: Double, patternWithoutDelimiter: String, byte: Data, integer: Int? = nil, int32: Int? = nil, int64: Int64? = nil, float: Float? = nil, string: String? = nil, binary: URL? = nil, date: Date? = nil, dateTime: Date? = nil, password: String? = nil, callback: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { testEndpointParametersWithRequestBuilder(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(apiResponseQueue) { result -> Void in switch result { case .success: @@ -356,9 +360,9 @@ open class FakeAPI { - returns: RequestBuilder */ open class func testEndpointParametersWithRequestBuilder(number: Double, double: Double, patternWithoutDelimiter: String, byte: Data, integer: Int? = nil, int32: Int? = nil, int64: Int64? = nil, float: Float? = nil, string: String? = nil, binary: URL? = nil, date: Date? = nil, dateTime: Date? = nil, password: String? = nil, callback: String? = nil) -> RequestBuilder { - let path = "/fake" - let URLString = PetstoreClientAPI.basePath + path - let formParams: [String: Any?] = [ + let localVariablePath = "/fake" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableFormParams: [String: Any?] = [ "integer": integer?.encodeToJSON(), "int32": int32?.encodeToJSON(), "int64": int64?.encodeToJSON(), @@ -375,20 +379,20 @@ open class FakeAPI { "callback": callback?.encodeToJSON(), ] - let nonNullParameters = APIHelper.rejectNil(formParams) - let parameters = APIHelper.convertBoolToString(nonNullParameters) + let localVariableNonNullParameters = APIHelper.rejectNil(localVariableFormParams) + let localVariableParameters = APIHelper.convertBoolToString(localVariableNonNullParameters) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ "Content-Type": "application/x-www-form-urlencoded", ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -472,7 +476,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func testEnumParameters(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func testEnumParameters(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { testEnumParametersWithRequestBuilder(enumHeaderStringArray: enumHeaderStringArray, enumHeaderString: enumHeaderString, enumQueryStringArray: enumQueryStringArray, enumQueryString: enumQueryString, enumQueryInteger: enumQueryInteger, enumQueryDouble: enumQueryDouble, enumFormStringArray: enumFormStringArray, enumFormString: enumFormString).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -498,35 +502,35 @@ open class FakeAPI { - returns: RequestBuilder */ open class func testEnumParametersWithRequestBuilder(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil) -> RequestBuilder { - let path = "/fake" - let URLString = PetstoreClientAPI.basePath + path - let formParams: [String: Any?] = [ + let localVariablePath = "/fake" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableFormParams: [String: Any?] = [ "enum_form_string_array": enumFormStringArray?.encodeToJSON(), "enum_form_string": enumFormString?.encodeToJSON(), ] - let nonNullParameters = APIHelper.rejectNil(formParams) - let parameters = APIHelper.convertBoolToString(nonNullParameters) + let localVariableNonNullParameters = APIHelper.rejectNil(localVariableFormParams) + let localVariableParameters = APIHelper.convertBoolToString(localVariableNonNullParameters) - var urlComponents = URLComponents(string: URLString) - urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ + var localVariableUrlComponents = URLComponents(string: localVariableURLString) + localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ "enum_query_string_array": enumQueryStringArray?.encodeToJSON(), "enum_query_string": enumQueryString?.encodeToJSON(), "enum_query_integer": enumQueryInteger?.encodeToJSON(), "enum_query_double": enumQueryDouble?.encodeToJSON(), ]) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ "Content-Type": "application/x-www-form-urlencoded", "enum_header_string_array": enumHeaderStringArray?.encodeToJSON(), "enum_header_string": enumHeaderString?.encodeToJSON(), ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -541,7 +545,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func testGroupParameters(requiredStringGroup: Int, requiredBooleanGroup: Bool, requiredInt64Group: Int64, stringGroup: Int? = nil, booleanGroup: Bool? = nil, int64Group: Int64? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func testGroupParameters(requiredStringGroup: Int, requiredBooleanGroup: Bool, requiredInt64Group: Int64, stringGroup: Int? = nil, booleanGroup: Bool? = nil, int64Group: Int64? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { testGroupParametersWithRequestBuilder(requiredStringGroup: requiredStringGroup, requiredBooleanGroup: requiredBooleanGroup, requiredInt64Group: requiredInt64Group, stringGroup: stringGroup, booleanGroup: booleanGroup, int64Group: int64Group).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -565,28 +569,28 @@ open class FakeAPI { - returns: RequestBuilder */ open class func testGroupParametersWithRequestBuilder(requiredStringGroup: Int, requiredBooleanGroup: Bool, requiredInt64Group: Int64, stringGroup: Int? = nil, booleanGroup: Bool? = nil, int64Group: Int64? = nil) -> RequestBuilder { - let path = "/fake" - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + let localVariablePath = "/fake" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - var urlComponents = URLComponents(string: URLString) - urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ + var localVariableUrlComponents = URLComponents(string: localVariableURLString) + localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ "required_string_group": requiredStringGroup.encodeToJSON(), "required_int64_group": requiredInt64Group.encodeToJSON(), "string_group": stringGroup?.encodeToJSON(), "int64_group": int64Group?.encodeToJSON(), ]) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ "required_boolean_group": requiredBooleanGroup.encodeToJSON(), "boolean_group": booleanGroup?.encodeToJSON(), ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "DELETE", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -596,7 +600,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func testInlineAdditionalProperties(param: [String: String], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func testInlineAdditionalProperties(param: [String: String], apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { testInlineAdditionalPropertiesWithRequestBuilder(param: param).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -614,21 +618,21 @@ open class FakeAPI { - returns: RequestBuilder */ open class func testInlineAdditionalPropertiesWithRequestBuilder(param: [String: String]) -> RequestBuilder { - let path = "/fake/inline-additionalProperties" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: param) + let localVariablePath = "/fake/inline-additionalProperties" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: param) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -639,7 +643,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func testJsonFormData(param: String, param2: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func testJsonFormData(param: String, param2: String, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { testJsonFormDataWithRequestBuilder(param: param, param2: param2).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -658,27 +662,26 @@ open class FakeAPI { - returns: RequestBuilder */ open class func testJsonFormDataWithRequestBuilder(param: String, param2: String) -> RequestBuilder { - let path = "/fake/jsonFormData" - let URLString = PetstoreClientAPI.basePath + path - let formParams: [String: Any?] = [ + let localVariablePath = "/fake/jsonFormData" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableFormParams: [String: Any?] = [ "param": param.encodeToJSON(), "param2": param2.encodeToJSON(), ] - let nonNullParameters = APIHelper.rejectNil(formParams) - let parameters = APIHelper.convertBoolToString(nonNullParameters) + let localVariableNonNullParameters = APIHelper.rejectNil(localVariableFormParams) + let localVariableParameters = APIHelper.convertBoolToString(localVariableNonNullParameters) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ "Content-Type": "application/x-www-form-urlencoded", ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } - } diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/APIs/FakeClassnameTags123API.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift similarity index 55% rename from samples/client/petstore/swift5/urlsessionLibrary/Sources/APIs/FakeClassnameTags123API.swift rename to samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift index d4d65166496..a6ca6c66b51 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/Sources/APIs/FakeClassnameTags123API.swift +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift @@ -6,8 +6,12 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif open class FakeClassnameTags123API { + /** To test class name in snake case @@ -15,7 +19,7 @@ open class FakeClassnameTags123API { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func testClassname(body: Client, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Client?, _ error: Error?) -> Void)) { + open class func testClassname(body: Client, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Client?, _ error: Error?) -> Void)) { testClassnameWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -37,21 +41,20 @@ open class FakeClassnameTags123API { - returns: RequestBuilder */ open class func testClassnameWithRequestBuilder(body: Client) -> RequestBuilder { - let path = "/fake_classname_test" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/fake_classname_test" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "PATCH", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "PATCH", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } - } diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/APIs/PetAPI.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift similarity index 57% rename from samples/client/petstore/swift5/urlsessionLibrary/Sources/APIs/PetAPI.swift rename to samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift index a1fe0d12b1d..8b97def931c 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/Sources/APIs/PetAPI.swift +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift @@ -6,8 +6,12 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif open class PetAPI { + /** Add a new pet to the store @@ -15,7 +19,7 @@ open class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func addPet(body: Pet, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func addPet(body: Pet, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { addPetWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -36,21 +40,21 @@ open class PetAPI { - returns: RequestBuilder */ open class func addPetWithRequestBuilder(body: Pet) -> RequestBuilder { - let path = "/pet" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/pet" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -61,7 +65,7 @@ open class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func deletePet(petId: Int64, apiKey: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func deletePet(petId: Int64, apiKey: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { deletePetWithRequestBuilder(petId: petId, apiKey: apiKey).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -83,24 +87,24 @@ open class PetAPI { - returns: RequestBuilder */ open class func deletePetWithRequestBuilder(petId: Int64, apiKey: String? = nil) -> RequestBuilder { - var path = "/pet/{petId}" + var localVariablePath = "/pet/{petId}" let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))" let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" - path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + localVariablePath = localVariablePath.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ "api_key": apiKey?.encodeToJSON(), ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "DELETE", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -119,7 +123,7 @@ open class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func findPetsByStatus(status: [String], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: [Pet]?, _ error: Error?) -> Void)) { + open class func findPetsByStatus(status: [String], apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: [Pet]?, _ error: Error?) -> Void)) { findPetsByStatusWithRequestBuilder(status: status).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -141,24 +145,24 @@ open class PetAPI { - returns: RequestBuilder<[Pet]> */ open class func findPetsByStatusWithRequestBuilder(status: [String]) -> RequestBuilder<[Pet]> { - let path = "/pet/findByStatus" - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + let localVariablePath = "/pet/findByStatus" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - var urlComponents = URLComponents(string: URLString) - urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ + var localVariableUrlComponents = URLComponents(string: localVariableURLString) + localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ "status": status.encodeToJSON(), ]) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -169,7 +173,7 @@ open class PetAPI { - parameter completion: completion handler to receive the data and the error objects */ @available(*, deprecated, message: "This operation is deprecated.") - open class func findPetsByTags(tags: [String], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: [Pet]?, _ error: Error?) -> Void)) { + open class func findPetsByTags(tags: [String], apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: [Pet]?, _ error: Error?) -> Void)) { findPetsByTagsWithRequestBuilder(tags: tags).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -192,24 +196,24 @@ open class PetAPI { */ @available(*, deprecated, message: "This operation is deprecated.") open class func findPetsByTagsWithRequestBuilder(tags: [String]) -> RequestBuilder<[Pet]> { - let path = "/pet/findByTags" - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + let localVariablePath = "/pet/findByTags" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - var urlComponents = URLComponents(string: URLString) - urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ + var localVariableUrlComponents = URLComponents(string: localVariableURLString) + localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ "tags": tags.encodeToJSON(), ]) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -219,7 +223,7 @@ open class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func getPetById(petId: Int64, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Pet?, _ error: Error?) -> Void)) { + open class func getPetById(petId: Int64, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Pet?, _ error: Error?) -> Void)) { getPetByIdWithRequestBuilder(petId: petId).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -241,24 +245,24 @@ open class PetAPI { - returns: RequestBuilder */ open class func getPetByIdWithRequestBuilder(petId: Int64) -> RequestBuilder { - var path = "/pet/{petId}" + var localVariablePath = "/pet/{petId}" let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))" let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" - path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + localVariablePath = localVariablePath.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -268,7 +272,7 @@ open class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func updatePet(body: Pet, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func updatePet(body: Pet, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { updatePetWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -289,21 +293,21 @@ open class PetAPI { - returns: RequestBuilder */ open class func updatePetWithRequestBuilder(body: Pet) -> RequestBuilder { - let path = "/pet" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/pet" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "PUT", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -315,7 +319,7 @@ open class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func updatePetWithForm(petId: Int64, name: String? = nil, status: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func updatePetWithForm(petId: Int64, name: String? = nil, status: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { updatePetWithFormWithRequestBuilder(petId: petId, name: name, status: status).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -338,30 +342,30 @@ open class PetAPI { - returns: RequestBuilder */ open class func updatePetWithFormWithRequestBuilder(petId: Int64, name: String? = nil, status: String? = nil) -> RequestBuilder { - var path = "/pet/{petId}" + var localVariablePath = "/pet/{petId}" let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))" let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" - path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path - let formParams: [String: Any?] = [ + localVariablePath = localVariablePath.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableFormParams: [String: Any?] = [ "name": name?.encodeToJSON(), "status": status?.encodeToJSON(), ] - let nonNullParameters = APIHelper.rejectNil(formParams) - let parameters = APIHelper.convertBoolToString(nonNullParameters) + let localVariableNonNullParameters = APIHelper.rejectNil(localVariableFormParams) + let localVariableParameters = APIHelper.convertBoolToString(localVariableNonNullParameters) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ "Content-Type": "application/x-www-form-urlencoded", ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -373,7 +377,7 @@ open class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func uploadFile(petId: Int64, additionalMetadata: String? = nil, file: URL? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: ApiResponse?, _ error: Error?) -> Void)) { + open class func uploadFile(petId: Int64, additionalMetadata: String? = nil, file: URL? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: ApiResponse?, _ error: Error?) -> Void)) { uploadFileWithRequestBuilder(petId: petId, additionalMetadata: additionalMetadata, file: file).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -396,30 +400,30 @@ open class PetAPI { - returns: RequestBuilder */ open class func uploadFileWithRequestBuilder(petId: Int64, additionalMetadata: String? = nil, file: URL? = nil) -> RequestBuilder { - var path = "/pet/{petId}/uploadImage" + var localVariablePath = "/pet/{petId}/uploadImage" let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))" let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" - path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path - let formParams: [String: Any?] = [ + localVariablePath = localVariablePath.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableFormParams: [String: Any?] = [ "additionalMetadata": additionalMetadata?.encodeToJSON(), "file": file?.encodeToJSON(), ] - let nonNullParameters = APIHelper.rejectNil(formParams) - let parameters = APIHelper.convertBoolToString(nonNullParameters) + let localVariableNonNullParameters = APIHelper.rejectNil(localVariableFormParams) + let localVariableParameters = APIHelper.convertBoolToString(localVariableNonNullParameters) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ "Content-Type": "multipart/form-data", ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -431,7 +435,7 @@ open class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func uploadFileWithRequiredFile(petId: Int64, requiredFile: URL, additionalMetadata: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: ApiResponse?, _ error: Error?) -> Void)) { + open class func uploadFileWithRequiredFile(petId: Int64, requiredFile: URL, additionalMetadata: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: ApiResponse?, _ error: Error?) -> Void)) { uploadFileWithRequiredFileWithRequestBuilder(petId: petId, requiredFile: requiredFile, additionalMetadata: additionalMetadata).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -454,30 +458,29 @@ open class PetAPI { - returns: RequestBuilder */ open class func uploadFileWithRequiredFileWithRequestBuilder(petId: Int64, requiredFile: URL, additionalMetadata: String? = nil) -> RequestBuilder { - var path = "/fake/{petId}/uploadImageWithRequiredFile" + var localVariablePath = "/fake/{petId}/uploadImageWithRequiredFile" let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))" let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" - path = path.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path - let formParams: [String: Any?] = [ + localVariablePath = localVariablePath.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableFormParams: [String: Any?] = [ "additionalMetadata": additionalMetadata?.encodeToJSON(), "requiredFile": requiredFile.encodeToJSON(), ] - let nonNullParameters = APIHelper.rejectNil(formParams) - let parameters = APIHelper.convertBoolToString(nonNullParameters) + let localVariableNonNullParameters = APIHelper.rejectNil(localVariableFormParams) + let localVariableParameters = APIHelper.convertBoolToString(localVariableNonNullParameters) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ "Content-Type": "multipart/form-data", ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } - } diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/APIs/StoreAPI.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift similarity index 54% rename from samples/client/petstore/swift5/urlsessionLibrary/Sources/APIs/StoreAPI.swift rename to samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift index 501f11f5f21..53c1fed1eb3 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/Sources/APIs/StoreAPI.swift +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift @@ -6,8 +6,12 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif open class StoreAPI { + /** Delete purchase order by ID @@ -15,7 +19,7 @@ open class StoreAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func deleteOrder(orderId: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func deleteOrder(orderId: String, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { deleteOrderWithRequestBuilder(orderId: orderId).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -34,24 +38,24 @@ open class StoreAPI { - returns: RequestBuilder */ open class func deleteOrderWithRequestBuilder(orderId: String) -> RequestBuilder { - var path = "/store/order/{order_id}" + var localVariablePath = "/store/order/{order_id}" let orderIdPreEscape = "\(APIHelper.mapValueToPathItem(orderId))" let orderIdPostEscape = orderIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" - path = path.replacingOccurrences(of: "{order_id}", with: orderIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + localVariablePath = localVariablePath.replacingOccurrences(of: "{order_id}", with: orderIdPostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "DELETE", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -60,7 +64,7 @@ open class StoreAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func getInventory(apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: [String: Int]?, _ error: Error?) -> Void)) { + open class func getInventory(apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: [String: Int]?, _ error: Error?) -> Void)) { getInventoryWithRequestBuilder().execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -81,21 +85,21 @@ open class StoreAPI { - returns: RequestBuilder<[String: Int]> */ open class func getInventoryWithRequestBuilder() -> RequestBuilder<[String: Int]> { - let path = "/store/inventory" - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + let localVariablePath = "/store/inventory" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder<[String: Int]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder<[String: Int]>.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -105,7 +109,7 @@ open class StoreAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func getOrderById(orderId: Int64, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Order?, _ error: Error?) -> Void)) { + open class func getOrderById(orderId: Int64, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Order?, _ error: Error?) -> Void)) { getOrderByIdWithRequestBuilder(orderId: orderId).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -124,24 +128,24 @@ open class StoreAPI { - returns: RequestBuilder */ open class func getOrderByIdWithRequestBuilder(orderId: Int64) -> RequestBuilder { - var path = "/store/order/{order_id}" + var localVariablePath = "/store/order/{order_id}" let orderIdPreEscape = "\(APIHelper.mapValueToPathItem(orderId))" let orderIdPostEscape = orderIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" - path = path.replacingOccurrences(of: "{order_id}", with: orderIdPostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + localVariablePath = localVariablePath.replacingOccurrences(of: "{order_id}", with: orderIdPostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -151,7 +155,7 @@ open class StoreAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func placeOrder(body: Order, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Order?, _ error: Error?) -> Void)) { + open class func placeOrder(body: Order, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Order?, _ error: Error?) -> Void)) { placeOrderWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -169,21 +173,20 @@ open class StoreAPI { - returns: RequestBuilder */ open class func placeOrderWithRequestBuilder(body: Order) -> RequestBuilder { - let path = "/store/order" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/store/order" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } - } diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/APIs/UserAPI.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift similarity index 52% rename from samples/client/petstore/swift5/urlsessionLibrary/Sources/APIs/UserAPI.swift rename to samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift index 254474014d3..c1e5691390e 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/Sources/APIs/UserAPI.swift +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift @@ -6,8 +6,12 @@ // import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif open class UserAPI { + /** Create user @@ -15,7 +19,7 @@ open class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func createUser(body: User, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func createUser(body: User, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { createUserWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -34,21 +38,21 @@ open class UserAPI { - returns: RequestBuilder */ open class func createUserWithRequestBuilder(body: User) -> RequestBuilder { - let path = "/user" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/user" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -58,7 +62,7 @@ open class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func createUsersWithArrayInput(body: [User], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func createUsersWithArrayInput(body: [User], apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { createUsersWithArrayInputWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -76,21 +80,21 @@ open class UserAPI { - returns: RequestBuilder */ open class func createUsersWithArrayInputWithRequestBuilder(body: [User]) -> RequestBuilder { - let path = "/user/createWithArray" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/user/createWithArray" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -100,7 +104,7 @@ open class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func createUsersWithListInput(body: [User], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func createUsersWithListInput(body: [User], apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { createUsersWithListInputWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -118,21 +122,21 @@ open class UserAPI { - returns: RequestBuilder */ open class func createUsersWithListInputWithRequestBuilder(body: [User]) -> RequestBuilder { - let path = "/user/createWithList" - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + let localVariablePath = "/user/createWithList" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "POST", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -142,7 +146,7 @@ open class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func deleteUser(username: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func deleteUser(username: String, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { deleteUserWithRequestBuilder(username: username).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -161,24 +165,24 @@ open class UserAPI { - returns: RequestBuilder */ open class func deleteUserWithRequestBuilder(username: String) -> RequestBuilder { - var path = "/user/{username}" + var localVariablePath = "/user/{username}" let usernamePreEscape = "\(APIHelper.mapValueToPathItem(username))" let usernamePostEscape = usernamePreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" - path = path.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + localVariablePath = localVariablePath.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "DELETE", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -188,7 +192,7 @@ open class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func getUserByName(username: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: User?, _ error: Error?) -> Void)) { + open class func getUserByName(username: String, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: User?, _ error: Error?) -> Void)) { getUserByNameWithRequestBuilder(username: username).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -206,24 +210,24 @@ open class UserAPI { - returns: RequestBuilder */ open class func getUserByNameWithRequestBuilder(username: String) -> RequestBuilder { - var path = "/user/{username}" + var localVariablePath = "/user/{username}" let usernamePreEscape = "\(APIHelper.mapValueToPathItem(username))" let usernamePostEscape = usernamePreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" - path = path.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + localVariablePath = localVariablePath.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -234,7 +238,7 @@ open class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func loginUser(username: String, password: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: String?, _ error: Error?) -> Void)) { + open class func loginUser(username: String, password: String, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: String?, _ error: Error?) -> Void)) { loginUserWithRequestBuilder(username: username, password: password).execute(apiResponseQueue) { result -> Void in switch result { case let .success(response): @@ -254,25 +258,25 @@ open class UserAPI { - returns: RequestBuilder */ open class func loginUserWithRequestBuilder(username: String, password: String) -> RequestBuilder { - let path = "/user/login" - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + let localVariablePath = "/user/login" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - var urlComponents = URLComponents(string: URLString) - urlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ + var localVariableUrlComponents = URLComponents(string: localVariableURLString) + localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ "username": username.encodeToJSON(), "password": password.encodeToJSON(), ]) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -281,7 +285,7 @@ open class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func logoutUser(apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func logoutUser(apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { logoutUserWithRequestBuilder().execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -298,21 +302,21 @@ open class UserAPI { - returns: RequestBuilder */ open class func logoutUserWithRequestBuilder() -> RequestBuilder { - let path = "/user/logout" - let URLString = PetstoreClientAPI.basePath + path - let parameters: [String: Any]? = nil + let localVariablePath = "/user/logout" + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "GET", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } /** @@ -323,7 +327,7 @@ open class UserAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - parameter completion: completion handler to receive the data and the error objects */ - open class func updateUser(username: String, body: User, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { + open class func updateUser(username: String, body: User, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) { updateUserWithRequestBuilder(username: username, body: body).execute(apiResponseQueue) { result -> Void in switch result { case .success: @@ -343,24 +347,23 @@ open class UserAPI { - returns: RequestBuilder */ open class func updateUserWithRequestBuilder(username: String, body: User) -> RequestBuilder { - var path = "/user/{username}" + var localVariablePath = "/user/{username}" let usernamePreEscape = "\(APIHelper.mapValueToPathItem(username))" let usernamePostEscape = usernamePreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" - path = path.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) - let URLString = PetstoreClientAPI.basePath + path - let parameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + localVariablePath = localVariablePath.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClient.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) - let urlComponents = URLComponents(string: URLString) + let localVariableUrlComponents = URLComponents(string: localVariableURLString) - let nillableHeaders: [String: Any?] = [ + let localVariableNillableHeaders: [String: Any?] = [ : ] - let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder() - return requestBuilder.init(method: "PUT", URLString: (urlComponents?.string ?? URLString), parameters: parameters, headers: headerParameters) + return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) } - } diff --git a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/CodableHelper.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/CodableHelper.swift new file mode 100644 index 00000000000..09c82e53e13 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/CodableHelper.swift @@ -0,0 +1,49 @@ +// +// CodableHelper.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation + +open class CodableHelper { + private static var customDateFormatter: DateFormatter? + private static var defaultDateFormatter: DateFormatter = OpenISO8601DateFormatter() + + private static var customJSONDecoder: JSONDecoder? + private static var defaultJSONDecoder: JSONDecoder = { + let decoder = JSONDecoder() + decoder.dateDecodingStrategy = .formatted(CodableHelper.dateFormatter) + return decoder + }() + + private static var customJSONEncoder: JSONEncoder? + private static var defaultJSONEncoder: JSONEncoder = { + let encoder = JSONEncoder() + encoder.dateEncodingStrategy = .formatted(CodableHelper.dateFormatter) + encoder.outputFormatting = .prettyPrinted + return encoder + }() + + public static var dateFormatter: DateFormatter { + get { return customDateFormatter ?? defaultDateFormatter } + set { customDateFormatter = newValue } + } + public static var jsonDecoder: JSONDecoder { + get { return customJSONDecoder ?? defaultJSONDecoder } + set { customJSONDecoder = newValue } + } + public static var jsonEncoder: JSONEncoder { + get { return customJSONEncoder ?? defaultJSONEncoder } + set { customJSONEncoder = newValue } + } + + open class func decode(_ type: T.Type, from data: Data) -> Swift.Result where T: Decodable { + return Swift.Result { try jsonDecoder.decode(type, from: data) } + } + + open class func encode(_ value: T) -> Swift.Result where T: Encodable { + return Swift.Result { try jsonEncoder.encode(value) } + } +} diff --git a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Configuration.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Configuration.swift new file mode 100644 index 00000000000..8fb05331889 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Configuration.swift @@ -0,0 +1,15 @@ +// Configuration.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation + +open class Configuration { + + // This value is used to configure the date formatter that is used to serialize dates into JSON format. + // You must set it prior to encoding any dates, and it will only be read once. + @available(*, unavailable, message: "To set a different date format, use CodableHelper.dateFormatter instead.") + public static var dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ" +} diff --git a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Extensions.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Extensions.swift new file mode 100644 index 00000000000..e23035dde30 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Extensions.swift @@ -0,0 +1,188 @@ +// Extensions.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +extension Bool: JSONEncodable { + func encodeToJSON() -> Any { return self as Any } +} + +extension Float: JSONEncodable { + func encodeToJSON() -> Any { return self as Any } +} + +extension Int: JSONEncodable { + func encodeToJSON() -> Any { return self as Any } +} + +extension Int32: JSONEncodable { + func encodeToJSON() -> Any { return NSNumber(value: self as Int32) } +} + +extension Int64: JSONEncodable { + func encodeToJSON() -> Any { return NSNumber(value: self as Int64) } +} + +extension Double: JSONEncodable { + func encodeToJSON() -> Any { return self as Any } +} + +extension String: JSONEncodable { + func encodeToJSON() -> Any { return self as Any } +} + +extension RawRepresentable where RawValue: JSONEncodable { + func encodeToJSON() -> Any { return self.rawValue as Any } +} + +private func encodeIfPossible(_ object: T) -> Any { + if let encodableObject = object as? JSONEncodable { + return encodableObject.encodeToJSON() + } else { + return object as Any + } +} + +extension Array: JSONEncodable { + func encodeToJSON() -> Any { + return self.map(encodeIfPossible) + } +} + +extension Set: JSONEncodable { + func encodeToJSON() -> Any { + return Array(self).encodeToJSON() + } +} + +extension Dictionary: JSONEncodable { + func encodeToJSON() -> Any { + var dictionary = [AnyHashable: Any]() + for (key, value) in self { + dictionary[key] = encodeIfPossible(value) + } + return dictionary as Any + } +} + +extension Data: JSONEncodable { + func encodeToJSON() -> Any { + return self.base64EncodedString(options: Data.Base64EncodingOptions()) + } +} + +extension Date: JSONEncodable { + func encodeToJSON() -> Any { + return CodableHelper.dateFormatter.string(from: self) as Any + } +} + +extension URL: JSONEncodable { + func encodeToJSON() -> Any { + return self + } +} + +extension UUID: JSONEncodable { + func encodeToJSON() -> Any { + return self.uuidString + } +} + +extension String: CodingKey { + + public var stringValue: String { + return self + } + + public init?(stringValue: String) { + self.init(stringLiteral: stringValue) + } + + public var intValue: Int? { + return nil + } + + public init?(intValue: Int) { + return nil + } + +} + +extension KeyedEncodingContainerProtocol { + + public mutating func encodeArray(_ values: [T], forKey key: Self.Key) throws where T: Encodable { + var arrayContainer = nestedUnkeyedContainer(forKey: key) + try arrayContainer.encode(contentsOf: values) + } + + public mutating func encodeArrayIfPresent(_ values: [T]?, forKey key: Self.Key) throws where T: Encodable { + if let values = values { + try encodeArray(values, forKey: key) + } + } + + public mutating func encodeMap(_ pairs: [Self.Key: T]) throws where T: Encodable { + for (key, value) in pairs { + try encode(value, forKey: key) + } + } + + public mutating func encodeMapIfPresent(_ pairs: [Self.Key: T]?) throws where T: Encodable { + if let pairs = pairs { + try encodeMap(pairs) + } + } + +} + +extension KeyedDecodingContainerProtocol { + + public func decodeArray(_ type: T.Type, forKey key: Self.Key) throws -> [T] where T: Decodable { + var tmpArray = [T]() + + var nestedContainer = try nestedUnkeyedContainer(forKey: key) + while !nestedContainer.isAtEnd { + let arrayValue = try nestedContainer.decode(T.self) + tmpArray.append(arrayValue) + } + + return tmpArray + } + + public func decodeArrayIfPresent(_ type: T.Type, forKey key: Self.Key) throws -> [T]? where T: Decodable { + var tmpArray: [T]? + + if contains(key) { + tmpArray = try decodeArray(T.self, forKey: key) + } + + return tmpArray + } + + public func decodeMap(_ type: T.Type, excludedKeys: Set) throws -> [Self.Key: T] where T: Decodable { + var map: [Self.Key: T] = [:] + + for key in allKeys { + if !excludedKeys.contains(key) { + let value = try decode(T.self, forKey: key) + map[key] = value + } + } + + return map + } + +} + +extension HTTPURLResponse { + var isStatusCodeSuccessful: Bool { + return Array(200 ..< 300).contains(statusCode) + } +} diff --git a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/JSONDataEncoding.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/JSONDataEncoding.swift new file mode 100644 index 00000000000..b79e9f5e64d --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/JSONDataEncoding.swift @@ -0,0 +1,53 @@ +// +// JSONDataEncoding.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation + +public struct JSONDataEncoding { + + // MARK: Properties + + private static let jsonDataKey = "jsonData" + + // MARK: Encoding + + /// Creates a URL request by encoding parameters and applying them onto an existing request. + /// + /// - parameter urlRequest: The request to have parameters applied. + /// - parameter parameters: The parameters to apply. This should have a single key/value + /// pair with "jsonData" as the key and a Data object as the value. + /// + /// - throws: An `Error` if the encoding process encounters an error. + /// + /// - returns: The encoded request. + public func encode(_ urlRequest: URLRequest, with parameters: [String: Any]?) -> URLRequest { + var urlRequest = urlRequest + + guard let jsonData = parameters?[JSONDataEncoding.jsonDataKey] as? Data, !jsonData.isEmpty else { + return urlRequest + } + + if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil { + urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") + } + + urlRequest.httpBody = jsonData + + return urlRequest + } + + public static func encodingParameters(jsonData: Data?) -> [String: Any]? { + var returnedParams: [String: Any]? + if let jsonData = jsonData, !jsonData.isEmpty { + var params: [String: Any] = [:] + params[jsonDataKey] = jsonData + returnedParams = params + } + return returnedParams + } + +} diff --git a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/JSONEncodingHelper.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/JSONEncodingHelper.swift new file mode 100644 index 00000000000..02f78ffb470 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/JSONEncodingHelper.swift @@ -0,0 +1,45 @@ +// +// JSONEncodingHelper.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation + +open class JSONEncodingHelper { + + open class func encodingParameters(forEncodableObject encodableObj: T?) -> [String: Any]? { + var params: [String: Any]? + + // Encode the Encodable object + if let encodableObj = encodableObj { + let encodeResult = CodableHelper.encode(encodableObj) + do { + let data = try encodeResult.get() + params = JSONDataEncoding.encodingParameters(jsonData: data) + } catch { + print(error.localizedDescription) + } + } + + return params + } + + open class func encodingParameters(forEncodableObject encodableObj: Any?) -> [String: Any]? { + var params: [String: Any]? + + if let encodableObj = encodableObj { + do { + let data = try JSONSerialization.data(withJSONObject: encodableObj, options: .prettyPrinted) + params = JSONDataEncoding.encodingParameters(jsonData: data) + } catch { + print(error.localizedDescription) + return nil + } + } + + return params + } + +} diff --git a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models.swift new file mode 100644 index 00000000000..96e26a20f7d --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models.swift @@ -0,0 +1,54 @@ +// Models.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation + +protocol JSONEncodable { + func encodeToJSON() -> Any +} + +public enum ErrorResponse: Error { + case error(Int, Data?, URLResponse?, Error) +} + +public enum DownloadException: Error { + case responseDataMissing + case responseFailed + case requestMissing + case requestMissingPath + case requestMissingURL +} + +public enum DecodableRequestBuilderError: Error { + case emptyDataResponse + case nilHTTPResponse + case unsuccessfulHTTPStatusCode + case jsonDecoding(DecodingError) + case generalError(Error) +} + +open class Response { + public let statusCode: Int + public let header: [String: String] + public let body: T? + + public init(statusCode: Int, header: [String: String], body: T?) { + self.statusCode = statusCode + self.header = header + self.body = body + } + + public convenience init(response: HTTPURLResponse, body: T?) { + let rawHeader = response.allHeaderFields + var header = [String: String]() + for (key, value) in rawHeader { + if let key = key.base as? String, let value = value as? String { + header[key] = value + } + } + self.init(statusCode: response.statusCode, header: header, body: body) + } +} diff --git a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesAnyType.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesAnyType.swift new file mode 100644 index 00000000000..7022f41580f --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesAnyType.swift @@ -0,0 +1,57 @@ +// +// AdditionalPropertiesAnyType.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +import AnyCodable + +public struct AdditionalPropertiesAnyType: Codable { + + public var name: String? + + public init(name: String? = nil) { + self.name = name + } + public enum CodingKeys: String, CodingKey, CaseIterable { + case name + } + public var additionalProperties: [String: AnyCodable] = [:] + + public subscript(key: String) -> AnyCodable? { + get { + if let value = additionalProperties[key] { + return value + } + return nil + } + + set { + additionalProperties[key] = newValue + } + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(name, forKey: .name) + var additionalPropertiesContainer = encoder.container(keyedBy: String.self) + try additionalPropertiesContainer.encodeMap(additionalProperties) + } + + // Decodable protocol methods + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: String.self) + + name = try container.decodeIfPresent(String.self, forKey: "name") + var nonAdditionalPropertyKeys = Set() + nonAdditionalPropertyKeys.insert("name") + additionalProperties = try container.decodeMap(AnyCodable.self, excludedKeys: nonAdditionalPropertyKeys) + } + + +} diff --git a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesArray.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesArray.swift new file mode 100644 index 00000000000..f0ac1d5c0e0 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesArray.swift @@ -0,0 +1,57 @@ +// +// AdditionalPropertiesArray.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +import AnyCodable + +public struct AdditionalPropertiesArray: Codable { + + public var name: String? + + public init(name: String? = nil) { + self.name = name + } + public enum CodingKeys: String, CodingKey, CaseIterable { + case name + } + public var additionalProperties: [String: [AnyCodable]] = [:] + + public subscript(key: String) -> [AnyCodable]? { + get { + if let value = additionalProperties[key] { + return value + } + return nil + } + + set { + additionalProperties[key] = newValue + } + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(name, forKey: .name) + var additionalPropertiesContainer = encoder.container(keyedBy: String.self) + try additionalPropertiesContainer.encodeMap(additionalProperties) + } + + // Decodable protocol methods + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: String.self) + + name = try container.decodeIfPresent(String.self, forKey: "name") + var nonAdditionalPropertyKeys = Set() + nonAdditionalPropertyKeys.insert("name") + additionalProperties = try container.decodeMap([AnyCodable].self, excludedKeys: nonAdditionalPropertyKeys) + } + + +} diff --git a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesBoolean.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesBoolean.swift new file mode 100644 index 00000000000..5879e198764 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesBoolean.swift @@ -0,0 +1,57 @@ +// +// AdditionalPropertiesBoolean.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +import AnyCodable + +public struct AdditionalPropertiesBoolean: Codable { + + public var name: String? + + public init(name: String? = nil) { + self.name = name + } + public enum CodingKeys: String, CodingKey, CaseIterable { + case name + } + public var additionalProperties: [String: Bool] = [:] + + public subscript(key: String) -> Bool? { + get { + if let value = additionalProperties[key] { + return value + } + return nil + } + + set { + additionalProperties[key] = newValue + } + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(name, forKey: .name) + var additionalPropertiesContainer = encoder.container(keyedBy: String.self) + try additionalPropertiesContainer.encodeMap(additionalProperties) + } + + // Decodable protocol methods + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: String.self) + + name = try container.decodeIfPresent(String.self, forKey: "name") + var nonAdditionalPropertyKeys = Set() + nonAdditionalPropertyKeys.insert("name") + additionalProperties = try container.decodeMap(Bool.self, excludedKeys: nonAdditionalPropertyKeys) + } + + +} diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/Models/AdditionalPropertiesClass.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesClass.swift similarity index 67% rename from samples/client/petstore/swift5/urlsessionLibrary/Sources/Models/AdditionalPropertiesClass.swift rename to samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesClass.swift index 5c3e8279143..e760b200563 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/Sources/Models/AdditionalPropertiesClass.swift +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesClass.swift @@ -6,9 +6,11 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif -public final class AdditionalPropertiesClass: Codable, Hashable { +public struct AdditionalPropertiesClass: Codable { public var mapString: [String: String]? public var mapMapString: [String: [String: String]]? @@ -17,6 +19,7 @@ public final class AdditionalPropertiesClass: Codable, Hashable { self.mapString = mapString self.mapMapString = mapMapString } + public enum CodingKeys: String, CodingKey, CaseIterable { case mapString = "map_string" case mapMapString = "map_map_string" @@ -29,19 +32,5 @@ public final class AdditionalPropertiesClass: Codable, Hashable { try container.encodeIfPresent(mapString, forKey: .mapString) try container.encodeIfPresent(mapMapString, forKey: .mapMapString) } - - - - public static func == (lhs: AdditionalPropertiesClass, rhs: AdditionalPropertiesClass) -> Bool { - lhs.mapString == rhs.mapString && - lhs.mapMapString == rhs.mapMapString - - } - - public func hash(into hasher: inout Hasher) { - hasher.combine(mapString?.hashValue) - hasher.combine(mapMapString?.hashValue) - - } - } + diff --git a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesInteger.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesInteger.swift new file mode 100644 index 00000000000..acfd7ae67be --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesInteger.swift @@ -0,0 +1,57 @@ +// +// AdditionalPropertiesInteger.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +import AnyCodable + +public struct AdditionalPropertiesInteger: Codable { + + public var name: String? + + public init(name: String? = nil) { + self.name = name + } + public enum CodingKeys: String, CodingKey, CaseIterable { + case name + } + public var additionalProperties: [String: Int] = [:] + + public subscript(key: String) -> Int? { + get { + if let value = additionalProperties[key] { + return value + } + return nil + } + + set { + additionalProperties[key] = newValue + } + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(name, forKey: .name) + var additionalPropertiesContainer = encoder.container(keyedBy: String.self) + try additionalPropertiesContainer.encodeMap(additionalProperties) + } + + // Decodable protocol methods + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: String.self) + + name = try container.decodeIfPresent(String.self, forKey: "name") + var nonAdditionalPropertyKeys = Set() + nonAdditionalPropertyKeys.insert("name") + additionalProperties = try container.decodeMap(Int.self, excludedKeys: nonAdditionalPropertyKeys) + } + + +} diff --git a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesNumber.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesNumber.swift new file mode 100644 index 00000000000..006997c5f6b --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesNumber.swift @@ -0,0 +1,57 @@ +// +// AdditionalPropertiesNumber.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +import AnyCodable + +public struct AdditionalPropertiesNumber: Codable { + + public var name: String? + + public init(name: String? = nil) { + self.name = name + } + public enum CodingKeys: String, CodingKey, CaseIterable { + case name + } + public var additionalProperties: [String: Double] = [:] + + public subscript(key: String) -> Double? { + get { + if let value = additionalProperties[key] { + return value + } + return nil + } + + set { + additionalProperties[key] = newValue + } + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(name, forKey: .name) + var additionalPropertiesContainer = encoder.container(keyedBy: String.self) + try additionalPropertiesContainer.encodeMap(additionalProperties) + } + + // Decodable protocol methods + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: String.self) + + name = try container.decodeIfPresent(String.self, forKey: "name") + var nonAdditionalPropertyKeys = Set() + nonAdditionalPropertyKeys.insert("name") + additionalProperties = try container.decodeMap(Double.self, excludedKeys: nonAdditionalPropertyKeys) + } + + +} diff --git a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesObject.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesObject.swift new file mode 100644 index 00000000000..adc28863447 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesObject.swift @@ -0,0 +1,57 @@ +// +// AdditionalPropertiesObject.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +import AnyCodable + +public struct AdditionalPropertiesObject: Codable { + + public var name: String? + + public init(name: String? = nil) { + self.name = name + } + public enum CodingKeys: String, CodingKey, CaseIterable { + case name + } + public var additionalProperties: [String: [String: AnyCodable]] = [:] + + public subscript(key: String) -> [String: AnyCodable]? { + get { + if let value = additionalProperties[key] { + return value + } + return nil + } + + set { + additionalProperties[key] = newValue + } + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(name, forKey: .name) + var additionalPropertiesContainer = encoder.container(keyedBy: String.self) + try additionalPropertiesContainer.encodeMap(additionalProperties) + } + + // Decodable protocol methods + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: String.self) + + name = try container.decodeIfPresent(String.self, forKey: "name") + var nonAdditionalPropertyKeys = Set() + nonAdditionalPropertyKeys.insert("name") + additionalProperties = try container.decodeMap([String: AnyCodable].self, excludedKeys: nonAdditionalPropertyKeys) + } + + +} diff --git a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesString.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesString.swift new file mode 100644 index 00000000000..eba32fc30e1 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesString.swift @@ -0,0 +1,57 @@ +// +// AdditionalPropertiesString.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +import AnyCodable + +public struct AdditionalPropertiesString: Codable { + + public var name: String? + + public init(name: String? = nil) { + self.name = name + } + public enum CodingKeys: String, CodingKey, CaseIterable { + case name + } + public var additionalProperties: [String: String] = [:] + + public subscript(key: String) -> String? { + get { + if let value = additionalProperties[key] { + return value + } + return nil + } + + set { + additionalProperties[key] = newValue + } + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(name, forKey: .name) + var additionalPropertiesContainer = encoder.container(keyedBy: String.self) + try additionalPropertiesContainer.encodeMap(additionalProperties) + } + + // Decodable protocol methods + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: String.self) + + name = try container.decodeIfPresent(String.self, forKey: "name") + var nonAdditionalPropertyKeys = Set() + nonAdditionalPropertyKeys.insert("name") + additionalProperties = try container.decodeMap(String.self, excludedKeys: nonAdditionalPropertyKeys) + } + + +} diff --git a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/Animal.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/Animal.swift new file mode 100644 index 00000000000..fb1a2df615d --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/Animal.swift @@ -0,0 +1,36 @@ +// +// Animal.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct Animal: Codable { + + public var className: String + public var color: String? = "red" + + public init(className: String, color: String? = "red") { + self.className = className + self.color = color + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case className + case color + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(className, forKey: .className) + try container.encodeIfPresent(color, forKey: .color) + } +} + diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/Models/AnimalFarm.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/AnimalFarm.swift similarity index 84% rename from samples/client/petstore/swift5/urlsessionLibrary/Sources/Models/AnimalFarm.swift rename to samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/AnimalFarm.swift index b20b894a1ad..a0b09cb9761 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/Sources/Models/AnimalFarm.swift +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/AnimalFarm.swift @@ -6,6 +6,8 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public typealias AnimalFarm = [Animal] diff --git a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift new file mode 100644 index 00000000000..4ee097de054 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift @@ -0,0 +1,40 @@ +// +// ApiResponse.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct ApiResponse: Codable { + + public var code: Int? + public var type: String? + public var message: String? + + public init(code: Int? = nil, type: String? = nil, message: String? = nil) { + self.code = code + self.type = type + self.message = message + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case code + case type + case message + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(code, forKey: .code) + try container.encodeIfPresent(type, forKey: .type) + try container.encodeIfPresent(message, forKey: .message) + } +} + diff --git a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfArrayOfNumberOnly.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfArrayOfNumberOnly.swift new file mode 100644 index 00000000000..6f3ceb17753 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfArrayOfNumberOnly.swift @@ -0,0 +1,32 @@ +// +// ArrayOfArrayOfNumberOnly.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct ArrayOfArrayOfNumberOnly: Codable { + + public var arrayArrayNumber: [[Double]]? + + public init(arrayArrayNumber: [[Double]]? = nil) { + self.arrayArrayNumber = arrayArrayNumber + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case arrayArrayNumber = "ArrayArrayNumber" + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(arrayArrayNumber, forKey: .arrayArrayNumber) + } +} + diff --git a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfNumberOnly.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfNumberOnly.swift new file mode 100644 index 00000000000..eb9892beb2b --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfNumberOnly.swift @@ -0,0 +1,32 @@ +// +// ArrayOfNumberOnly.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct ArrayOfNumberOnly: Codable { + + public var arrayNumber: [Double]? + + public init(arrayNumber: [Double]? = nil) { + self.arrayNumber = arrayNumber + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case arrayNumber = "ArrayNumber" + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(arrayNumber, forKey: .arrayNumber) + } +} + diff --git a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/ArrayTest.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/ArrayTest.swift new file mode 100644 index 00000000000..76aad66ec82 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/ArrayTest.swift @@ -0,0 +1,40 @@ +// +// ArrayTest.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct ArrayTest: Codable { + + public var arrayOfString: [String]? + public var arrayArrayOfInteger: [[Int64]]? + public var arrayArrayOfModel: [[ReadOnlyFirst]]? + + public init(arrayOfString: [String]? = nil, arrayArrayOfInteger: [[Int64]]? = nil, arrayArrayOfModel: [[ReadOnlyFirst]]? = nil) { + self.arrayOfString = arrayOfString + self.arrayArrayOfInteger = arrayArrayOfInteger + self.arrayArrayOfModel = arrayArrayOfModel + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case arrayOfString = "array_of_string" + case arrayArrayOfInteger = "array_array_of_integer" + case arrayArrayOfModel = "array_array_of_model" + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(arrayOfString, forKey: .arrayOfString) + try container.encodeIfPresent(arrayArrayOfInteger, forKey: .arrayArrayOfInteger) + try container.encodeIfPresent(arrayArrayOfModel, forKey: .arrayArrayOfModel) + } +} + diff --git a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/BigCat.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/BigCat.swift new file mode 100644 index 00000000000..842930f738d --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/BigCat.swift @@ -0,0 +1,37 @@ +// +// BigCat.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +import AnyCodable + +public struct BigCat: Codable { + + public enum Kind: String, Codable, CaseIterable { + case lions = "lions" + case tigers = "tigers" + case leopards = "leopards" + case jaguars = "jaguars" + } + public var kind: Kind? + + public init(kind: Kind? = nil) { + self.kind = kind + } + public enum CodingKeys: String, CodingKey, CaseIterable { + case kind + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(kind, forKey: .kind) + } + + + +} diff --git a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/BigCatAllOf.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/BigCatAllOf.swift new file mode 100644 index 00000000000..b7c03fe8821 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/BigCatAllOf.swift @@ -0,0 +1,37 @@ +// +// BigCatAllOf.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +import AnyCodable + +public struct BigCatAllOf: Codable { + + public enum Kind: String, Codable, CaseIterable { + case lions = "lions" + case tigers = "tigers" + case leopards = "leopards" + case jaguars = "jaguars" + } + public var kind: Kind? + + public init(kind: Kind? = nil) { + self.kind = kind + } + public enum CodingKeys: String, CodingKey, CaseIterable { + case kind + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(kind, forKey: .kind) + } + + + +} diff --git a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/Capitalization.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/Capitalization.swift new file mode 100644 index 00000000000..d06bb38d2d1 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/Capitalization.swift @@ -0,0 +1,53 @@ +// +// Capitalization.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct Capitalization: Codable { + + public var smallCamel: String? + public var capitalCamel: String? + public var smallSnake: String? + public var capitalSnake: String? + public var sCAETHFlowPoints: String? + /** Name of the pet */ + public var ATT_NAME: String? + + public init(smallCamel: String? = nil, capitalCamel: String? = nil, smallSnake: String? = nil, capitalSnake: String? = nil, sCAETHFlowPoints: String? = nil, ATT_NAME: String? = nil) { + self.smallCamel = smallCamel + self.capitalCamel = capitalCamel + self.smallSnake = smallSnake + self.capitalSnake = capitalSnake + self.sCAETHFlowPoints = sCAETHFlowPoints + self.ATT_NAME = ATT_NAME + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case smallCamel + case capitalCamel = "CapitalCamel" + case smallSnake = "small_Snake" + case capitalSnake = "Capital_Snake" + case sCAETHFlowPoints = "SCA_ETH_Flow_Points" + case ATT_NAME + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(smallCamel, forKey: .smallCamel) + try container.encodeIfPresent(capitalCamel, forKey: .capitalCamel) + try container.encodeIfPresent(smallSnake, forKey: .smallSnake) + try container.encodeIfPresent(capitalSnake, forKey: .capitalSnake) + try container.encodeIfPresent(sCAETHFlowPoints, forKey: .sCAETHFlowPoints) + try container.encodeIfPresent(ATT_NAME, forKey: .ATT_NAME) + } +} + diff --git a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/Cat.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/Cat.swift new file mode 100644 index 00000000000..7a394aca88d --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/Cat.swift @@ -0,0 +1,40 @@ +// +// Cat.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct Cat: Codable { + + public var className: String + public var color: String? = "red" + public var declawed: Bool? + + public init(className: String, color: String? = "red", declawed: Bool? = nil) { + self.className = className + self.color = color + self.declawed = declawed + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case className + case color + case declawed + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(className, forKey: .className) + try container.encodeIfPresent(color, forKey: .color) + try container.encodeIfPresent(declawed, forKey: .declawed) + } +} + diff --git a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/CatAllOf.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/CatAllOf.swift new file mode 100644 index 00000000000..679eda93b89 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/CatAllOf.swift @@ -0,0 +1,32 @@ +// +// CatAllOf.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct CatAllOf: Codable { + + public var declawed: Bool? + + public init(declawed: Bool? = nil) { + self.declawed = declawed + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case declawed + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(declawed, forKey: .declawed) + } +} + diff --git a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/Category.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/Category.swift new file mode 100644 index 00000000000..89016ca353d --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/Category.swift @@ -0,0 +1,36 @@ +// +// Category.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct Category: Codable, Hashable { + + public var id: Int64? + public var name: String? = "default-name" + + public init(id: Int64? = nil, name: String? = "default-name") { + self.id = id + self.name = name + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case id + case name + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(id, forKey: .id) + try container.encode(name, forKey: .name) + } +} + diff --git a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/ClassModel.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/ClassModel.swift new file mode 100644 index 00000000000..bc4e56c01ae --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/ClassModel.swift @@ -0,0 +1,33 @@ +// +// ClassModel.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +/** Model for testing model with \"_class\" property */ +public struct ClassModel: Codable { + + public var _class: String? + + public init(_class: String? = nil) { + self._class = _class + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case _class + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(_class, forKey: ._class) + } +} + diff --git a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/Client.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/Client.swift new file mode 100644 index 00000000000..f1c50e5b8b9 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/Client.swift @@ -0,0 +1,32 @@ +// +// Client.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct Client: Codable { + + public var client: String? + + public init(client: String? = nil) { + self.client = client + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case client + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(client, forKey: .client) + } +} + diff --git a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/Dog.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/Dog.swift new file mode 100644 index 00000000000..55c387c28ae --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/Dog.swift @@ -0,0 +1,40 @@ +// +// Dog.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct Dog: Codable { + + public var className: String + public var color: String? = "red" + public var breed: String? + + public init(className: String, color: String? = "red", breed: String? = nil) { + self.className = className + self.color = color + self.breed = breed + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case className + case color + case breed + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(className, forKey: .className) + try container.encodeIfPresent(color, forKey: .color) + try container.encodeIfPresent(breed, forKey: .breed) + } +} + diff --git a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/DogAllOf.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/DogAllOf.swift new file mode 100644 index 00000000000..b86ba8ccf8f --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/DogAllOf.swift @@ -0,0 +1,32 @@ +// +// DogAllOf.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct DogAllOf: Codable { + + public var breed: String? + + public init(breed: String? = nil) { + self.breed = breed + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case breed + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(breed, forKey: .breed) + } +} + diff --git a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/EnumArrays.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/EnumArrays.swift new file mode 100644 index 00000000000..edd583c8a29 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/EnumArrays.swift @@ -0,0 +1,44 @@ +// +// EnumArrays.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct EnumArrays: Codable { + + public enum JustSymbol: String, Codable, CaseIterable { + case greaterThanOrEqualTo = ">=" + case dollar = "$" + } + public enum ArrayEnum: String, Codable, CaseIterable { + case fish = "fish" + case crab = "crab" + } + public var justSymbol: JustSymbol? + public var arrayEnum: [ArrayEnum]? + + public init(justSymbol: JustSymbol? = nil, arrayEnum: [ArrayEnum]? = nil) { + self.justSymbol = justSymbol + self.arrayEnum = arrayEnum + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case justSymbol = "just_symbol" + case arrayEnum = "array_enum" + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(justSymbol, forKey: .justSymbol) + try container.encodeIfPresent(arrayEnum, forKey: .arrayEnum) + } +} + diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/Models/EnumClass.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/EnumClass.swift similarity index 88% rename from samples/client/petstore/swift5/urlsessionLibrary/Sources/Models/EnumClass.swift rename to samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/EnumClass.swift index ab01cf297f8..6ea2895aee5 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/Sources/Models/EnumClass.swift +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/EnumClass.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public enum EnumClass: String, Codable, CaseIterable { case abc = "_abc" diff --git a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/EnumTest.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/EnumTest.swift new file mode 100644 index 00000000000..4ae75032cfc --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/EnumTest.swift @@ -0,0 +1,66 @@ +// +// EnumTest.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct EnumTest: Codable { + + public enum EnumString: String, Codable, CaseIterable { + case upper = "UPPER" + case lower = "lower" + case empty = "" + } + public enum EnumStringRequired: String, Codable, CaseIterable { + case upper = "UPPER" + case lower = "lower" + case empty = "" + } + public enum EnumInteger: Int, Codable, CaseIterable { + case _1 = 1 + case number1 = -1 + } + public enum EnumNumber: Double, Codable, CaseIterable { + case _11 = 1.1 + case number12 = -1.2 + } + public var enumString: EnumString? + public var enumStringRequired: EnumStringRequired + public var enumInteger: EnumInteger? + public var enumNumber: EnumNumber? + public var outerEnum: OuterEnum? + + public init(enumString: EnumString? = nil, enumStringRequired: EnumStringRequired, enumInteger: EnumInteger? = nil, enumNumber: EnumNumber? = nil, outerEnum: OuterEnum? = nil) { + self.enumString = enumString + self.enumStringRequired = enumStringRequired + self.enumInteger = enumInteger + self.enumNumber = enumNumber + self.outerEnum = outerEnum + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case enumString = "enum_string" + case enumStringRequired = "enum_string_required" + case enumInteger = "enum_integer" + case enumNumber = "enum_number" + case outerEnum + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(enumString, forKey: .enumString) + try container.encode(enumStringRequired, forKey: .enumStringRequired) + try container.encodeIfPresent(enumInteger, forKey: .enumInteger) + try container.encodeIfPresent(enumNumber, forKey: .enumNumber) + try container.encodeIfPresent(outerEnum, forKey: .outerEnum) + } +} + diff --git a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/File.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/File.swift new file mode 100644 index 00000000000..d6513e0df74 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/File.swift @@ -0,0 +1,34 @@ +// +// File.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +/** Must be named `File` for test. */ +public struct File: Codable { + + /** Test capitalization */ + public var sourceURI: String? + + public init(sourceURI: String? = nil) { + self.sourceURI = sourceURI + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case sourceURI + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(sourceURI, forKey: .sourceURI) + } +} + diff --git a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/FileSchemaTestClass.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/FileSchemaTestClass.swift new file mode 100644 index 00000000000..d707e2ff2e2 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/FileSchemaTestClass.swift @@ -0,0 +1,36 @@ +// +// FileSchemaTestClass.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct FileSchemaTestClass: Codable { + + public var file: File? + public var files: [File]? + + public init(file: File? = nil, files: [File]? = nil) { + self.file = file + self.files = files + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case file + case files + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(file, forKey: .file) + try container.encodeIfPresent(files, forKey: .files) + } +} + diff --git a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/FormatTest.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/FormatTest.swift new file mode 100644 index 00000000000..cbf0050081e --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/FormatTest.swift @@ -0,0 +1,80 @@ +// +// FormatTest.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct FormatTest: Codable { + + public var integer: Int? + public var int32: Int? + public var int64: Int64? + public var number: Double + public var float: Float? + public var double: Double? + public var string: String? + public var byte: Data + public var binary: URL? + public var date: Date + public var dateTime: Date? + public var uuid: UUID? + public var password: String + + public init(integer: Int? = nil, int32: Int? = nil, int64: Int64? = nil, number: Double, float: Float? = nil, double: Double? = nil, string: String? = nil, byte: Data, binary: URL? = nil, date: Date, dateTime: Date? = nil, uuid: UUID? = nil, password: String) { + self.integer = integer + self.int32 = int32 + self.int64 = int64 + self.number = number + self.float = float + self.double = double + self.string = string + self.byte = byte + self.binary = binary + self.date = date + self.dateTime = dateTime + self.uuid = uuid + self.password = password + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case integer + case int32 + case int64 + case number + case float + case double + case string + case byte + case binary + case date + case dateTime + case uuid + case password + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(integer, forKey: .integer) + try container.encodeIfPresent(int32, forKey: .int32) + try container.encodeIfPresent(int64, forKey: .int64) + try container.encode(number, forKey: .number) + try container.encodeIfPresent(float, forKey: .float) + try container.encodeIfPresent(double, forKey: .double) + try container.encodeIfPresent(string, forKey: .string) + try container.encode(byte, forKey: .byte) + try container.encodeIfPresent(binary, forKey: .binary) + try container.encode(date, forKey: .date) + try container.encodeIfPresent(dateTime, forKey: .dateTime) + try container.encodeIfPresent(uuid, forKey: .uuid) + try container.encode(password, forKey: .password) + } +} + diff --git a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/HasOnlyReadOnly.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/HasOnlyReadOnly.swift new file mode 100644 index 00000000000..9185cd673a8 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/HasOnlyReadOnly.swift @@ -0,0 +1,36 @@ +// +// HasOnlyReadOnly.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct HasOnlyReadOnly: Codable { + + public var bar: String? + public var foo: String? + + public init(bar: String? = nil, foo: String? = nil) { + self.bar = bar + self.foo = foo + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case bar + case foo + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(bar, forKey: .bar) + try container.encodeIfPresent(foo, forKey: .foo) + } +} + diff --git a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/List.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/List.swift new file mode 100644 index 00000000000..6568fe28f34 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/List.swift @@ -0,0 +1,32 @@ +// +// List.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct List: Codable { + + public var _123list: String? + + public init(_123list: String? = nil) { + self._123list = _123list + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case _123list = "123-list" + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(_123list, forKey: ._123list) + } +} + diff --git a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/MapTest.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/MapTest.swift new file mode 100644 index 00000000000..eb9634803b3 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/MapTest.swift @@ -0,0 +1,48 @@ +// +// MapTest.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct MapTest: Codable { + + public enum MapOfEnumString: String, Codable, CaseIterable { + case upper = "UPPER" + case lower = "lower" + } + public var mapMapOfString: [String: [String: String]]? + public var mapOfEnumString: [String: String]? + public var directMap: [String: Bool]? + public var indirectMap: StringBooleanMap? + + public init(mapMapOfString: [String: [String: String]]? = nil, mapOfEnumString: [String: String]? = nil, directMap: [String: Bool]? = nil, indirectMap: StringBooleanMap? = nil) { + self.mapMapOfString = mapMapOfString + self.mapOfEnumString = mapOfEnumString + self.directMap = directMap + self.indirectMap = indirectMap + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case mapMapOfString = "map_map_of_string" + case mapOfEnumString = "map_of_enum_string" + case directMap = "direct_map" + case indirectMap = "indirect_map" + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(mapMapOfString, forKey: .mapMapOfString) + try container.encodeIfPresent(mapOfEnumString, forKey: .mapOfEnumString) + try container.encodeIfPresent(directMap, forKey: .directMap) + try container.encodeIfPresent(indirectMap, forKey: .indirectMap) + } +} + diff --git a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/MixedPropertiesAndAdditionalPropertiesClass.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/MixedPropertiesAndAdditionalPropertiesClass.swift new file mode 100644 index 00000000000..4d171a58c80 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/MixedPropertiesAndAdditionalPropertiesClass.swift @@ -0,0 +1,40 @@ +// +// MixedPropertiesAndAdditionalPropertiesClass.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct MixedPropertiesAndAdditionalPropertiesClass: Codable { + + public var uuid: UUID? + public var dateTime: Date? + public var map: [String: Animal]? + + public init(uuid: UUID? = nil, dateTime: Date? = nil, map: [String: Animal]? = nil) { + self.uuid = uuid + self.dateTime = dateTime + self.map = map + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case uuid + case dateTime + case map + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(uuid, forKey: .uuid) + try container.encodeIfPresent(dateTime, forKey: .dateTime) + try container.encodeIfPresent(map, forKey: .map) + } +} + diff --git a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/Model200Response.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/Model200Response.swift new file mode 100644 index 00000000000..24a07e862b8 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/Model200Response.swift @@ -0,0 +1,37 @@ +// +// Model200Response.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +/** Model for testing model name starting with number */ +public struct Model200Response: Codable { + + public var name: Int? + public var _class: String? + + public init(name: Int? = nil, _class: String? = nil) { + self.name = name + self._class = _class + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case name + case _class = "class" + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(name, forKey: .name) + try container.encodeIfPresent(_class, forKey: ._class) + } +} + diff --git a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/Name.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/Name.swift new file mode 100644 index 00000000000..15308075d9a --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/Name.swift @@ -0,0 +1,45 @@ +// +// Name.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +/** Model for testing model name same as property name */ +public struct Name: Codable { + + public var name: Int + public var snakeCase: Int? + public var property: String? + public var _123number: Int? + + public init(name: Int, snakeCase: Int? = nil, property: String? = nil, _123number: Int? = nil) { + self.name = name + self.snakeCase = snakeCase + self.property = property + self._123number = _123number + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case name + case snakeCase = "snake_case" + case property + case _123number = "123Number" + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(name, forKey: .name) + try container.encodeIfPresent(snakeCase, forKey: .snakeCase) + try container.encodeIfPresent(property, forKey: .property) + try container.encodeIfPresent(_123number, forKey: ._123number) + } +} + diff --git a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/NumberOnly.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/NumberOnly.swift new file mode 100644 index 00000000000..555b1beda1d --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/NumberOnly.swift @@ -0,0 +1,32 @@ +// +// NumberOnly.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct NumberOnly: Codable { + + public var justNumber: Double? + + public init(justNumber: Double? = nil) { + self.justNumber = justNumber + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case justNumber = "JustNumber" + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(justNumber, forKey: .justNumber) + } +} + diff --git a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/Order.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/Order.swift new file mode 100644 index 00000000000..be133bc42ad --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/Order.swift @@ -0,0 +1,58 @@ +// +// Order.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct Order: Codable { + + public enum Status: String, Codable, CaseIterable { + case placed = "placed" + case approved = "approved" + case delivered = "delivered" + } + public var id: Int64? + public var petId: Int64? + public var quantity: Int? + public var shipDate: Date? + /** Order Status */ + public var status: Status? + public var complete: Bool? = false + + public init(id: Int64? = nil, petId: Int64? = nil, quantity: Int? = nil, shipDate: Date? = nil, status: Status? = nil, complete: Bool? = false) { + self.id = id + self.petId = petId + self.quantity = quantity + self.shipDate = shipDate + self.status = status + self.complete = complete + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case id + case petId + case quantity + case shipDate + case status + case complete + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(id, forKey: .id) + try container.encodeIfPresent(petId, forKey: .petId) + try container.encodeIfPresent(quantity, forKey: .quantity) + try container.encodeIfPresent(shipDate, forKey: .shipDate) + try container.encodeIfPresent(status, forKey: .status) + try container.encodeIfPresent(complete, forKey: .complete) + } +} + diff --git a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/OuterComposite.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/OuterComposite.swift new file mode 100644 index 00000000000..6e555ae9e1e --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/OuterComposite.swift @@ -0,0 +1,40 @@ +// +// OuterComposite.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct OuterComposite: Codable { + + public var myNumber: Double? + public var myString: String? + public var myBoolean: Bool? + + public init(myNumber: Double? = nil, myString: String? = nil, myBoolean: Bool? = nil) { + self.myNumber = myNumber + self.myString = myString + self.myBoolean = myBoolean + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case myNumber = "my_number" + case myString = "my_string" + case myBoolean = "my_boolean" + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(myNumber, forKey: .myNumber) + try container.encodeIfPresent(myString, forKey: .myString) + try container.encodeIfPresent(myBoolean, forKey: .myBoolean) + } +} + diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/Models/OuterEnum.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/OuterEnum.swift similarity index 89% rename from samples/client/petstore/swift5/urlsessionLibrary/Sources/Models/OuterEnum.swift rename to samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/OuterEnum.swift index 9bd6f3bef8f..76c34b3c2ce 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/Sources/Models/OuterEnum.swift +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/OuterEnum.swift @@ -6,7 +6,9 @@ // import Foundation +#if canImport(AnyCodable) import AnyCodable +#endif public enum OuterEnum: String, Codable, CaseIterable { case placed = "placed" diff --git a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/Pet.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/Pet.swift new file mode 100644 index 00000000000..ddd1186b891 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/Pet.swift @@ -0,0 +1,58 @@ +// +// Pet.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct Pet: Codable, Hashable { + + public enum Status: String, Codable, CaseIterable { + case available = "available" + case pending = "pending" + case sold = "sold" + } + public var id: Int64? + public var category: Category? + public var name: String + public var photoUrls: [String] + public var tags: [Tag]? + /** pet status in the store */ + public var status: Status? + + public init(id: Int64? = nil, category: Category? = nil, name: String, photoUrls: [String], tags: [Tag]? = nil, status: Status? = nil) { + self.id = id + self.category = category + self.name = name + self.photoUrls = photoUrls + self.tags = tags + self.status = status + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case id + case category + case name + case photoUrls + case tags + case status + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(id, forKey: .id) + try container.encodeIfPresent(category, forKey: .category) + try container.encode(name, forKey: .name) + try container.encode(photoUrls, forKey: .photoUrls) + try container.encodeIfPresent(tags, forKey: .tags) + try container.encodeIfPresent(status, forKey: .status) + } +} + diff --git a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/ReadOnlyFirst.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/ReadOnlyFirst.swift new file mode 100644 index 00000000000..b4cd35ad296 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/ReadOnlyFirst.swift @@ -0,0 +1,36 @@ +// +// ReadOnlyFirst.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct ReadOnlyFirst: Codable { + + public var bar: String? + public var baz: String? + + public init(bar: String? = nil, baz: String? = nil) { + self.bar = bar + self.baz = baz + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case bar + case baz + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(bar, forKey: .bar) + try container.encodeIfPresent(baz, forKey: .baz) + } +} + diff --git a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/Return.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/Return.swift new file mode 100644 index 00000000000..f12d1c17fdc --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/Return.swift @@ -0,0 +1,33 @@ +// +// Return.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +/** Model for testing reserved words */ +public struct Return: Codable { + + public var _return: Int? + + public init(_return: Int? = nil) { + self._return = _return + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case _return = "return" + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(_return, forKey: ._return) + } +} + diff --git a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/SpecialModelName.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/SpecialModelName.swift new file mode 100644 index 00000000000..f797e406453 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/SpecialModelName.swift @@ -0,0 +1,32 @@ +// +// SpecialModelName.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct SpecialModelName: Codable { + + public var specialPropertyName: Int64? + + public init(specialPropertyName: Int64? = nil) { + self.specialPropertyName = specialPropertyName + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case specialPropertyName = "$special[property.name]" + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(specialPropertyName, forKey: .specialPropertyName) + } +} + diff --git a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/StringBooleanMap.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/StringBooleanMap.swift new file mode 100644 index 00000000000..1ef2bd41c79 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/StringBooleanMap.swift @@ -0,0 +1,52 @@ +// +// StringBooleanMap.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct StringBooleanMap: Codable { + + + public enum CodingKeys: CodingKey, CaseIterable { + } + + public var additionalProperties: [String: Bool] = [:] + + public subscript(key: String) -> Bool? { + get { + if let value = additionalProperties[key] { + return value + } + return nil + } + + set { + additionalProperties[key] = newValue + } + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + var additionalPropertiesContainer = encoder.container(keyedBy: String.self) + try additionalPropertiesContainer.encodeMap(additionalProperties) + } + + // Decodable protocol methods + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + + var nonAdditionalPropertyKeys = Set() + let additionalPropertiesContainer = try decoder.container(keyedBy: String.self) + additionalProperties = try additionalPropertiesContainer.decodeMap(Bool.self, excludedKeys: nonAdditionalPropertyKeys) + } +} + diff --git a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift new file mode 100644 index 00000000000..07b826264f3 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift @@ -0,0 +1,36 @@ +// +// Tag.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct Tag: Codable, Hashable { + + public var id: Int64? + public var name: String? + + public init(id: Int64? = nil, name: String? = nil) { + self.id = id + self.name = name + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case id + case name + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(id, forKey: .id) + try container.encodeIfPresent(name, forKey: .name) + } +} + diff --git a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderDefault.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderDefault.swift new file mode 100644 index 00000000000..dcf87b413ab --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderDefault.swift @@ -0,0 +1,48 @@ +// +// TypeHolderDefault.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct TypeHolderDefault: Codable { + + public var stringItem: String = "what" + public var numberItem: Double + public var integerItem: Int + public var boolItem: Bool = true + public var arrayItem: [Int] + + public init(stringItem: String = "what", numberItem: Double, integerItem: Int, boolItem: Bool = true, arrayItem: [Int]) { + self.stringItem = stringItem + self.numberItem = numberItem + self.integerItem = integerItem + self.boolItem = boolItem + self.arrayItem = arrayItem + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case stringItem = "string_item" + case numberItem = "number_item" + case integerItem = "integer_item" + case boolItem = "bool_item" + case arrayItem = "array_item" + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(stringItem, forKey: .stringItem) + try container.encode(numberItem, forKey: .numberItem) + try container.encode(integerItem, forKey: .integerItem) + try container.encode(boolItem, forKey: .boolItem) + try container.encode(arrayItem, forKey: .arrayItem) + } +} + diff --git a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderExample.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderExample.swift new file mode 100644 index 00000000000..634f2d55168 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderExample.swift @@ -0,0 +1,48 @@ +// +// TypeHolderExample.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct TypeHolderExample: Codable { + + public var stringItem: String + public var numberItem: Double + public var integerItem: Int + public var boolItem: Bool + public var arrayItem: [Int] + + public init(stringItem: String, numberItem: Double, integerItem: Int, boolItem: Bool, arrayItem: [Int]) { + self.stringItem = stringItem + self.numberItem = numberItem + self.integerItem = integerItem + self.boolItem = boolItem + self.arrayItem = arrayItem + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case stringItem = "string_item" + case numberItem = "number_item" + case integerItem = "integer_item" + case boolItem = "bool_item" + case arrayItem = "array_item" + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(stringItem, forKey: .stringItem) + try container.encode(numberItem, forKey: .numberItem) + try container.encode(integerItem, forKey: .integerItem) + try container.encode(boolItem, forKey: .boolItem) + try container.encode(arrayItem, forKey: .arrayItem) + } +} + diff --git a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/User.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/User.swift new file mode 100644 index 00000000000..bad75dea179 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/User.swift @@ -0,0 +1,61 @@ +// +// User.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct User: Codable { + + public var id: Int64? + public var username: String? + public var firstName: String? + public var lastName: String? + public var email: String? + public var password: String? + public var phone: String? + /** User Status */ + public var userStatus: Int? + + public init(id: Int64? = nil, username: String? = nil, firstName: String? = nil, lastName: String? = nil, email: String? = nil, password: String? = nil, phone: String? = nil, userStatus: Int? = nil) { + self.id = id + self.username = username + self.firstName = firstName + self.lastName = lastName + self.email = email + self.password = password + self.phone = phone + self.userStatus = userStatus + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case id + case username + case firstName + case lastName + case email + case password + case phone + case userStatus + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(id, forKey: .id) + try container.encodeIfPresent(username, forKey: .username) + try container.encodeIfPresent(firstName, forKey: .firstName) + try container.encodeIfPresent(lastName, forKey: .lastName) + try container.encodeIfPresent(email, forKey: .email) + try container.encodeIfPresent(password, forKey: .password) + try container.encodeIfPresent(phone, forKey: .phone) + try container.encodeIfPresent(userStatus, forKey: .userStatus) + } +} + diff --git a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/XmlItem.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/XmlItem.swift new file mode 100644 index 00000000000..896202b00ec --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models/XmlItem.swift @@ -0,0 +1,143 @@ +// +// XmlItem.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +import AnyCodable + +public struct XmlItem: Codable { + + public var attributeString: String? + public var attributeNumber: Double? + public var attributeInteger: Int? + public var attributeBoolean: Bool? + public var wrappedArray: [Int]? + public var nameString: String? + public var nameNumber: Double? + public var nameInteger: Int? + public var nameBoolean: Bool? + public var nameArray: [Int]? + public var nameWrappedArray: [Int]? + public var prefixString: String? + public var prefixNumber: Double? + public var prefixInteger: Int? + public var prefixBoolean: Bool? + public var prefixArray: [Int]? + public var prefixWrappedArray: [Int]? + public var namespaceString: String? + public var namespaceNumber: Double? + public var namespaceInteger: Int? + public var namespaceBoolean: Bool? + public var namespaceArray: [Int]? + public var namespaceWrappedArray: [Int]? + public var prefixNsString: String? + public var prefixNsNumber: Double? + public var prefixNsInteger: Int? + public var prefixNsBoolean: Bool? + public var prefixNsArray: [Int]? + public var prefixNsWrappedArray: [Int]? + + public init(attributeString: String? = nil, attributeNumber: Double? = nil, attributeInteger: Int? = nil, attributeBoolean: Bool? = nil, wrappedArray: [Int]? = nil, nameString: String? = nil, nameNumber: Double? = nil, nameInteger: Int? = nil, nameBoolean: Bool? = nil, nameArray: [Int]? = nil, nameWrappedArray: [Int]? = nil, prefixString: String? = nil, prefixNumber: Double? = nil, prefixInteger: Int? = nil, prefixBoolean: Bool? = nil, prefixArray: [Int]? = nil, prefixWrappedArray: [Int]? = nil, namespaceString: String? = nil, namespaceNumber: Double? = nil, namespaceInteger: Int? = nil, namespaceBoolean: Bool? = nil, namespaceArray: [Int]? = nil, namespaceWrappedArray: [Int]? = nil, prefixNsString: String? = nil, prefixNsNumber: Double? = nil, prefixNsInteger: Int? = nil, prefixNsBoolean: Bool? = nil, prefixNsArray: [Int]? = nil, prefixNsWrappedArray: [Int]? = nil) { + self.attributeString = attributeString + self.attributeNumber = attributeNumber + self.attributeInteger = attributeInteger + self.attributeBoolean = attributeBoolean + self.wrappedArray = wrappedArray + self.nameString = nameString + self.nameNumber = nameNumber + self.nameInteger = nameInteger + self.nameBoolean = nameBoolean + self.nameArray = nameArray + self.nameWrappedArray = nameWrappedArray + self.prefixString = prefixString + self.prefixNumber = prefixNumber + self.prefixInteger = prefixInteger + self.prefixBoolean = prefixBoolean + self.prefixArray = prefixArray + self.prefixWrappedArray = prefixWrappedArray + self.namespaceString = namespaceString + self.namespaceNumber = namespaceNumber + self.namespaceInteger = namespaceInteger + self.namespaceBoolean = namespaceBoolean + self.namespaceArray = namespaceArray + self.namespaceWrappedArray = namespaceWrappedArray + self.prefixNsString = prefixNsString + self.prefixNsNumber = prefixNsNumber + self.prefixNsInteger = prefixNsInteger + self.prefixNsBoolean = prefixNsBoolean + self.prefixNsArray = prefixNsArray + self.prefixNsWrappedArray = prefixNsWrappedArray + } + public enum CodingKeys: String, CodingKey, CaseIterable { + case attributeString = "attribute_string" + case attributeNumber = "attribute_number" + case attributeInteger = "attribute_integer" + case attributeBoolean = "attribute_boolean" + case wrappedArray = "wrapped_array" + case nameString = "name_string" + case nameNumber = "name_number" + case nameInteger = "name_integer" + case nameBoolean = "name_boolean" + case nameArray = "name_array" + case nameWrappedArray = "name_wrapped_array" + case prefixString = "prefix_string" + case prefixNumber = "prefix_number" + case prefixInteger = "prefix_integer" + case prefixBoolean = "prefix_boolean" + case prefixArray = "prefix_array" + case prefixWrappedArray = "prefix_wrapped_array" + case namespaceString = "namespace_string" + case namespaceNumber = "namespace_number" + case namespaceInteger = "namespace_integer" + case namespaceBoolean = "namespace_boolean" + case namespaceArray = "namespace_array" + case namespaceWrappedArray = "namespace_wrapped_array" + case prefixNsString = "prefix_ns_string" + case prefixNsNumber = "prefix_ns_number" + case prefixNsInteger = "prefix_ns_integer" + case prefixNsBoolean = "prefix_ns_boolean" + case prefixNsArray = "prefix_ns_array" + case prefixNsWrappedArray = "prefix_ns_wrapped_array" + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(attributeString, forKey: .attributeString) + try container.encodeIfPresent(attributeNumber, forKey: .attributeNumber) + try container.encodeIfPresent(attributeInteger, forKey: .attributeInteger) + try container.encodeIfPresent(attributeBoolean, forKey: .attributeBoolean) + try container.encodeIfPresent(wrappedArray, forKey: .wrappedArray) + try container.encodeIfPresent(nameString, forKey: .nameString) + try container.encodeIfPresent(nameNumber, forKey: .nameNumber) + try container.encodeIfPresent(nameInteger, forKey: .nameInteger) + try container.encodeIfPresent(nameBoolean, forKey: .nameBoolean) + try container.encodeIfPresent(nameArray, forKey: .nameArray) + try container.encodeIfPresent(nameWrappedArray, forKey: .nameWrappedArray) + try container.encodeIfPresent(prefixString, forKey: .prefixString) + try container.encodeIfPresent(prefixNumber, forKey: .prefixNumber) + try container.encodeIfPresent(prefixInteger, forKey: .prefixInteger) + try container.encodeIfPresent(prefixBoolean, forKey: .prefixBoolean) + try container.encodeIfPresent(prefixArray, forKey: .prefixArray) + try container.encodeIfPresent(prefixWrappedArray, forKey: .prefixWrappedArray) + try container.encodeIfPresent(namespaceString, forKey: .namespaceString) + try container.encodeIfPresent(namespaceNumber, forKey: .namespaceNumber) + try container.encodeIfPresent(namespaceInteger, forKey: .namespaceInteger) + try container.encodeIfPresent(namespaceBoolean, forKey: .namespaceBoolean) + try container.encodeIfPresent(namespaceArray, forKey: .namespaceArray) + try container.encodeIfPresent(namespaceWrappedArray, forKey: .namespaceWrappedArray) + try container.encodeIfPresent(prefixNsString, forKey: .prefixNsString) + try container.encodeIfPresent(prefixNsNumber, forKey: .prefixNsNumber) + try container.encodeIfPresent(prefixNsInteger, forKey: .prefixNsInteger) + try container.encodeIfPresent(prefixNsBoolean, forKey: .prefixNsBoolean) + try container.encodeIfPresent(prefixNsArray, forKey: .prefixNsArray) + try container.encodeIfPresent(prefixNsWrappedArray, forKey: .prefixNsWrappedArray) + } + + + +} diff --git a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/OpenISO8601DateFormatter.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/OpenISO8601DateFormatter.swift new file mode 100644 index 00000000000..e06208074cd --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/OpenISO8601DateFormatter.swift @@ -0,0 +1,44 @@ +// +// OpenISO8601DateFormatter.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation + +// https://stackoverflow.com/a/50281094/976628 +public class OpenISO8601DateFormatter: DateFormatter { + static let withoutSeconds: DateFormatter = { + let formatter = DateFormatter() + formatter.calendar = Calendar(identifier: .iso8601) + formatter.locale = Locale(identifier: "en_US_POSIX") + formatter.timeZone = TimeZone(secondsFromGMT: 0) + formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ" + return formatter + }() + + private func setup() { + calendar = Calendar(identifier: .iso8601) + locale = Locale(identifier: "en_US_POSIX") + timeZone = TimeZone(secondsFromGMT: 0) + dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ" + } + + override init() { + super.init() + setup() + } + + required init?(coder aDecoder: NSCoder) { + super.init(coder: aDecoder) + setup() + } + + override public func date(from string: String) -> Date? { + if let result = super.date(from: string) { + return result + } + return OpenISO8601DateFormatter.withoutSeconds.date(from: string) + } +} diff --git a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/SynchronizedDictionary.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/SynchronizedDictionary.swift new file mode 100644 index 00000000000..acf7ff4031b --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/SynchronizedDictionary.swift @@ -0,0 +1,36 @@ +// SynchronizedDictionary.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation + +internal struct SynchronizedDictionary { + + private var dictionary = [K: V]() + private let queue = DispatchQueue( + label: "SynchronizedDictionary", + qos: DispatchQoS.userInitiated, + attributes: [DispatchQueue.Attributes.concurrent], + autoreleaseFrequency: DispatchQueue.AutoreleaseFrequency.inherit, + target: nil + ) + + internal subscript(key: K) -> V? { + get { + var value: V? + + queue.sync { + value = self.dictionary[key] + } + + return value + } + set { + queue.sync(flags: DispatchWorkItemFlags.barrier) { + self.dictionary[key] = newValue + } + } + } +} 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 new file mode 100644 index 00000000000..41959190a26 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift @@ -0,0 +1,649 @@ +// URLSessionImplementations.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if !os(macOS) +import MobileCoreServices +#endif + +class URLSessionRequestBuilderFactory: RequestBuilderFactory { + func getNonDecodableBuilder() -> RequestBuilder.Type { + return URLSessionRequestBuilder.self + } + + func getBuilder() -> RequestBuilder.Type { + return URLSessionDecodableRequestBuilder.self + } +} + +// Store the URLSession to retain its reference +private var urlSessionStore = SynchronizedDictionary() + +open class URLSessionRequestBuilder: RequestBuilder { + + /** + May be assigned if you want to control the authentication challenges. + */ + public var taskDidReceiveChallenge: ((URLSession, URLSessionTask, URLAuthenticationChallenge) -> (URLSession.AuthChallengeDisposition, URLCredential?))? + + /** + May be assigned if you want to do any of those things: + - control the task completion + - intercept and handle errors like authorization + - retry the request. + */ + @available(*, deprecated, message: "Please override execute() method to intercept and handle errors like authorization or retry the request. Check the Wiki for more info. https://github.com/OpenAPITools/openapi-generator/wiki/FAQ#how-do-i-implement-bearer-token-authentication-with-urlsession-on-the-swift-api-client") + public var taskCompletionShouldRetry: ((Data?, URLResponse?, Error?, @escaping (Bool) -> Void) -> Void)? + + required public init(method: String, URLString: String, parameters: [String: Any]?, headers: [String: String] = [:]) { + super.init(method: method, URLString: URLString, parameters: parameters, headers: headers) + } + + /** + May be overridden by a subclass if you want to control the URLSession + configuration. + */ + open func createURLSession() -> URLSession { + let configuration = URLSessionConfiguration.default + configuration.httpAdditionalHeaders = buildHeaders() + let sessionDelegate = SessionDelegate() + sessionDelegate.credential = credential + sessionDelegate.taskDidReceiveChallenge = taskDidReceiveChallenge + return URLSession(configuration: configuration, delegate: sessionDelegate, delegateQueue: nil) + } + + /** + May be overridden by a subclass if you want to control the Content-Type + that is given to an uploaded form part. + + Return nil to use the default behavior (inferring the Content-Type from + the file extension). Return the desired Content-Type otherwise. + */ + open func contentTypeForFormPart(fileURL: URL) -> String? { + return nil + } + + /** + May be overridden by a subclass if you want to control the URLRequest + configuration (e.g. to override the cache policy). + */ + open func createURLRequest(urlSession: URLSession, method: HTTPMethod, encoding: ParameterEncoding, headers: [String: String]) throws -> URLRequest { + + guard let url = URL(string: URLString) else { + throw DownloadException.requestMissingURL + } + + var originalRequest = URLRequest(url: url) + + originalRequest.httpMethod = method.rawValue + + headers.forEach { key, value in + originalRequest.setValue(value, forHTTPHeaderField: key) + } + + buildHeaders().forEach { key, value in + originalRequest.setValue(value, forHTTPHeaderField: key) + } + + let modifiedRequest = try encoding.encode(originalRequest, with: parameters) + + return modifiedRequest + } + + override open func execute(_ apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, _ completion: @escaping (_ result: Swift.Result, Error>) -> Void) { + let urlSessionId = UUID().uuidString + // Create a new manager for each request to customize its request header + let urlSession = createURLSession() + urlSessionStore[urlSessionId] = urlSession + + guard let xMethod = HTTPMethod(rawValue: method) else { + fatalError("Unsupported Http method - \(method)") + } + + let encoding: ParameterEncoding + + switch xMethod { + case .get, .head: + encoding = URLEncoding() + + case .options, .post, .put, .patch, .delete, .trace, .connect: + let contentType = headers["Content-Type"] ?? "application/json" + + if contentType == "application/json" { + encoding = JSONDataEncoding() + } else if contentType == "multipart/form-data" { + encoding = FormDataEncoding(contentTypeForFormPart: contentTypeForFormPart(fileURL:)) + } else if contentType == "application/x-www-form-urlencoded" { + encoding = FormURLEncoding() + } else { + fatalError("Unsupported Media Type - \(contentType)") + } + } + + let cleanupRequest = { + urlSessionStore[urlSessionId]?.finishTasksAndInvalidate() + urlSessionStore[urlSessionId] = nil + } + + do { + let request = try createURLRequest(urlSession: urlSession, method: xMethod, encoding: encoding, headers: headers) + + let dataTask = urlSession.dataTask(with: request) { data, response, error in + + if let taskCompletionShouldRetry = self.taskCompletionShouldRetry { + + taskCompletionShouldRetry(data, response, error) { shouldRetry in + + if shouldRetry { + cleanupRequest() + self.execute(apiResponseQueue, completion) + } else { + apiResponseQueue.async { + self.processRequestResponse(urlRequest: request, data: data, response: response, error: error, completion: completion) + cleanupRequest() + } + } + } + } else { + apiResponseQueue.async { + self.processRequestResponse(urlRequest: request, data: data, response: response, error: error, completion: completion) + cleanupRequest() + } + } + } + + if #available(iOS 11.0, macOS 10.13, macCatalyst 13.0, tvOS 11.0, watchOS 4.0, *) { + onProgressReady?(dataTask.progress) + } + + dataTask.resume() + + } catch { + apiResponseQueue.async { + cleanupRequest() + completion(.failure(ErrorResponse.error(415, nil, nil, error))) + } + } + } + + fileprivate func processRequestResponse(urlRequest: URLRequest, data: Data?, response: URLResponse?, error: Error?, completion: @escaping (_ result: Swift.Result, Error>) -> Void) { + + if let error = error { + completion(.failure(ErrorResponse.error(-1, data, response, error))) + return + } + + guard let httpResponse = response as? HTTPURLResponse else { + completion(.failure(ErrorResponse.error(-2, data, response, DecodableRequestBuilderError.nilHTTPResponse))) + return + } + + guard httpResponse.isStatusCodeSuccessful else { + completion(.failure(ErrorResponse.error(httpResponse.statusCode, data, response, DecodableRequestBuilderError.unsuccessfulHTTPStatusCode))) + return + } + + switch T.self { + case is String.Type: + + let body = data.flatMap { String(data: $0, encoding: .utf8) } ?? "" + + completion(.success(Response(response: httpResponse, body: body as? T))) + + case is URL.Type: + do { + + guard error == nil else { + throw DownloadException.responseFailed + } + + guard let data = data else { + throw DownloadException.responseDataMissing + } + + let fileManager = FileManager.default + let cachesDirectory = fileManager.urls(for: .cachesDirectory, in: .userDomainMask)[0] + let requestURL = try getURL(from: urlRequest) + + var requestPath = try getPath(from: requestURL) + + if let headerFileName = getFileName(fromContentDisposition: httpResponse.allHeaderFields["Content-Disposition"] as? String) { + requestPath = requestPath.appending("/\(headerFileName)") + } else { + requestPath = requestPath.appending("/tmp.PetstoreClient.\(UUID().uuidString)") + } + + let filePath = cachesDirectory.appendingPathComponent(requestPath) + let directoryPath = filePath.deletingLastPathComponent().path + + try fileManager.createDirectory(atPath: directoryPath, withIntermediateDirectories: true, attributes: nil) + try data.write(to: filePath, options: .atomic) + + completion(.success(Response(response: httpResponse, body: filePath as? T))) + + } catch let requestParserError as DownloadException { + completion(.failure(ErrorResponse.error(400, data, response, requestParserError))) + } catch { + completion(.failure(ErrorResponse.error(400, data, response, error))) + } + + case is Void.Type: + + completion(.success(Response(response: httpResponse, body: nil))) + + case is Data.Type: + + completion(.success(Response(response: httpResponse, body: data as? T))) + + default: + + completion(.success(Response(response: httpResponse, body: data as? T))) + } + + } + + open func buildHeaders() -> [String: String] { + var httpHeaders: [String: String] = [:] + for (key, value) in headers { + httpHeaders[key] = value + } + for (key, value) in PetstoreClient.customHeaders { + httpHeaders[key] = value + } + return httpHeaders + } + + fileprivate func getFileName(fromContentDisposition contentDisposition: String?) -> String? { + + guard let contentDisposition = contentDisposition else { + return nil + } + + let items = contentDisposition.components(separatedBy: ";") + + var filename: String? + + for contentItem in items { + + let filenameKey = "filename=" + guard let range = contentItem.range(of: filenameKey) else { + break + } + + filename = contentItem + return filename? + .replacingCharacters(in: range, with: "") + .replacingOccurrences(of: "\"", with: "") + .trimmingCharacters(in: .whitespacesAndNewlines) + } + + return filename + + } + + fileprivate func getPath(from url: URL) throws -> String { + + guard var path = URLComponents(url: url, resolvingAgainstBaseURL: true)?.path else { + throw DownloadException.requestMissingPath + } + + if path.hasPrefix("/") { + path.remove(at: path.startIndex) + } + + return path + + } + + fileprivate func getURL(from urlRequest: URLRequest) throws -> URL { + + guard let url = urlRequest.url else { + throw DownloadException.requestMissingURL + } + + return url + } + +} + +open class URLSessionDecodableRequestBuilder: URLSessionRequestBuilder { + override fileprivate func processRequestResponse(urlRequest: URLRequest, data: Data?, response: URLResponse?, error: Error?, completion: @escaping (_ result: Swift.Result, Error>) -> Void) { + + if let error = error { + completion(.failure(ErrorResponse.error(-1, data, response, error))) + return + } + + guard let httpResponse = response as? HTTPURLResponse else { + completion(.failure(ErrorResponse.error(-2, data, response, DecodableRequestBuilderError.nilHTTPResponse))) + return + } + + guard httpResponse.isStatusCodeSuccessful else { + completion(.failure(ErrorResponse.error(httpResponse.statusCode, data, response, DecodableRequestBuilderError.unsuccessfulHTTPStatusCode))) + return + } + + switch T.self { + case is String.Type: + + let body = data.flatMap { String(data: $0, encoding: .utf8) } ?? "" + + completion(.success(Response(response: httpResponse, body: body as? T))) + + case is URL.Type: + do { + + guard error == nil else { + throw DownloadException.responseFailed + } + + guard let data = data else { + throw DownloadException.responseDataMissing + } + + let fileManager = FileManager.default + let cachesDirectory = fileManager.urls(for: .cachesDirectory, in: .userDomainMask)[0] + let requestURL = try getURL(from: urlRequest) + + var requestPath = try getPath(from: requestURL) + + if let headerFileName = getFileName(fromContentDisposition: httpResponse.allHeaderFields["Content-Disposition"] as? String) { + requestPath = requestPath.appending("/\(headerFileName)") + } else { + requestPath = requestPath.appending("/tmp.PetstoreClient.\(UUID().uuidString)") + } + + let filePath = cachesDirectory.appendingPathComponent(requestPath) + let directoryPath = filePath.deletingLastPathComponent().path + + try fileManager.createDirectory(atPath: directoryPath, withIntermediateDirectories: true, attributes: nil) + try data.write(to: filePath, options: .atomic) + + completion(.success(Response(response: httpResponse, body: filePath as? T))) + + } catch let requestParserError as DownloadException { + completion(.failure(ErrorResponse.error(400, data, response, requestParserError))) + } catch { + completion(.failure(ErrorResponse.error(400, data, response, error))) + } + + case is Void.Type: + + completion(.success(Response(response: httpResponse, body: nil))) + + case is Data.Type: + + completion(.success(Response(response: httpResponse, body: data as? T))) + + default: + + guard let data = data, !data.isEmpty else { + completion(.failure(ErrorResponse.error(httpResponse.statusCode, nil, response, DecodableRequestBuilderError.emptyDataResponse))) + return + } + + let decodeResult = CodableHelper.decode(T.self, from: data) + + switch decodeResult { + case let .success(decodableObj): + completion(.success(Response(response: httpResponse, body: decodableObj))) + case let .failure(error): + completion(.failure(ErrorResponse.error(httpResponse.statusCode, data, response, error))) + } + } + } +} + +private class SessionDelegate: NSObject, URLSessionDelegate, URLSessionDataDelegate { + + var credential: URLCredential? + + var taskDidReceiveChallenge: ((URLSession, URLSessionTask, URLAuthenticationChallenge) -> (URLSession.AuthChallengeDisposition, URLCredential?))? + + func urlSession(_ session: URLSession, task: URLSessionTask, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) { + + var disposition: URLSession.AuthChallengeDisposition = .performDefaultHandling + + var credential: URLCredential? + + if let taskDidReceiveChallenge = taskDidReceiveChallenge { + (disposition, credential) = taskDidReceiveChallenge(session, task, challenge) + } else { + if challenge.previousFailureCount > 0 { + disposition = .rejectProtectionSpace + } else { + credential = self.credential ?? session.configuration.urlCredentialStorage?.defaultCredential(for: challenge.protectionSpace) + + if credential != nil { + disposition = .useCredential + } + } + } + + completionHandler(disposition, credential) + } +} + +public enum HTTPMethod: String { + case options = "OPTIONS" + case get = "GET" + case head = "HEAD" + case post = "POST" + case put = "PUT" + case patch = "PATCH" + case delete = "DELETE" + case trace = "TRACE" + case connect = "CONNECT" +} + +public protocol ParameterEncoding { + func encode(_ urlRequest: URLRequest, with parameters: [String: Any]?) throws -> URLRequest +} + +private class URLEncoding: ParameterEncoding { + func encode(_ urlRequest: URLRequest, with parameters: [String: Any]?) throws -> URLRequest { + + var urlRequest = urlRequest + + guard let parameters = parameters else { return urlRequest } + + guard let url = urlRequest.url else { + throw DownloadException.requestMissingURL + } + + if var urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false), !parameters.isEmpty { + urlComponents.queryItems = APIHelper.mapValuesToQueryItems(parameters) + urlRequest.url = urlComponents.url + } + + return urlRequest + } +} + +private class FormDataEncoding: ParameterEncoding { + + let contentTypeForFormPart: (_ fileURL: URL) -> String? + + init(contentTypeForFormPart: @escaping (_ fileURL: URL) -> String?) { + self.contentTypeForFormPart = contentTypeForFormPart + } + + func encode(_ urlRequest: URLRequest, with parameters: [String: Any]?) throws -> URLRequest { + + var urlRequest = urlRequest + + guard let parameters = parameters, !parameters.isEmpty else { + return urlRequest + } + + let boundary = "Boundary-\(UUID().uuidString)" + + urlRequest.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type") + + for (key, value) in parameters { + switch value { + case let fileURL as URL: + + urlRequest = try configureFileUploadRequest( + urlRequest: urlRequest, + boundary: boundary, + name: key, + fileURL: fileURL + ) + + case let string as String: + + if let data = string.data(using: .utf8) { + urlRequest = configureDataUploadRequest( + urlRequest: urlRequest, + boundary: boundary, + name: key, + data: data + ) + } + + case let number as NSNumber: + + if let data = number.stringValue.data(using: .utf8) { + urlRequest = configureDataUploadRequest( + urlRequest: urlRequest, + boundary: boundary, + name: key, + data: data + ) + } + + default: + fatalError("Unprocessable value \(value) with key \(key)") + } + } + + var body = urlRequest.httpBody.orEmpty + + body.append("\r\n--\(boundary)--\r\n") + + urlRequest.httpBody = body + + return urlRequest + } + + private func configureFileUploadRequest(urlRequest: URLRequest, boundary: String, name: String, fileURL: URL) throws -> URLRequest { + + var urlRequest = urlRequest + + var body = urlRequest.httpBody.orEmpty + + let fileData = try Data(contentsOf: fileURL) + + let mimetype = contentTypeForFormPart(fileURL) ?? mimeType(for: fileURL) + + let fileName = fileURL.lastPathComponent + + // If we already added something then we need an additional newline. + if body.count > 0 { + body.append("\r\n") + } + + // Value boundary. + body.append("--\(boundary)\r\n") + + // Value headers. + body.append("Content-Disposition: form-data; name=\"\(name)\"; filename=\"\(fileName)\"\r\n") + body.append("Content-Type: \(mimetype)\r\n") + + // Separate headers and body. + body.append("\r\n") + + // The value data. + body.append(fileData) + + urlRequest.httpBody = body + + return urlRequest + } + + private func configureDataUploadRequest(urlRequest: URLRequest, boundary: String, name: String, data: Data) -> URLRequest { + + var urlRequest = urlRequest + + var body = urlRequest.httpBody.orEmpty + + // If we already added something then we need an additional newline. + if body.count > 0 { + body.append("\r\n") + } + + // Value boundary. + body.append("--\(boundary)\r\n") + + // Value headers. + body.append("Content-Disposition: form-data; name=\"\(name)\"\r\n") + + // Separate headers and body. + body.append("\r\n") + + // The value data. + body.append(data) + + urlRequest.httpBody = body + + return urlRequest + + } + + func mimeType(for url: URL) -> String { + let pathExtension = url.pathExtension + + if let uti = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, pathExtension as NSString, nil)?.takeRetainedValue() { + if let mimetype = UTTypeCopyPreferredTagWithClass(uti, kUTTagClassMIMEType)?.takeRetainedValue() { + return mimetype as String + } + } + return "application/octet-stream" + } + +} + +private class FormURLEncoding: ParameterEncoding { + func encode(_ urlRequest: URLRequest, with parameters: [String: Any]?) throws -> URLRequest { + + var urlRequest = urlRequest + + var requestBodyComponents = URLComponents() + requestBodyComponents.queryItems = APIHelper.mapValuesToQueryItems(parameters ?? [:]) + + if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil { + urlRequest.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") + } + + urlRequest.httpBody = requestBodyComponents.query?.data(using: .utf8) + + return urlRequest + } +} + +private extension Data { + /// Append string to Data + /// + /// Rather than littering my code with calls to `dataUsingEncoding` to convert strings to Data, and then add that data to the Data, this wraps it in a nice convenient little extension to Data. This converts using UTF-8. + /// + /// - parameter string: The string to be added to the `Data`. + + mutating func append(_ string: String) { + if let data = string.data(using: .utf8) { + append(data) + } + } +} + +private extension Optional where Wrapped == Data { + var orEmpty: Data { + self ?? Data() + } +} + +extension JSONDataEncoding: ParameterEncoding {} diff --git a/samples/client/petstore/swift5/x-swift-hashable/README.md b/samples/client/petstore/swift5/x-swift-hashable/README.md new file mode 100644 index 00000000000..1725415f7e0 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/README.md @@ -0,0 +1,141 @@ +# Swift5 API client for PetstoreClient + +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 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.Swift5ClientCodegen + +## Installation + +### Carthage + +Run `carthage update` + +### CocoaPods + +Run `pod install` + +## Documentation for API Endpoints + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +Class | Method | HTTP request | Description +------------ | ------------- | ------------- | ------------- +*AnotherFakeAPI* | [**call123testSpecialTags**](docs/AnotherFakeAPI.md#call123testspecialtags) | **PATCH** /another-fake/dummy | To test special tags +*FakeAPI* | [**fakeOuterBooleanSerialize**](docs/FakeAPI.md#fakeouterbooleanserialize) | **POST** /fake/outer/boolean | +*FakeAPI* | [**fakeOuterCompositeSerialize**](docs/FakeAPI.md#fakeoutercompositeserialize) | **POST** /fake/outer/composite | +*FakeAPI* | [**fakeOuterNumberSerialize**](docs/FakeAPI.md#fakeouternumberserialize) | **POST** /fake/outer/number | +*FakeAPI* | [**fakeOuterStringSerialize**](docs/FakeAPI.md#fakeouterstringserialize) | **POST** /fake/outer/string | +*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 +*FakeAPI* | [**testEndpointParameters**](docs/FakeAPI.md#testendpointparameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 +*FakeAPI* | [**testEnumParameters**](docs/FakeAPI.md#testenumparameters) | **GET** /fake | To test enum parameters +*FakeAPI* | [**testGroupParameters**](docs/FakeAPI.md#testgroupparameters) | **DELETE** /fake | Fake endpoint to test group parameters (optional) +*FakeAPI* | [**testInlineAdditionalProperties**](docs/FakeAPI.md#testinlineadditionalproperties) | **POST** /fake/inline-additionalProperties | test inline additionalProperties +*FakeAPI* | [**testJsonFormData**](docs/FakeAPI.md#testjsonformdata) | **GET** /fake/jsonFormData | test json serialization of form data +*FakeClassnameTags123API* | [**testClassname**](docs/FakeClassnameTags123API.md#testclassname) | **PATCH** /fake_classname_test | To test class name in snake case +*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 +*PetAPI* | [**uploadFileWithRequiredFile**](docs/PetAPI.md#uploadfilewithrequiredfile) | **POST** /fake/{petId}/uploadImageWithRequiredFile | uploads an image (required) +*StoreAPI* | [**deleteOrder**](docs/StoreAPI.md#deleteorder) | **DELETE** /store/order/{order_id} | 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/{order_id} | 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 + + - [AdditionalPropertiesClass](docs/AdditionalPropertiesClass.md) + - [Animal](docs/Animal.md) + - [AnimalFarm](docs/AnimalFarm.md) + - [ApiResponse](docs/ApiResponse.md) + - [ArrayOfArrayOfNumberOnly](docs/ArrayOfArrayOfNumberOnly.md) + - [ArrayOfNumberOnly](docs/ArrayOfNumberOnly.md) + - [ArrayTest](docs/ArrayTest.md) + - [Capitalization](docs/Capitalization.md) + - [Cat](docs/Cat.md) + - [CatAllOf](docs/CatAllOf.md) + - [Category](docs/Category.md) + - [ClassModel](docs/ClassModel.md) + - [Client](docs/Client.md) + - [Dog](docs/Dog.md) + - [DogAllOf](docs/DogAllOf.md) + - [EnumArrays](docs/EnumArrays.md) + - [EnumClass](docs/EnumClass.md) + - [EnumTest](docs/EnumTest.md) + - [File](docs/File.md) + - [FileSchemaTestClass](docs/FileSchemaTestClass.md) + - [FormatTest](docs/FormatTest.md) + - [HasOnlyReadOnly](docs/HasOnlyReadOnly.md) + - [List](docs/List.md) + - [MapTest](docs/MapTest.md) + - [MixedPropertiesAndAdditionalPropertiesClass](docs/MixedPropertiesAndAdditionalPropertiesClass.md) + - [Model200Response](docs/Model200Response.md) + - [Name](docs/Name.md) + - [NumberOnly](docs/NumberOnly.md) + - [Order](docs/Order.md) + - [OuterComposite](docs/OuterComposite.md) + - [OuterEnum](docs/OuterEnum.md) + - [Pet](docs/Pet.md) + - [ReadOnlyFirst](docs/ReadOnlyFirst.md) + - [Return](docs/Return.md) + - [SpecialModelName](docs/SpecialModelName.md) + - [StringBooleanMap](docs/StringBooleanMap.md) + - [Tag](docs/Tag.md) + - [TypeHolderDefault](docs/TypeHolderDefault.md) + - [TypeHolderExample](docs/TypeHolderExample.md) + - [User](docs/User.md) + + +## Documentation For Authorization + + +## api_key + +- **Type**: API key +- **API key parameter name**: api_key +- **Location**: HTTP header + +## api_key_query + +- **Type**: API key +- **API key parameter name**: api_key_query +- **Location**: URL query string + +## http_basic_test + +- **Type**: HTTP basic authentication + +## 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 + + +## Author + + + diff --git a/samples/client/petstore/swift5/x-swift-hashable/docs/AdditionalPropertiesAnyType.md b/samples/client/petstore/swift5/x-swift-hashable/docs/AdditionalPropertiesAnyType.md new file mode 100644 index 00000000000..bae60ab148f --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/docs/AdditionalPropertiesAnyType.md @@ -0,0 +1,10 @@ +# AdditionalPropertiesAnyType + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **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/swift5/x-swift-hashable/docs/AdditionalPropertiesArray.md b/samples/client/petstore/swift5/x-swift-hashable/docs/AdditionalPropertiesArray.md new file mode 100644 index 00000000000..a371b5e28f3 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/docs/AdditionalPropertiesArray.md @@ -0,0 +1,10 @@ +# AdditionalPropertiesArray + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **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/swift5/x-swift-hashable/docs/AdditionalPropertiesBoolean.md b/samples/client/petstore/swift5/x-swift-hashable/docs/AdditionalPropertiesBoolean.md new file mode 100644 index 00000000000..d5f0d6da11e --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/docs/AdditionalPropertiesBoolean.md @@ -0,0 +1,10 @@ +# AdditionalPropertiesBoolean + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **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/swift5/x-swift-hashable/docs/AdditionalPropertiesClass.md b/samples/client/petstore/swift5/x-swift-hashable/docs/AdditionalPropertiesClass.md new file mode 100644 index 00000000000..1f222244134 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/docs/AdditionalPropertiesClass.md @@ -0,0 +1,11 @@ +# AdditionalPropertiesClass + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**mapString** | **[String: String]** | | [optional] +**mapMapString** | [String: [String: 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/swift5/x-swift-hashable/docs/AdditionalPropertiesInteger.md b/samples/client/petstore/swift5/x-swift-hashable/docs/AdditionalPropertiesInteger.md new file mode 100644 index 00000000000..629293abdfe --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/docs/AdditionalPropertiesInteger.md @@ -0,0 +1,10 @@ +# AdditionalPropertiesInteger + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **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/swift5/x-swift-hashable/docs/AdditionalPropertiesNumber.md b/samples/client/petstore/swift5/x-swift-hashable/docs/AdditionalPropertiesNumber.md new file mode 100644 index 00000000000..65adfe78137 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/docs/AdditionalPropertiesNumber.md @@ -0,0 +1,10 @@ +# AdditionalPropertiesNumber + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **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/swift5/x-swift-hashable/docs/AdditionalPropertiesObject.md b/samples/client/petstore/swift5/x-swift-hashable/docs/AdditionalPropertiesObject.md new file mode 100644 index 00000000000..99d69b7aae6 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/docs/AdditionalPropertiesObject.md @@ -0,0 +1,10 @@ +# AdditionalPropertiesObject + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **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/swift5/x-swift-hashable/docs/AdditionalPropertiesString.md b/samples/client/petstore/swift5/x-swift-hashable/docs/AdditionalPropertiesString.md new file mode 100644 index 00000000000..5bb8122887c --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/docs/AdditionalPropertiesString.md @@ -0,0 +1,10 @@ +# AdditionalPropertiesString + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **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/swift5/x-swift-hashable/docs/Animal.md b/samples/client/petstore/swift5/x-swift-hashable/docs/Animal.md new file mode 100644 index 00000000000..69c601455cd --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/docs/Animal.md @@ -0,0 +1,11 @@ +# Animal + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**className** | **String** | | +**color** | **String** | | [optional] [default to "red"] + +[[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/swift5/x-swift-hashable/docs/AnimalFarm.md b/samples/client/petstore/swift5/x-swift-hashable/docs/AnimalFarm.md new file mode 100644 index 00000000000..df6bab21dae --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/docs/AnimalFarm.md @@ -0,0 +1,9 @@ +# AnimalFarm + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +[[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/swift5/x-swift-hashable/docs/AnotherFakeAPI.md b/samples/client/petstore/swift5/x-swift-hashable/docs/AnotherFakeAPI.md new file mode 100644 index 00000000000..aead5f1f980 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/docs/AnotherFakeAPI.md @@ -0,0 +1,59 @@ +# AnotherFakeAPI + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**call123testSpecialTags**](AnotherFakeAPI.md#call123testspecialtags) | **PATCH** /another-fake/dummy | To test special tags + + +# **call123testSpecialTags** +```swift + open class func call123testSpecialTags(body: Client, completion: @escaping (_ data: Client?, _ error: Error?) -> Void) +``` + +To test special tags + +To test special tags and operation ID starting with number + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let body = Client(client: "client_example") // Client | client model + +// To test special tags +AnotherFakeAPI.call123testSpecialTags(body: body) { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**Client**](Client.md) | client model | + +### Return type + +[**Client**](Client.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) + diff --git a/samples/client/petstore/swift5/x-swift-hashable/docs/ApiResponse.md b/samples/client/petstore/swift5/x-swift-hashable/docs/ApiResponse.md new file mode 100644 index 00000000000..c6d9768fe9b --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/docs/ApiResponse.md @@ -0,0 +1,12 @@ +# ApiResponse + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**code** | **Int** | | [optional] +**type** | **String** | | [optional] +**message** | **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/swift5/x-swift-hashable/docs/ArrayOfArrayOfNumberOnly.md b/samples/client/petstore/swift5/x-swift-hashable/docs/ArrayOfArrayOfNumberOnly.md new file mode 100644 index 00000000000..c6fceff5e08 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/docs/ArrayOfArrayOfNumberOnly.md @@ -0,0 +1,10 @@ +# ArrayOfArrayOfNumberOnly + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**arrayArrayNumber** | [[Double]] | | [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/swift5/x-swift-hashable/docs/ArrayOfNumberOnly.md b/samples/client/petstore/swift5/x-swift-hashable/docs/ArrayOfNumberOnly.md new file mode 100644 index 00000000000..f09f8fa6f70 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/docs/ArrayOfNumberOnly.md @@ -0,0 +1,10 @@ +# ArrayOfNumberOnly + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**arrayNumber** | **[Double]** | | [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/swift5/x-swift-hashable/docs/ArrayTest.md b/samples/client/petstore/swift5/x-swift-hashable/docs/ArrayTest.md new file mode 100644 index 00000000000..bf416b8330c --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/docs/ArrayTest.md @@ -0,0 +1,12 @@ +# ArrayTest + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**arrayOfString** | **[String]** | | [optional] +**arrayArrayOfInteger** | [[Int64]] | | [optional] +**arrayArrayOfModel** | [[ReadOnlyFirst]] | | [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/swift5/x-swift-hashable/docs/BigCat.md b/samples/client/petstore/swift5/x-swift-hashable/docs/BigCat.md new file mode 100644 index 00000000000..cd904c7381a --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/docs/BigCat.md @@ -0,0 +1,10 @@ +# BigCat + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**kind** | **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/swift5/x-swift-hashable/docs/BigCatAllOf.md b/samples/client/petstore/swift5/x-swift-hashable/docs/BigCatAllOf.md new file mode 100644 index 00000000000..20da4caf5d0 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/docs/BigCatAllOf.md @@ -0,0 +1,10 @@ +# BigCatAllOf + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**kind** | **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/swift5/x-swift-hashable/docs/Capitalization.md b/samples/client/petstore/swift5/x-swift-hashable/docs/Capitalization.md new file mode 100644 index 00000000000..95374216c77 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/docs/Capitalization.md @@ -0,0 +1,15 @@ +# Capitalization + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**smallCamel** | **String** | | [optional] +**capitalCamel** | **String** | | [optional] +**smallSnake** | **String** | | [optional] +**capitalSnake** | **String** | | [optional] +**sCAETHFlowPoints** | **String** | | [optional] +**ATT_NAME** | **String** | Name of the pet | [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/swift5/x-swift-hashable/docs/Cat.md b/samples/client/petstore/swift5/x-swift-hashable/docs/Cat.md new file mode 100644 index 00000000000..fb5949b1576 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/docs/Cat.md @@ -0,0 +1,10 @@ +# Cat + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**declawed** | **Bool** | | [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/swift5/x-swift-hashable/docs/CatAllOf.md b/samples/client/petstore/swift5/x-swift-hashable/docs/CatAllOf.md new file mode 100644 index 00000000000..79789be61c0 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/docs/CatAllOf.md @@ -0,0 +1,10 @@ +# CatAllOf + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**declawed** | **Bool** | | [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/swift5/x-swift-hashable/docs/Category.md b/samples/client/petstore/swift5/x-swift-hashable/docs/Category.md new file mode 100644 index 00000000000..5ca5408c0f9 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/docs/Category.md @@ -0,0 +1,11 @@ +# Category + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **Int64** | | [optional] +**name** | **String** | | [default to "default-name"] + +[[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/swift5/x-swift-hashable/docs/ClassModel.md b/samples/client/petstore/swift5/x-swift-hashable/docs/ClassModel.md new file mode 100644 index 00000000000..e3912fdf0fd --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/docs/ClassModel.md @@ -0,0 +1,10 @@ +# ClassModel + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**_class** | **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/swift5/x-swift-hashable/docs/Client.md b/samples/client/petstore/swift5/x-swift-hashable/docs/Client.md new file mode 100644 index 00000000000..0de1b238c36 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/docs/Client.md @@ -0,0 +1,10 @@ +# Client + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**client** | **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/swift5/x-swift-hashable/docs/Dog.md b/samples/client/petstore/swift5/x-swift-hashable/docs/Dog.md new file mode 100644 index 00000000000..4824786da04 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/docs/Dog.md @@ -0,0 +1,10 @@ +# Dog + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**breed** | **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/swift5/x-swift-hashable/docs/DogAllOf.md b/samples/client/petstore/swift5/x-swift-hashable/docs/DogAllOf.md new file mode 100644 index 00000000000..9302ef52e93 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/docs/DogAllOf.md @@ -0,0 +1,10 @@ +# DogAllOf + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**breed** | **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/swift5/x-swift-hashable/docs/EnumArrays.md b/samples/client/petstore/swift5/x-swift-hashable/docs/EnumArrays.md new file mode 100644 index 00000000000..b9a9807d3c8 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/docs/EnumArrays.md @@ -0,0 +1,11 @@ +# EnumArrays + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**justSymbol** | **String** | | [optional] +**arrayEnum** | **[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/swift5/x-swift-hashable/docs/EnumClass.md b/samples/client/petstore/swift5/x-swift-hashable/docs/EnumClass.md new file mode 100644 index 00000000000..67f017becd0 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/docs/EnumClass.md @@ -0,0 +1,9 @@ +# EnumClass + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +[[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/swift5/x-swift-hashable/docs/EnumTest.md b/samples/client/petstore/swift5/x-swift-hashable/docs/EnumTest.md new file mode 100644 index 00000000000..bc9b036dd76 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/docs/EnumTest.md @@ -0,0 +1,14 @@ +# EnumTest + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**enumString** | **String** | | [optional] +**enumStringRequired** | **String** | | +**enumInteger** | **Int** | | [optional] +**enumNumber** | **Double** | | [optional] +**outerEnum** | [**OuterEnum**](OuterEnum.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/swift5/x-swift-hashable/docs/FakeAPI.md b/samples/client/petstore/swift5/x-swift-hashable/docs/FakeAPI.md new file mode 100644 index 00000000000..553a46281aa --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/docs/FakeAPI.md @@ -0,0 +1,662 @@ +# FakeAPI + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**fakeOuterBooleanSerialize**](FakeAPI.md#fakeouterbooleanserialize) | **POST** /fake/outer/boolean | +[**fakeOuterCompositeSerialize**](FakeAPI.md#fakeoutercompositeserialize) | **POST** /fake/outer/composite | +[**fakeOuterNumberSerialize**](FakeAPI.md#fakeouternumberserialize) | **POST** /fake/outer/number | +[**fakeOuterStringSerialize**](FakeAPI.md#fakeouterstringserialize) | **POST** /fake/outer/string | +[**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 +[**testEndpointParameters**](FakeAPI.md#testendpointparameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 +[**testEnumParameters**](FakeAPI.md#testenumparameters) | **GET** /fake | To test enum parameters +[**testGroupParameters**](FakeAPI.md#testgroupparameters) | **DELETE** /fake | Fake endpoint to test group parameters (optional) +[**testInlineAdditionalProperties**](FakeAPI.md#testinlineadditionalproperties) | **POST** /fake/inline-additionalProperties | test inline additionalProperties +[**testJsonFormData**](FakeAPI.md#testjsonformdata) | **GET** /fake/jsonFormData | test json serialization of form data + + +# **fakeOuterBooleanSerialize** +```swift + open class func fakeOuterBooleanSerialize(body: Bool? = nil, completion: @escaping (_ data: Bool?, _ error: Error?) -> Void) +``` + + + +Test serialization of outer boolean types + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let body = true // Bool | Input boolean as post body (optional) + +FakeAPI.fakeOuterBooleanSerialize(body: body) { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | **Bool** | Input boolean as post body | [optional] + +### Return type + +**Bool** + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: */* + +[[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) + +# **fakeOuterCompositeSerialize** +```swift + open class func fakeOuterCompositeSerialize(body: OuterComposite? = nil, completion: @escaping (_ data: OuterComposite?, _ error: Error?) -> Void) +``` + + + +Test serialization of object with outer number type + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let body = OuterComposite(myNumber: 123, myString: "myString_example", myBoolean: false) // OuterComposite | Input composite as post body (optional) + +FakeAPI.fakeOuterCompositeSerialize(body: body) { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**OuterComposite**](OuterComposite.md) | Input composite as post body | [optional] + +### Return type + +[**OuterComposite**](OuterComposite.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: */* + +[[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) + +# **fakeOuterNumberSerialize** +```swift + open class func fakeOuterNumberSerialize(body: Double? = nil, completion: @escaping (_ data: Double?, _ error: Error?) -> Void) +``` + + + +Test serialization of outer number types + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let body = 987 // Double | Input number as post body (optional) + +FakeAPI.fakeOuterNumberSerialize(body: body) { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | **Double** | Input number as post body | [optional] + +### Return type + +**Double** + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: */* + +[[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) + +# **fakeOuterStringSerialize** +```swift + open class func fakeOuterStringSerialize(body: String? = nil, completion: @escaping (_ data: String?, _ error: Error?) -> Void) +``` + + + +Test serialization of outer string types + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let body = "body_example" // String | Input string as post body (optional) + +FakeAPI.fakeOuterStringSerialize(body: body) { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | **String** | Input string as post body | [optional] + +### Return type + +**String** + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: */* + +[[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** +```swift + open class func testBodyWithFileSchema(body: FileSchemaTestClass, completion: @escaping (_ data: Void?, _ error: Error?) -> Void) +``` + + + +For this test, the body for this request much reference a schema named `File`. + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let body = FileSchemaTestClass(file: File(sourceURI: "sourceURI_example"), files: [nil]) // FileSchemaTestClass | + +FakeAPI.testBodyWithFileSchema(body: body) { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**FileSchemaTestClass**](FileSchemaTestClass.md) | | + +### 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) + +# **testBodyWithQueryParams** +```swift + open class func testBodyWithQueryParams(query: String, body: User, completion: @escaping (_ data: Void?, _ error: Error?) -> Void) +``` + + + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let query = "query_example" // String | +let body = User(id: 123, username: "username_example", firstName: "firstName_example", lastName: "lastName_example", email: "email_example", password: "password_example", phone: "phone_example", userStatus: 123) // User | + +FakeAPI.testBodyWithQueryParams(query: query, body: body) { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **query** | **String** | | + **body** | [**User**](User.md) | | + +### 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) + +# **testClientModel** +```swift + open class func testClientModel(body: Client, completion: @escaping (_ data: Client?, _ error: Error?) -> Void) +``` + +To test \"client\" model + +To test \"client\" model + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let body = Client(client: "client_example") // Client | client model + +// To test \"client\" model +FakeAPI.testClientModel(body: body) { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**Client**](Client.md) | client model | + +### Return type + +[**Client**](Client.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) + +# **testEndpointParameters** +```swift + open class func testEndpointParameters(number: Double, double: Double, patternWithoutDelimiter: String, byte: Data, integer: Int? = nil, int32: Int? = nil, int64: Int64? = nil, float: Float? = nil, string: String? = nil, binary: URL? = nil, date: Date? = nil, dateTime: Date? = nil, password: String? = nil, callback: String? = nil, completion: @escaping (_ data: Void?, _ error: Error?) -> Void) +``` + +Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + +Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let number = 987 // Double | None +let double = 987 // Double | None +let patternWithoutDelimiter = "patternWithoutDelimiter_example" // String | None +let byte = Data([9, 8, 7]) // Data | None +let integer = 987 // Int | None (optional) +let int32 = 987 // Int | None (optional) +let int64 = 987 // Int64 | None (optional) +let float = 987 // Float | None (optional) +let string = "string_example" // String | None (optional) +let binary = URL(string: "https://example.com")! // URL | None (optional) +let date = Date() // Date | None (optional) +let dateTime = Date() // Date | None (optional) +let password = "password_example" // String | None (optional) +let callback = "callback_example" // String | None (optional) + +// Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 +FakeAPI.testEndpointParameters(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) { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **number** | **Double** | None | + **double** | **Double** | None | + **patternWithoutDelimiter** | **String** | None | + **byte** | **Data** | None | + **integer** | **Int** | None | [optional] + **int32** | **Int** | None | [optional] + **int64** | **Int64** | None | [optional] + **float** | **Float** | None | [optional] + **string** | **String** | None | [optional] + **binary** | **URL** | None | [optional] + **date** | **Date** | None | [optional] + **dateTime** | **Date** | None | [optional] + **password** | **String** | None | [optional] + **callback** | **String** | None | [optional] + +### Return type + +Void (empty response body) + +### Authorization + +[http_basic_test](../README.md#http_basic_test) + +### HTTP request headers + + - **Content-Type**: application/x-www-form-urlencoded + - **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) + +# **testEnumParameters** +```swift + open class func testEnumParameters(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, completion: @escaping (_ data: Void?, _ error: Error?) -> Void) +``` + +To test enum parameters + +To test enum parameters + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let enumHeaderStringArray = ["enumHeaderStringArray_example"] // [String] | Header parameter enum test (string array) (optional) +let enumHeaderString = "enumHeaderString_example" // String | Header parameter enum test (string) (optional) (default to .efg) +let enumQueryStringArray = ["enumQueryStringArray_example"] // [String] | Query parameter enum test (string array) (optional) +let enumQueryString = "enumQueryString_example" // String | Query parameter enum test (string) (optional) (default to .efg) +let enumQueryInteger = 987 // Int | Query parameter enum test (double) (optional) +let enumQueryDouble = 987 // Double | Query parameter enum test (double) (optional) +let enumFormStringArray = ["inner_example"] // [String] | Form parameter enum test (string array) (optional) (default to .dollar) +let enumFormString = "enumFormString_example" // String | Form parameter enum test (string) (optional) (default to .efg) + +// To test enum parameters +FakeAPI.testEnumParameters(enumHeaderStringArray: enumHeaderStringArray, enumHeaderString: enumHeaderString, enumQueryStringArray: enumQueryStringArray, enumQueryString: enumQueryString, enumQueryInteger: enumQueryInteger, enumQueryDouble: enumQueryDouble, enumFormStringArray: enumFormStringArray, enumFormString: enumFormString) { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **enumHeaderStringArray** | [**[String]**](String.md) | Header parameter enum test (string array) | [optional] + **enumHeaderString** | **String** | Header parameter enum test (string) | [optional] [default to .efg] + **enumQueryStringArray** | [**[String]**](String.md) | Query parameter enum test (string array) | [optional] + **enumQueryString** | **String** | Query parameter enum test (string) | [optional] [default to .efg] + **enumQueryInteger** | **Int** | Query parameter enum test (double) | [optional] + **enumQueryDouble** | **Double** | Query parameter enum test (double) | [optional] + **enumFormStringArray** | [**[String]**](String.md) | Form parameter enum test (string array) | [optional] [default to .dollar] + **enumFormString** | **String** | Form parameter enum test (string) | [optional] [default to .efg] + +### Return type + +Void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/x-www-form-urlencoded + - **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) + +# **testGroupParameters** +```swift + open class func testGroupParameters(requiredStringGroup: Int, requiredBooleanGroup: Bool, requiredInt64Group: Int64, stringGroup: Int? = nil, booleanGroup: Bool? = nil, int64Group: Int64? = nil, completion: @escaping (_ data: Void?, _ error: Error?) -> Void) +``` + +Fake endpoint to test group parameters (optional) + +Fake endpoint to test group parameters (optional) + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let requiredStringGroup = 987 // Int | Required String in group parameters +let requiredBooleanGroup = true // Bool | Required Boolean in group parameters +let requiredInt64Group = 987 // Int64 | Required Integer in group parameters +let stringGroup = 987 // Int | String in group parameters (optional) +let booleanGroup = true // Bool | Boolean in group parameters (optional) +let int64Group = 987 // Int64 | Integer in group parameters (optional) + +// Fake endpoint to test group parameters (optional) +FakeAPI.testGroupParameters(requiredStringGroup: requiredStringGroup, requiredBooleanGroup: requiredBooleanGroup, requiredInt64Group: requiredInt64Group, stringGroup: stringGroup, booleanGroup: booleanGroup, int64Group: int64Group) { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **requiredStringGroup** | **Int** | Required String in group parameters | + **requiredBooleanGroup** | **Bool** | Required Boolean in group parameters | + **requiredInt64Group** | **Int64** | Required Integer in group parameters | + **stringGroup** | **Int** | String in group parameters | [optional] + **booleanGroup** | **Bool** | Boolean in group parameters | [optional] + **int64Group** | **Int64** | Integer in group parameters | [optional] + +### Return type + +Void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **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) + +# **testInlineAdditionalProperties** +```swift + open class func testInlineAdditionalProperties(param: [String: String], completion: @escaping (_ data: Void?, _ error: Error?) -> Void) +``` + +test inline additionalProperties + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let param = "TODO" // [String: String] | request body + +// test inline additionalProperties +FakeAPI.testInlineAdditionalProperties(param: param) { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **param** | [**[String: String]**](String.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) + +# **testJsonFormData** +```swift + open class func testJsonFormData(param: String, param2: String, completion: @escaping (_ data: Void?, _ error: Error?) -> Void) +``` + +test json serialization of form data + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let param = "param_example" // String | field1 +let param2 = "param2_example" // String | field2 + +// test json serialization of form data +FakeAPI.testJsonFormData(param: param, param2: param2) { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **param** | **String** | field1 | + **param2** | **String** | field2 | + +### Return type + +Void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/x-www-form-urlencoded + - **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) + diff --git a/samples/client/petstore/swift5/x-swift-hashable/docs/FakeClassnameTags123API.md b/samples/client/petstore/swift5/x-swift-hashable/docs/FakeClassnameTags123API.md new file mode 100644 index 00000000000..9f24b46edbc --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/docs/FakeClassnameTags123API.md @@ -0,0 +1,59 @@ +# FakeClassnameTags123API + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**testClassname**](FakeClassnameTags123API.md#testclassname) | **PATCH** /fake_classname_test | To test class name in snake case + + +# **testClassname** +```swift + open class func testClassname(body: Client, completion: @escaping (_ data: Client?, _ error: Error?) -> Void) +``` + +To test class name in snake case + +To test class name in snake case + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let body = Client(client: "client_example") // Client | client model + +// To test class name in snake case +FakeClassnameTags123API.testClassname(body: body) { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**Client**](Client.md) | client model | + +### Return type + +[**Client**](Client.md) + +### Authorization + +[api_key_query](../README.md#api_key_query) + +### 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/petstore/swift5/x-swift-hashable/docs/File.md b/samples/client/petstore/swift5/x-swift-hashable/docs/File.md new file mode 100644 index 00000000000..3edfef17b79 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/docs/File.md @@ -0,0 +1,10 @@ +# File + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**sourceURI** | **String** | Test capitalization | [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/swift5/x-swift-hashable/docs/FileSchemaTestClass.md b/samples/client/petstore/swift5/x-swift-hashable/docs/FileSchemaTestClass.md new file mode 100644 index 00000000000..afdacc60b2c --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/docs/FileSchemaTestClass.md @@ -0,0 +1,11 @@ +# FileSchemaTestClass + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**file** | [**File**](File.md) | | [optional] +**files** | [File] | | [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/swift5/x-swift-hashable/docs/FormatTest.md b/samples/client/petstore/swift5/x-swift-hashable/docs/FormatTest.md new file mode 100644 index 00000000000..f74d94f6c46 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/docs/FormatTest.md @@ -0,0 +1,22 @@ +# FormatTest + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**integer** | **Int** | | [optional] +**int32** | **Int** | | [optional] +**int64** | **Int64** | | [optional] +**number** | **Double** | | +**float** | **Float** | | [optional] +**double** | **Double** | | [optional] +**string** | **String** | | [optional] +**byte** | **Data** | | +**binary** | **URL** | | [optional] +**date** | **Date** | | +**dateTime** | **Date** | | [optional] +**uuid** | **UUID** | | [optional] +**password** | **String** | | + +[[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/swift5/x-swift-hashable/docs/HasOnlyReadOnly.md b/samples/client/petstore/swift5/x-swift-hashable/docs/HasOnlyReadOnly.md new file mode 100644 index 00000000000..57b6e3a17e6 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/docs/HasOnlyReadOnly.md @@ -0,0 +1,11 @@ +# HasOnlyReadOnly + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**bar** | **String** | | [optional] [readonly] +**foo** | **String** | | [optional] [readonly] + +[[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/swift5/x-swift-hashable/docs/List.md b/samples/client/petstore/swift5/x-swift-hashable/docs/List.md new file mode 100644 index 00000000000..b77718302ed --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/docs/List.md @@ -0,0 +1,10 @@ +# List + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**_123list** | **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/swift5/x-swift-hashable/docs/MapTest.md b/samples/client/petstore/swift5/x-swift-hashable/docs/MapTest.md new file mode 100644 index 00000000000..73f9e0d50ac --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/docs/MapTest.md @@ -0,0 +1,13 @@ +# MapTest + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**mapMapOfString** | [String: [String: String]] | | [optional] +**mapOfEnumString** | **[String: String]** | | [optional] +**directMap** | **[String: Bool]** | | [optional] +**indirectMap** | [**StringBooleanMap**](StringBooleanMap.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/swift5/x-swift-hashable/docs/MixedPropertiesAndAdditionalPropertiesClass.md b/samples/client/petstore/swift5/x-swift-hashable/docs/MixedPropertiesAndAdditionalPropertiesClass.md new file mode 100644 index 00000000000..3fdfd03f0e3 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/docs/MixedPropertiesAndAdditionalPropertiesClass.md @@ -0,0 +1,12 @@ +# MixedPropertiesAndAdditionalPropertiesClass + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**uuid** | **UUID** | | [optional] +**dateTime** | **Date** | | [optional] +**map** | [String: Animal] | | [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/swift5/x-swift-hashable/docs/Model200Response.md b/samples/client/petstore/swift5/x-swift-hashable/docs/Model200Response.md new file mode 100644 index 00000000000..5865ea690cc --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/docs/Model200Response.md @@ -0,0 +1,11 @@ +# Model200Response + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **Int** | | [optional] +**_class** | **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/swift5/x-swift-hashable/docs/Name.md b/samples/client/petstore/swift5/x-swift-hashable/docs/Name.md new file mode 100644 index 00000000000..f7b180292cd --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/docs/Name.md @@ -0,0 +1,13 @@ +# Name + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **Int** | | +**snakeCase** | **Int** | | [optional] [readonly] +**property** | **String** | | [optional] +**_123number** | **Int** | | [optional] [readonly] + +[[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/swift5/x-swift-hashable/docs/NumberOnly.md b/samples/client/petstore/swift5/x-swift-hashable/docs/NumberOnly.md new file mode 100644 index 00000000000..72bd361168b --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/docs/NumberOnly.md @@ -0,0 +1,10 @@ +# NumberOnly + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**justNumber** | **Double** | | [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/swift5/x-swift-hashable/docs/Order.md b/samples/client/petstore/swift5/x-swift-hashable/docs/Order.md new file mode 100644 index 00000000000..15487f01175 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/docs/Order.md @@ -0,0 +1,15 @@ +# Order + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **Int64** | | [optional] +**petId** | **Int64** | | [optional] +**quantity** | **Int** | | [optional] +**shipDate** | **Date** | | [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/swift5/x-swift-hashable/docs/OuterComposite.md b/samples/client/petstore/swift5/x-swift-hashable/docs/OuterComposite.md new file mode 100644 index 00000000000..d6b3583bc3f --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/docs/OuterComposite.md @@ -0,0 +1,12 @@ +# OuterComposite + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**myNumber** | **Double** | | [optional] +**myString** | **String** | | [optional] +**myBoolean** | **Bool** | | [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/swift5/x-swift-hashable/docs/OuterEnum.md b/samples/client/petstore/swift5/x-swift-hashable/docs/OuterEnum.md new file mode 100644 index 00000000000..06d413b0168 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/docs/OuterEnum.md @@ -0,0 +1,9 @@ +# OuterEnum + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +[[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/swift5/x-swift-hashable/docs/Pet.md b/samples/client/petstore/swift5/x-swift-hashable/docs/Pet.md new file mode 100644 index 00000000000..5c05f98fad4 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/docs/Pet.md @@ -0,0 +1,15 @@ +# Pet + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **Int64** | | [optional] +**category** | [**Category**](Category.md) | | [optional] +**name** | **String** | | +**photoUrls** | **[String]** | | +**tags** | [Tag] | | [optional] +**status** | **String** | pet status in the store | [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/swift5/x-swift-hashable/docs/PetAPI.md b/samples/client/petstore/swift5/x-swift-hashable/docs/PetAPI.md new file mode 100644 index 00000000000..27efe083347 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/docs/PetAPI.md @@ -0,0 +1,469 @@ +# PetAPI + +All URIs are relative to *http://petstore.swagger.io:80/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 +[**uploadFileWithRequiredFile**](PetAPI.md#uploadfilewithrequiredfile) | **POST** /fake/{petId}/uploadImageWithRequiredFile | uploads an image (required) + + +# **addPet** +```swift + open class func addPet(body: Pet, completion: @escaping (_ data: Void?, _ error: Error?) -> Void) +``` + +Add a new pet to the store + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let body = Pet(id: 123, category: Category(id: 123, name: "name_example"), name: "name_example", photoUrls: ["photoUrls_example"], tags: [Tag(id: 123, name: "name_example")], status: "status_example") // Pet | Pet object that needs to be added to the store + +// Add a new pet to the store +PetAPI.addPet(body: body) { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**Pet**](Pet.md) | Pet object that needs to be added to the store | + +### Return type + +Void (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: application/json, application/xml + - **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) + +# **deletePet** +```swift + open class func deletePet(petId: Int64, apiKey: String? = nil, completion: @escaping (_ data: Void?, _ error: Error?) -> Void) +``` + +Deletes a pet + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let petId = 987 // Int64 | Pet id to delete +let apiKey = "apiKey_example" // String | (optional) + +// Deletes a pet +PetAPI.deletePet(petId: petId, apiKey: apiKey) { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **Int64** | Pet id to delete | + **apiKey** | **String** | | [optional] + +### Return type + +Void (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: Not defined + - **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) + +# **findPetsByStatus** +```swift + open class func findPetsByStatus(status: [String], completion: @escaping (_ data: [Pet]?, _ error: Error?) -> Void) +``` + +Finds Pets by status + +Multiple status values can be provided with comma separated strings + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let status = ["status_example"] // [String] | Status values that need to be considered for filter + +// Finds Pets by status +PetAPI.findPetsByStatus(status: status) { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **status** | [**[String]**](String.md) | Status values that need to be considered for filter | + +### Return type + +[**[Pet]**](Pet.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: Not defined + - **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) + +# **findPetsByTags** +```swift + open class func findPetsByTags(tags: [String], completion: @escaping (_ data: [Pet]?, _ error: Error?) -> Void) +``` + +Finds Pets by tags + +Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let tags = ["inner_example"] // [String] | Tags to filter by + +// Finds Pets by tags +PetAPI.findPetsByTags(tags: tags) { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **tags** | [**[String]**](String.md) | Tags to filter by | + +### Return type + +[**[Pet]**](Pet.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: Not defined + - **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) + +# **getPetById** +```swift + open class func getPetById(petId: Int64, completion: @escaping (_ data: Pet?, _ error: Error?) -> Void) +``` + +Find pet by ID + +Returns a single pet + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let petId = 987 // Int64 | ID of pet to return + +// Find pet by ID +PetAPI.getPetById(petId: petId) { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **Int64** | 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 + +[[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) + +# **updatePet** +```swift + open class func updatePet(body: Pet, completion: @escaping (_ data: Void?, _ error: Error?) -> Void) +``` + +Update an existing pet + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let body = Pet(id: 123, category: Category(id: 123, name: "name_example"), name: "name_example", photoUrls: ["photoUrls_example"], tags: [Tag(id: 123, name: "name_example")], status: "status_example") // Pet | Pet object that needs to be added to the store + +// Update an existing pet +PetAPI.updatePet(body: body) { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**Pet**](Pet.md) | Pet object that needs to be added to the store | + +### Return type + +Void (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: application/json, application/xml + - **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) + +# **updatePetWithForm** +```swift + open class func updatePetWithForm(petId: Int64, name: String? = nil, status: String? = nil, completion: @escaping (_ data: Void?, _ error: Error?) -> Void) +``` + +Updates a pet in the store with form data + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let petId = 987 // Int64 | ID of pet that needs to be updated +let name = "name_example" // String | Updated name of the pet (optional) +let status = "status_example" // String | Updated status of the pet (optional) + +// Updates a pet in the store with form data +PetAPI.updatePetWithForm(petId: petId, name: name, status: status) { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **Int64** | 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 (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: application/x-www-form-urlencoded + - **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) + +# **uploadFile** +```swift + open class func uploadFile(petId: Int64, additionalMetadata: String? = nil, file: URL? = nil, completion: @escaping (_ data: ApiResponse?, _ error: Error?) -> Void) +``` + +uploads an image + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let petId = 987 // Int64 | ID of pet to update +let additionalMetadata = "additionalMetadata_example" // String | Additional data to pass to server (optional) +let file = URL(string: "https://example.com")! // URL | file to upload (optional) + +// uploads an image +PetAPI.uploadFile(petId: petId, additionalMetadata: additionalMetadata, file: file) { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **Int64** | ID of pet to update | + **additionalMetadata** | **String** | Additional data to pass to server | [optional] + **file** | **URL** | file to upload | [optional] + +### Return type + +[**ApiResponse**](ApiResponse.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: multipart/form-data + - **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) + +# **uploadFileWithRequiredFile** +```swift + open class func uploadFileWithRequiredFile(petId: Int64, requiredFile: URL, additionalMetadata: String? = nil, completion: @escaping (_ data: ApiResponse?, _ error: Error?) -> Void) +``` + +uploads an image (required) + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let petId = 987 // Int64 | ID of pet to update +let requiredFile = URL(string: "https://example.com")! // URL | file to upload +let additionalMetadata = "additionalMetadata_example" // String | Additional data to pass to server (optional) + +// uploads an image (required) +PetAPI.uploadFileWithRequiredFile(petId: petId, requiredFile: requiredFile, additionalMetadata: additionalMetadata) { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **Int64** | ID of pet to update | + **requiredFile** | **URL** | file to upload | + **additionalMetadata** | **String** | Additional data to pass to server | [optional] + +### Return type + +[**ApiResponse**](ApiResponse.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: multipart/form-data + - **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/petstore/swift5/x-swift-hashable/docs/ReadOnlyFirst.md b/samples/client/petstore/swift5/x-swift-hashable/docs/ReadOnlyFirst.md new file mode 100644 index 00000000000..ed537b87598 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/docs/ReadOnlyFirst.md @@ -0,0 +1,11 @@ +# ReadOnlyFirst + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**bar** | **String** | | [optional] [readonly] +**baz** | **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/swift5/x-swift-hashable/docs/Return.md b/samples/client/petstore/swift5/x-swift-hashable/docs/Return.md new file mode 100644 index 00000000000..66d17c27c88 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/docs/Return.md @@ -0,0 +1,10 @@ +# Return + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**_return** | **Int** | | [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/swift5/x-swift-hashable/docs/SpecialModelName.md b/samples/client/petstore/swift5/x-swift-hashable/docs/SpecialModelName.md new file mode 100644 index 00000000000..3ec27a38c2a --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/docs/SpecialModelName.md @@ -0,0 +1,10 @@ +# SpecialModelName + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**specialPropertyName** | **Int64** | | [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/swift5/x-swift-hashable/docs/StoreAPI.md b/samples/client/petstore/swift5/x-swift-hashable/docs/StoreAPI.md new file mode 100644 index 00000000000..383dda5d3c7 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/docs/StoreAPI.md @@ -0,0 +1,206 @@ +# StoreAPI + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**deleteOrder**](StoreAPI.md#deleteorder) | **DELETE** /store/order/{order_id} | Delete purchase order by ID +[**getInventory**](StoreAPI.md#getinventory) | **GET** /store/inventory | Returns pet inventories by status +[**getOrderById**](StoreAPI.md#getorderbyid) | **GET** /store/order/{order_id} | Find purchase order by ID +[**placeOrder**](StoreAPI.md#placeorder) | **POST** /store/order | Place an order for a pet + + +# **deleteOrder** +```swift + open class func deleteOrder(orderId: String, completion: @escaping (_ data: Void?, _ error: Error?) -> Void) +``` + +Delete purchase order by ID + +For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let orderId = "orderId_example" // String | ID of the order that needs to be deleted + +// Delete purchase order by ID +StoreAPI.deleteOrder(orderId: orderId) { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **orderId** | **String** | ID of the order that needs to be deleted | + +### Return type + +Void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **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) + +# **getInventory** +```swift + open class func getInventory(completion: @escaping (_ data: [String: Int]?, _ error: Error?) -> Void) +``` + +Returns pet inventories by status + +Returns a map of status codes to quantities + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + + +// Returns pet inventories by status +StoreAPI.getInventory() { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### Parameters +This endpoint does not need any parameter. + +### Return type + +**[String: Int]** + +### Authorization + +[api_key](../README.md#api_key) + +### HTTP request headers + + - **Content-Type**: Not defined + - **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) + +# **getOrderById** +```swift + open class func getOrderById(orderId: Int64, completion: @escaping (_ data: Order?, _ error: Error?) -> Void) +``` + +Find purchase order by ID + +For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let orderId = 987 // Int64 | ID of pet that needs to be fetched + +// Find purchase order by ID +StoreAPI.getOrderById(orderId: orderId) { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **orderId** | **Int64** | 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 + +[[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) + +# **placeOrder** +```swift + open class func placeOrder(body: Order, completion: @escaping (_ data: Order?, _ error: Error?) -> Void) +``` + +Place an order for a pet + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let body = Order(id: 123, petId: 123, quantity: 123, shipDate: Date(), status: "status_example", complete: false) // Order | order placed for purchasing the pet + +// Place an order for a pet +StoreAPI.placeOrder(body: body) { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### 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 + +[[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/swift5/x-swift-hashable/docs/StringBooleanMap.md b/samples/client/petstore/swift5/x-swift-hashable/docs/StringBooleanMap.md new file mode 100644 index 00000000000..7abf11ec68b --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/docs/StringBooleanMap.md @@ -0,0 +1,9 @@ +# StringBooleanMap + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +[[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/swift5/x-swift-hashable/docs/Tag.md b/samples/client/petstore/swift5/x-swift-hashable/docs/Tag.md new file mode 100644 index 00000000000..ff4ac8aa451 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/docs/Tag.md @@ -0,0 +1,11 @@ +# Tag + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **Int64** | | [optional] +**name** | **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/swift5/x-swift-hashable/docs/TypeHolderDefault.md b/samples/client/petstore/swift5/x-swift-hashable/docs/TypeHolderDefault.md new file mode 100644 index 00000000000..5161394bdc3 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/docs/TypeHolderDefault.md @@ -0,0 +1,14 @@ +# TypeHolderDefault + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**stringItem** | **String** | | [default to "what"] +**numberItem** | **Double** | | +**integerItem** | **Int** | | +**boolItem** | **Bool** | | [default to true] +**arrayItem** | **[Int]** | | + +[[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/swift5/x-swift-hashable/docs/TypeHolderExample.md b/samples/client/petstore/swift5/x-swift-hashable/docs/TypeHolderExample.md new file mode 100644 index 00000000000..46d0471cd71 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/docs/TypeHolderExample.md @@ -0,0 +1,14 @@ +# TypeHolderExample + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**stringItem** | **String** | | +**numberItem** | **Double** | | +**integerItem** | **Int** | | +**boolItem** | **Bool** | | +**arrayItem** | **[Int]** | | + +[[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/swift5/x-swift-hashable/docs/User.md b/samples/client/petstore/swift5/x-swift-hashable/docs/User.md new file mode 100644 index 00000000000..5a439de0ff9 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/docs/User.md @@ -0,0 +1,17 @@ +# User + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **Int64** | | [optional] +**username** | **String** | | [optional] +**firstName** | **String** | | [optional] +**lastName** | **String** | | [optional] +**email** | **String** | | [optional] +**password** | **String** | | [optional] +**phone** | **String** | | [optional] +**userStatus** | **Int** | User Status | [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/swift5/x-swift-hashable/docs/UserAPI.md b/samples/client/petstore/swift5/x-swift-hashable/docs/UserAPI.md new file mode 100644 index 00000000000..380813bc68c --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/docs/UserAPI.md @@ -0,0 +1,406 @@ +# UserAPI + +All URIs are relative to *http://petstore.swagger.io:80/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** +```swift + open class func createUser(body: User, completion: @escaping (_ data: Void?, _ error: Error?) -> Void) +``` + +Create user + +This can only be done by the logged in user. + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let body = User(id: 123, username: "username_example", firstName: "firstName_example", lastName: "lastName_example", email: "email_example", password: "password_example", phone: "phone_example", userStatus: 123) // User | Created user object + +// Create user +UserAPI.createUser(body: body) { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**User**](User.md) | Created user object | + +### Return type + +Void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **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) + +# **createUsersWithArrayInput** +```swift + open class func createUsersWithArrayInput(body: [User], completion: @escaping (_ data: Void?, _ error: Error?) -> Void) +``` + +Creates list of users with given input array + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let body = [User(id: 123, username: "username_example", firstName: "firstName_example", lastName: "lastName_example", email: "email_example", password: "password_example", phone: "phone_example", userStatus: 123)] // [User] | List of user object + +// Creates list of users with given input array +UserAPI.createUsersWithArrayInput(body: body) { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**[User]**](User.md) | List of user object | + +### Return type + +Void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **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) + +# **createUsersWithListInput** +```swift + open class func createUsersWithListInput(body: [User], completion: @escaping (_ data: Void?, _ error: Error?) -> Void) +``` + +Creates list of users with given input array + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let body = [User(id: 123, username: "username_example", firstName: "firstName_example", lastName: "lastName_example", email: "email_example", password: "password_example", phone: "phone_example", userStatus: 123)] // [User] | List of user object + +// Creates list of users with given input array +UserAPI.createUsersWithListInput(body: body) { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**[User]**](User.md) | List of user object | + +### Return type + +Void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **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) + +# **deleteUser** +```swift + open class func deleteUser(username: String, completion: @escaping (_ data: Void?, _ error: Error?) -> Void) +``` + +Delete user + +This can only be done by the logged in user. + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let username = "username_example" // String | The name that needs to be deleted + +// Delete user +UserAPI.deleteUser(username: username) { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **String** | The name that needs to be deleted | + +### Return type + +Void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **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) + +# **getUserByName** +```swift + open class func getUserByName(username: String, completion: @escaping (_ data: User?, _ error: Error?) -> Void) +``` + +Get user by user name + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let username = "username_example" // String | The name that needs to be fetched. Use user1 for testing. + +// Get user by user name +UserAPI.getUserByName(username: username) { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### 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 + +[[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) + +# **loginUser** +```swift + open class func loginUser(username: String, password: String, completion: @escaping (_ data: String?, _ error: Error?) -> Void) +``` + +Logs user into the system + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let username = "username_example" // String | The user name for login +let password = "password_example" // String | The password for login in clear text + +// Logs user into the system +UserAPI.loginUser(username: username, password: password) { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### 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 + +[[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) + +# **logoutUser** +```swift + open class func logoutUser(completion: @escaping (_ data: Void?, _ error: Error?) -> Void) +``` + +Logs out current logged in user session + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + + +// Logs out current logged in user session +UserAPI.logoutUser() { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### 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**: 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) + +# **updateUser** +```swift + open class func updateUser(username: String, body: User, completion: @escaping (_ data: Void?, _ error: Error?) -> Void) +``` + +Updated user + +This can only be done by the logged in user. + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let username = "username_example" // String | name that need to be deleted +let body = User(id: 123, username: "username_example", firstName: "firstName_example", lastName: "lastName_example", email: "email_example", password: "password_example", phone: "phone_example", userStatus: 123) // User | Updated user object + +// Updated user +UserAPI.updateUser(username: username, body: body) { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **String** | name that need to be deleted | + **body** | [**User**](User.md) | Updated user object | + +### Return type + +Void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **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) + diff --git a/samples/client/petstore/swift5/x-swift-hashable/docs/XmlItem.md b/samples/client/petstore/swift5/x-swift-hashable/docs/XmlItem.md new file mode 100644 index 00000000000..1a4eb4e9c83 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/docs/XmlItem.md @@ -0,0 +1,38 @@ +# XmlItem + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**attributeString** | **String** | | [optional] +**attributeNumber** | **Double** | | [optional] +**attributeInteger** | **Int** | | [optional] +**attributeBoolean** | **Bool** | | [optional] +**wrappedArray** | **[Int]** | | [optional] +**nameString** | **String** | | [optional] +**nameNumber** | **Double** | | [optional] +**nameInteger** | **Int** | | [optional] +**nameBoolean** | **Bool** | | [optional] +**nameArray** | **[Int]** | | [optional] +**nameWrappedArray** | **[Int]** | | [optional] +**prefixString** | **String** | | [optional] +**prefixNumber** | **Double** | | [optional] +**prefixInteger** | **Int** | | [optional] +**prefixBoolean** | **Bool** | | [optional] +**prefixArray** | **[Int]** | | [optional] +**prefixWrappedArray** | **[Int]** | | [optional] +**namespaceString** | **String** | | [optional] +**namespaceNumber** | **Double** | | [optional] +**namespaceInteger** | **Int** | | [optional] +**namespaceBoolean** | **Bool** | | [optional] +**namespaceArray** | **[Int]** | | [optional] +**namespaceWrappedArray** | **[Int]** | | [optional] +**prefixNsString** | **String** | | [optional] +**prefixNsNumber** | **Double** | | [optional] +**prefixNsInteger** | **Int** | | [optional] +**prefixNsBoolean** | **Bool** | | [optional] +**prefixNsArray** | **[Int]** | | [optional] +**prefixNsWrappedArray** | **[Int]** | | [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/swift5/x-swift-hashable/git_push.sh b/samples/client/petstore/swift5/x-swift-hashable/git_push.sh new file mode 100644 index 00000000000..ced3be2b0c7 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/git_push.sh @@ -0,0 +1,58 @@ +#!/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-pestore-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/swift5/x-swift-hashable/pom.xml b/samples/client/petstore/swift5/x-swift-hashable/pom.xml new file mode 100644 index 00000000000..c1b201eb3b4 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/pom.xml @@ -0,0 +1,43 @@ + + 4.0.0 + io.swagger + Swift5PetstoreClientTests + pom + 1.0-SNAPSHOT + Swift5 Swagger Petstore Client + + + + maven-dependency-plugin + + + package + + copy-dependencies + + + ${project.build.directory} + + + + + + org.codehaus.mojo + exec-maven-plugin + 1.2.1 + + + xcodebuild-test + integration-test + + exec + + + ./run_spmbuild.sh + + + + + + + diff --git a/samples/client/petstore/swift5/x-swift-hashable/project.yml b/samples/client/petstore/swift5/x-swift-hashable/project.yml new file mode 100644 index 00000000000..0493cf65896 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/project.yml @@ -0,0 +1,15 @@ +name: PetstoreClient +targets: + PetstoreClient: + type: framework + platform: iOS + deploymentTarget: "9.0" + sources: [PetstoreClient] + info: + path: ./Info.plist + version: 1.0.0 + settings: + APPLICATION_EXTENSION_API_ONLY: true + scheme: {} + dependencies: + - carthage: AnyCodable diff --git a/samples/client/petstore/swift5/x-swift-hashable/run_spmbuild.sh b/samples/client/petstore/swift5/x-swift-hashable/run_spmbuild.sh new file mode 100755 index 00000000000..1a9f585ad05 --- /dev/null +++ b/samples/client/petstore/swift5/x-swift-hashable/run_spmbuild.sh @@ -0,0 +1,3 @@ +#!/bin/sh + +swift build && exit ${PIPESTATUS[0]} diff --git a/samples/client/petstore/tiny/cpp/.gitignore b/samples/client/petstore/tiny/cpp/.gitignore new file mode 100644 index 00000000000..89cc49cbd65 --- /dev/null +++ b/samples/client/petstore/tiny/cpp/.gitignore @@ -0,0 +1,5 @@ +.pio +.vscode/.browse.c_cpp.db* +.vscode/c_cpp_properties.json +.vscode/launch.json +.vscode/ipch diff --git a/samples/client/petstore/tiny/cpp/.openapi-generator-ignore b/samples/client/petstore/tiny/cpp/.openapi-generator-ignore new file mode 100644 index 00000000000..7484ee590a3 --- /dev/null +++ b/samples/client/petstore/tiny/cpp/.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/tiny/cpp/.openapi-generator/FILES b/samples/client/petstore/tiny/cpp/.openapi-generator/FILES new file mode 100644 index 00000000000..1024d945064 --- /dev/null +++ b/samples/client/petstore/tiny/cpp/.openapi-generator/FILES @@ -0,0 +1,30 @@ +README.md +README.md +lib/Models/ApiResponse.cpp +lib/Models/ApiResponse.h +lib/Models/Category.cpp +lib/Models/Category.h +lib/Models/Helpers.cpp +lib/Models/Helpers.h +lib/Models/Order.cpp +lib/Models/Order.h +lib/Models/Pet.cpp +lib/Models/Pet.h +lib/Models/Tag.cpp +lib/Models/Tag.h +lib/Models/User.cpp +lib/Models/User.h +lib/service/AbstractService.cpp +lib/service/AbstractService.h +lib/service/PetApi.cpp +lib/service/PetApi.h +lib/service/Response.h +lib/service/StoreApi.cpp +lib/service/StoreApi.h +lib/service/UserApi.cpp +lib/service/UserApi.h +platformio.ini +pre_compiling_bourne.py +root.cert +src/main.cpp +test/RunTests.cpp diff --git a/samples/client/petstore/cpp-qt5/.openapi-generator/VERSION b/samples/client/petstore/tiny/cpp/.openapi-generator/VERSION similarity index 100% rename from samples/client/petstore/cpp-qt5/.openapi-generator/VERSION rename to samples/client/petstore/tiny/cpp/.openapi-generator/VERSION diff --git a/samples/client/petstore/tiny/cpp/README.md b/samples/client/petstore/tiny/cpp/README.md new file mode 100644 index 00000000000..e8bf721275b --- /dev/null +++ b/samples/client/petstore/tiny/cpp/README.md @@ -0,0 +1,73 @@ +# Documentation for OpenAPI Petstore +This is a client generator for microcontrollers on the Espressif32 platform and the Arduino framework +After the client have been generated, you have to change these following variablies: +- root.cert | Provide your service root certificate. +- src/main.cpp | Change wifi name +- src/main.cpp | Change wifi password +- lib/service/AbstractService.h | Change to your url + +# Documentation for OpenAPI Petstore 1.0.0 Tiny client cpp (Arduino) + +The project is structured like this: +``` +samples/client/petstore/tiny/cpp/ +├── lib +│ ├── Models +│ ├── service +│ └── TestFiles +├── platformio.ini +├── pre_compiling_bourne.py +├── README.md +├── root.cert +├── src +│ └── main.cpp +└── test + └── RunTests.cpp +``` + +All URIs are relative to http://petstore.swagger.iohttp://petstore.swagger.io/v2 + +### PetApi +|Method | HTTP request | Description| +|------------- | ------------- | -------------| +|*addPet* | *POST* /pet | Add a new pet to the store.| +|*deletePet* | *DELETE* /pet/{petId} | Deletes a pet.| +|*findPetsByStatus* | *GET* /pet/findByStatus | Finds Pets by status.| +|*findPetsByTags* | *GET* /pet/findByTags | Finds Pets by tags.| +|*getPetById* | *GET* /pet/{petId} | Find pet by ID.| +|*updatePet* | *PUT* /pet | Update an existing pet.| +|*updatePetWithForm* | *POST* /pet/{petId} | Updates a pet in the store with form data.| +|*uploadFile* | *POST* /pet/{petId}/uploadImage | uploads an image.| + +### StoreApi +|Method | HTTP request | Description| +|------------- | ------------- | -------------| +|*deleteOrder* | *DELETE* /store/order/{orderId} | Delete purchase order by ID.| +|*getInventory* | *GET* /store/inventory | Returns pet inventories by status.| +|*getOrderById* | *GET* /store/order/{orderId} | Find purchase order by ID.| +|*placeOrder* | *POST* /store/order | Place an order for a pet.| + +### UserApi +|Method | HTTP request | Description| +|------------- | ------------- | -------------| +|*createUser* | *POST* /user | Create user.| +|*createUsersWithArrayInput* | *POST* /user/createWithArray | Creates list of users with given input array.| +|*createUsersWithListInput* | *POST* /user/createWithList | Creates list of users with given input array.| +|*deleteUser* | *DELETE* /user/{username} | Delete user.| +|*getUserByName* | *GET* /user/{username} | Get user by user name.| +|*loginUser* | *GET* /user/login | Logs user into the system.| +|*logoutUser* | *GET* /user/logout | Logs out current logged in user session.| +|*updateUser* | *PUT* /user/{username} | Updated user.| + + +## What are the Model files for the data structures/objects? +|Class | Description| +|------------- | -------------| +|*ApiResponse* | Describes the result of uploading an image resource| +|*Category* | A category for a pet| +|*Order* | An order for a pets from the pet store| +|*Pet* | A pet for sale in the pet store| +|*Tag* | A tag for a pet| +|*User* | A User who is purchasing from the pet store| + + diff --git a/samples/client/petstore/tiny/cpp/lib/Models/ApiResponse.cpp b/samples/client/petstore/tiny/cpp/lib/Models/ApiResponse.cpp new file mode 100644 index 00000000000..e9be9e2b618 --- /dev/null +++ b/samples/client/petstore/tiny/cpp/lib/Models/ApiResponse.cpp @@ -0,0 +1,139 @@ + + +#include "ApiResponse.h" + +using namespace Tiny; + +ApiResponse::ApiResponse() +{ + code = int(0); + type = std::string(); + message = std::string(); +} + +ApiResponse::ApiResponse(std::string jsonString) +{ + this->fromJson(jsonString); +} + +ApiResponse::~ApiResponse() +{ + +} + +void +ApiResponse::fromJson(std::string jsonObj) +{ + bourne::json object = bourne::json::parse(jsonObj); + + const char *codeKey = "code"; + + if(object.has_key(codeKey)) + { + bourne::json value = object[codeKey]; + + + + jsonToValue(&code, value, "int"); + + + } + + const char *typeKey = "type"; + + if(object.has_key(typeKey)) + { + bourne::json value = object[typeKey]; + + + + jsonToValue(&type, value, "std::string"); + + + } + + const char *messageKey = "message"; + + if(object.has_key(messageKey)) + { + bourne::json value = object[messageKey]; + + + + jsonToValue(&message, value, "std::string"); + + + } + + +} + +bourne::json +ApiResponse::toJson() +{ + bourne::json object = bourne::json::object(); + + + + + + object["code"] = getCode(); + + + + + + + object["type"] = getType(); + + + + + + + object["message"] = getMessage(); + + + + return object; + +} + +int +ApiResponse::getCode() +{ + return code; +} + +void +ApiResponse::setCode(int code) +{ + this->code = code; +} + +std::string +ApiResponse::getType() +{ + return type; +} + +void +ApiResponse::setType(std::string type) +{ + this->type = type; +} + +std::string +ApiResponse::getMessage() +{ + return message; +} + +void +ApiResponse::setMessage(std::string message) +{ + this->message = message; +} + + + diff --git a/samples/client/petstore/tiny/cpp/lib/Models/ApiResponse.h b/samples/client/petstore/tiny/cpp/lib/Models/ApiResponse.h new file mode 100644 index 00000000000..dbaf8abcaf3 --- /dev/null +++ b/samples/client/petstore/tiny/cpp/lib/Models/ApiResponse.h @@ -0,0 +1,78 @@ + +/* + * ApiResponse.h + * + * Describes the result of uploading an image resource + */ + +#ifndef TINY_CPP_CLIENT_ApiResponse_H_ +#define TINY_CPP_CLIENT_ApiResponse_H_ + + +#include +#include "bourne/json.hpp" +#include "Helpers.h" + +namespace Tiny { + + +/*! \brief Describes the result of uploading an image resource + * + * \ingroup Models + * + */ + +class ApiResponse{ +public: + + /*! \brief Constructor. + */ + ApiResponse(); + ApiResponse(std::string jsonString); + + + /*! \brief Destructor. + */ + virtual ~ApiResponse(); + + + /*! \brief Retrieve a bourne JSON representation of this class. + */ + bourne::json toJson(); + + + /*! \brief Fills in members of this class from bourne JSON object representing it. + */ + void fromJson(std::string jsonObj); + + /*! \brief Get + */ + int getCode(); + + /*! \brief Set + */ + void setCode(int code); + /*! \brief Get + */ + std::string getType(); + + /*! \brief Set + */ + void setType(std::string type); + /*! \brief Get + */ + std::string getMessage(); + + /*! \brief Set + */ + void setMessage(std::string message); + + + private: + int code{}; + std::string type{}; + std::string message{}; +}; +} + +#endif /* TINY_CPP_CLIENT_ApiResponse_H_ */ diff --git a/samples/client/petstore/tiny/cpp/lib/Models/Category.cpp b/samples/client/petstore/tiny/cpp/lib/Models/Category.cpp new file mode 100644 index 00000000000..950b06ffd44 --- /dev/null +++ b/samples/client/petstore/tiny/cpp/lib/Models/Category.cpp @@ -0,0 +1,106 @@ + + +#include "Category.h" + +using namespace Tiny; + +Category::Category() +{ + id = long(0); + name = std::string(); +} + +Category::Category(std::string jsonString) +{ + this->fromJson(jsonString); +} + +Category::~Category() +{ + +} + +void +Category::fromJson(std::string jsonObj) +{ + bourne::json object = bourne::json::parse(jsonObj); + + const char *idKey = "id"; + + if(object.has_key(idKey)) + { + bourne::json value = object[idKey]; + + + + jsonToValue(&id, value, "long"); + + + } + + const char *nameKey = "name"; + + if(object.has_key(nameKey)) + { + bourne::json value = object[nameKey]; + + + + jsonToValue(&name, value, "std::string"); + + + } + + +} + +bourne::json +Category::toJson() +{ + bourne::json object = bourne::json::object(); + + + + + + object["id"] = getId(); + + + + + + + object["name"] = getName(); + + + + return object; + +} + +long +Category::getId() +{ + return id; +} + +void +Category::setId(long id) +{ + this->id = id; +} + +std::string +Category::getName() +{ + return name; +} + +void +Category::setName(std::string name) +{ + this->name = name; +} + + + diff --git a/samples/client/petstore/tiny/cpp/lib/Models/Category.h b/samples/client/petstore/tiny/cpp/lib/Models/Category.h new file mode 100644 index 00000000000..9c90e3dd416 --- /dev/null +++ b/samples/client/petstore/tiny/cpp/lib/Models/Category.h @@ -0,0 +1,70 @@ + +/* + * Category.h + * + * A category for a pet + */ + +#ifndef TINY_CPP_CLIENT_Category_H_ +#define TINY_CPP_CLIENT_Category_H_ + + +#include +#include "bourne/json.hpp" +#include "Helpers.h" + +namespace Tiny { + + +/*! \brief A category for a pet + * + * \ingroup Models + * + */ + +class Category{ +public: + + /*! \brief Constructor. + */ + Category(); + Category(std::string jsonString); + + + /*! \brief Destructor. + */ + virtual ~Category(); + + + /*! \brief Retrieve a bourne JSON representation of this class. + */ + bourne::json toJson(); + + + /*! \brief Fills in members of this class from bourne JSON object representing it. + */ + void fromJson(std::string jsonObj); + + /*! \brief Get + */ + long getId(); + + /*! \brief Set + */ + void setId(long id); + /*! \brief Get + */ + std::string getName(); + + /*! \brief Set + */ + void setName(std::string name); + + + private: + long id{}; + std::string name{}; +}; +} + +#endif /* TINY_CPP_CLIENT_Category_H_ */ diff --git a/samples/client/petstore/tiny/cpp/lib/Models/Helpers.cpp b/samples/client/petstore/tiny/cpp/lib/Models/Helpers.cpp new file mode 100644 index 00000000000..c3935b37cde --- /dev/null +++ b/samples/client/petstore/tiny/cpp/lib/Models/Helpers.cpp @@ -0,0 +1,102 @@ +#include "Helpers.h" +#include +#include + +bool isprimitive(std::string type){ + if(type == "std::string" || + type == "int" || + type == "float" || + type == "long" || + type == "double" || + type == "bool" || + type == "std::map" || + type == "std::list") + { + return true; + } + return false; +} + + +void +jsonToValue(void* target, bourne::json value, std::string type) +{ + if (target == NULL || value.is_null()) { + return; + } + + else if (type.compare("bool") == 0) + { + bool* val = static_cast (target); + *val = value.to_bool(); + } + + else if (type.compare("int") == 0) + { + int* val = static_cast (target); + *val = value.to_int(); + } + + else if (type.compare("float") == 0) + { + float* val = static_cast (target); + *val = (float)(value.to_float()); + } + + else if (type.compare("long") == 0) + { + long* val = static_cast (target); + *val = (long)(value.to_int()); + } + + else if (type.compare("double") == 0) + { + double* val = static_cast (target); + *val = value.to_float(); + } + + else if (type.compare("std::string") == 0) + { + std::string* val = static_cast (target); + *val = value.to_string(); + } + else { + return; + } +} + +std::string +stringify(long input){ + std::stringstream stream; + stream << input; + return stream.str(); + +}; + +std::string +stringify(int input){ + std::stringstream stream; + stream << input; + return stream.str(); +}; + +std::string +stringify(double input){ + std::stringstream stream; + stream << input; + return stream.str(); +}; + +std::string +stringify(float input){ + std::stringstream stream; + stream << input; + return stream.str(); +}; + +std::string +stringify(std::string input){ + std::stringstream stream; + stream << input; + return stream.str(); +}; diff --git a/samples/client/petstore/tiny/cpp/lib/Models/Helpers.h b/samples/client/petstore/tiny/cpp/lib/Models/Helpers.h new file mode 100644 index 00000000000..5ef7d9afdf7 --- /dev/null +++ b/samples/client/petstore/tiny/cpp/lib/Models/Helpers.h @@ -0,0 +1,22 @@ +#ifndef TINY_CPP_CLIENT_HELPERS_H_ +#define TINY_CPP_CLIENT_HELPERS_H_ + +#include +#include "bourne/json.hpp" + +bool isprimitive(std::string type); + +void jsonToValue(void* target, bourne::json value, std::string type); + +std::string stringify(long input); + +std::string stringify(int input); + +std::string stringify(double input); + +std::string stringify(float input); + +std::string stringify(std::string input); + +#endif /* TINY_CPP_CLIENT_HELPERS_H_ */ + diff --git a/samples/client/petstore/tiny/cpp/lib/Models/Order.cpp b/samples/client/petstore/tiny/cpp/lib/Models/Order.cpp new file mode 100644 index 00000000000..b8b7e00d3fc --- /dev/null +++ b/samples/client/petstore/tiny/cpp/lib/Models/Order.cpp @@ -0,0 +1,238 @@ + + +#include "Order.h" + +using namespace Tiny; + +Order::Order() +{ + id = long(0); + petId = long(0); + quantity = int(0); + shipDate = std::string(); + status = std::string(); + complete = bool(false); +} + +Order::Order(std::string jsonString) +{ + this->fromJson(jsonString); +} + +Order::~Order() +{ + +} + +void +Order::fromJson(std::string jsonObj) +{ + bourne::json object = bourne::json::parse(jsonObj); + + const char *idKey = "id"; + + if(object.has_key(idKey)) + { + bourne::json value = object[idKey]; + + + + jsonToValue(&id, value, "long"); + + + } + + const char *petIdKey = "petId"; + + if(object.has_key(petIdKey)) + { + bourne::json value = object[petIdKey]; + + + + jsonToValue(&petId, value, "long"); + + + } + + const char *quantityKey = "quantity"; + + if(object.has_key(quantityKey)) + { + bourne::json value = object[quantityKey]; + + + + jsonToValue(&quantity, value, "int"); + + + } + + const char *shipDateKey = "shipDate"; + + if(object.has_key(shipDateKey)) + { + bourne::json value = object[shipDateKey]; + + + + jsonToValue(&shipDate, value, "std::string"); + + + } + + const char *statusKey = "status"; + + if(object.has_key(statusKey)) + { + bourne::json value = object[statusKey]; + + + + jsonToValue(&status, value, "std::string"); + + + } + + const char *completeKey = "complete"; + + if(object.has_key(completeKey)) + { + bourne::json value = object[completeKey]; + + + + jsonToValue(&complete, value, "bool"); + + + } + + +} + +bourne::json +Order::toJson() +{ + bourne::json object = bourne::json::object(); + + + + + + object["id"] = getId(); + + + + + + + object["petId"] = getPetId(); + + + + + + + object["quantity"] = getQuantity(); + + + + + + + object["shipDate"] = getShipDate(); + + + + + + + object["status"] = getStatus(); + + + + + + + object["complete"] = isComplete(); + + + + return object; + +} + +long +Order::getId() +{ + return id; +} + +void +Order::setId(long id) +{ + this->id = id; +} + +long +Order::getPetId() +{ + return petId; +} + +void +Order::setPetId(long petId) +{ + this->petId = petId; +} + +int +Order::getQuantity() +{ + return quantity; +} + +void +Order::setQuantity(int quantity) +{ + this->quantity = quantity; +} + +std::string +Order::getShipDate() +{ + return shipDate; +} + +void +Order::setShipDate(std::string shipDate) +{ + this->shipDate = shipDate; +} + +std::string +Order::getStatus() +{ + return status; +} + +void +Order::setStatus(std::string status) +{ + this->status = status; +} + +bool +Order::isComplete() +{ + return complete; +} + +void +Order::setComplete(bool complete) +{ + this->complete = complete; +} + + + diff --git a/samples/client/petstore/tiny/cpp/lib/Models/Order.h b/samples/client/petstore/tiny/cpp/lib/Models/Order.h new file mode 100644 index 00000000000..6f36404f959 --- /dev/null +++ b/samples/client/petstore/tiny/cpp/lib/Models/Order.h @@ -0,0 +1,102 @@ + +/* + * Order.h + * + * An order for a pets from the pet store + */ + +#ifndef TINY_CPP_CLIENT_Order_H_ +#define TINY_CPP_CLIENT_Order_H_ + + +#include +#include "bourne/json.hpp" +#include "Helpers.h" + +namespace Tiny { + + +/*! \brief An order for a pets from the pet store + * + * \ingroup Models + * + */ + +class Order{ +public: + + /*! \brief Constructor. + */ + Order(); + Order(std::string jsonString); + + + /*! \brief Destructor. + */ + virtual ~Order(); + + + /*! \brief Retrieve a bourne JSON representation of this class. + */ + bourne::json toJson(); + + + /*! \brief Fills in members of this class from bourne JSON object representing it. + */ + void fromJson(std::string jsonObj); + + /*! \brief Get + */ + long getId(); + + /*! \brief Set + */ + void setId(long id); + /*! \brief Get + */ + long getPetId(); + + /*! \brief Set + */ + void setPetId(long petId); + /*! \brief Get + */ + int getQuantity(); + + /*! \brief Set + */ + void setQuantity(int quantity); + /*! \brief Get + */ + std::string getShipDate(); + + /*! \brief Set + */ + void setShipDate(std::string shipDate); + /*! \brief Get Order Status + */ + std::string getStatus(); + + /*! \brief Set Order Status + */ + void setStatus(std::string status); + /*! \brief Get + */ + bool isComplete(); + + /*! \brief Set + */ + void setComplete(bool complete); + + + private: + long id{}; + long petId{}; + int quantity{}; + std::string shipDate{}; + std::string status{}; + bool complete{}; +}; +} + +#endif /* TINY_CPP_CLIENT_Order_H_ */ diff --git a/samples/client/petstore/tiny/cpp/lib/Models/Pet.cpp b/samples/client/petstore/tiny/cpp/lib/Models/Pet.cpp new file mode 100644 index 00000000000..57f7781aef2 --- /dev/null +++ b/samples/client/petstore/tiny/cpp/lib/Models/Pet.cpp @@ -0,0 +1,274 @@ + + +#include "Pet.h" + +using namespace Tiny; + +Pet::Pet() +{ + id = long(0); + category = Category(); + name = std::string(); + photoUrls = std::list(); + tags = std::list(); + status = std::string(); +} + +Pet::Pet(std::string jsonString) +{ + this->fromJson(jsonString); +} + +Pet::~Pet() +{ + +} + +void +Pet::fromJson(std::string jsonObj) +{ + bourne::json object = bourne::json::parse(jsonObj); + + const char *idKey = "id"; + + if(object.has_key(idKey)) + { + bourne::json value = object[idKey]; + + + + jsonToValue(&id, value, "long"); + + + } + + const char *categoryKey = "category"; + + if(object.has_key(categoryKey)) + { + bourne::json value = object[categoryKey]; + + + + + Category* obj = &category; + obj->fromJson(value.dump()); + + } + + const char *nameKey = "name"; + + if(object.has_key(nameKey)) + { + bourne::json value = object[nameKey]; + + + + jsonToValue(&name, value, "std::string"); + + + } + + const char *photoUrlsKey = "photoUrls"; + + if(object.has_key(photoUrlsKey)) + { + bourne::json value = object[photoUrlsKey]; + + + std::list photoUrls_list; + std::string element; + for(auto& var : value.array_range()) + { + + jsonToValue(&element, var, "std::string"); + + + photoUrls_list.push_back(element); + } + photoUrls = photoUrls_list; + + + } + + const char *tagsKey = "tags"; + + if(object.has_key(tagsKey)) + { + bourne::json value = object[tagsKey]; + + + std::list tags_list; + Tag element; + for(auto& var : value.array_range()) + { + + + element.fromJson(var.dump()); + + tags_list.push_back(element); + } + tags = tags_list; + + + } + + const char *statusKey = "status"; + + if(object.has_key(statusKey)) + { + bourne::json value = object[statusKey]; + + + + jsonToValue(&status, value, "std::string"); + + + } + + +} + +bourne::json +Pet::toJson() +{ + bourne::json object = bourne::json::object(); + + + + + + object["id"] = getId(); + + + + + + + + object["category"] = getCategory().toJson(); + + + + + + object["name"] = getName(); + + + + + + std::list photoUrls_list = getPhotoUrls(); + bourne::json photoUrls_arr = bourne::json::array(); + + for(auto& var : photoUrls_list) + { + photoUrls_arr.append(var); + } + object["photoUrls"] = photoUrls_arr; + + + + + + + + + std::list tags_list = getTags(); + bourne::json tags_arr = bourne::json::array(); + + for(auto& var : tags_list) + { + Tag obj = var; + tags_arr.append(obj.toJson()); + } + object["tags"] = tags_arr; + + + + + + + + object["status"] = getStatus(); + + + + return object; + +} + +long +Pet::getId() +{ + return id; +} + +void +Pet::setId(long id) +{ + this->id = id; +} + +Category +Pet::getCategory() +{ + return category; +} + +void +Pet::setCategory(Category category) +{ + this->category = category; +} + +std::string +Pet::getName() +{ + return name; +} + +void +Pet::setName(std::string name) +{ + this->name = name; +} + +std::list +Pet::getPhotoUrls() +{ + return photoUrls; +} + +void +Pet::setPhotoUrls(std::list photoUrls) +{ + this->photoUrls = photoUrls; +} + +std::list +Pet::getTags() +{ + return tags; +} + +void +Pet::setTags(std::list tags) +{ + this->tags = tags; +} + +std::string +Pet::getStatus() +{ + return status; +} + +void +Pet::setStatus(std::string status) +{ + this->status = status; +} + + + diff --git a/samples/client/petstore/tiny/cpp/lib/Models/Pet.h b/samples/client/petstore/tiny/cpp/lib/Models/Pet.h new file mode 100644 index 00000000000..3329735f8a1 --- /dev/null +++ b/samples/client/petstore/tiny/cpp/lib/Models/Pet.h @@ -0,0 +1,105 @@ + +/* + * Pet.h + * + * A pet for sale in the pet store + */ + +#ifndef TINY_CPP_CLIENT_Pet_H_ +#define TINY_CPP_CLIENT_Pet_H_ + + +#include +#include "bourne/json.hpp" +#include "Helpers.h" +#include "Category.h" +#include "Tag.h" +#include + +namespace Tiny { + + +/*! \brief A pet for sale in the pet store + * + * \ingroup Models + * + */ + +class Pet{ +public: + + /*! \brief Constructor. + */ + Pet(); + Pet(std::string jsonString); + + + /*! \brief Destructor. + */ + virtual ~Pet(); + + + /*! \brief Retrieve a bourne JSON representation of this class. + */ + bourne::json toJson(); + + + /*! \brief Fills in members of this class from bourne JSON object representing it. + */ + void fromJson(std::string jsonObj); + + /*! \brief Get + */ + long getId(); + + /*! \brief Set + */ + void setId(long id); + /*! \brief Get + */ + Category getCategory(); + + /*! \brief Set + */ + void setCategory(Category category); + /*! \brief Get + */ + std::string getName(); + + /*! \brief Set + */ + void setName(std::string name); + /*! \brief Get + */ + std::list getPhotoUrls(); + + /*! \brief Set + */ + void setPhotoUrls(std::list photoUrls); + /*! \brief Get + */ + std::list getTags(); + + /*! \brief Set + */ + void setTags(std::list tags); + /*! \brief Get pet status in the store + */ + std::string getStatus(); + + /*! \brief Set pet status in the store + */ + void setStatus(std::string status); + + + private: + long id{}; + Category category; + std::string name{}; + std::list photoUrls; + std::list tags; + std::string status{}; +}; +} + +#endif /* TINY_CPP_CLIENT_Pet_H_ */ diff --git a/samples/client/petstore/tiny/cpp/lib/Models/Tag.cpp b/samples/client/petstore/tiny/cpp/lib/Models/Tag.cpp new file mode 100644 index 00000000000..e46d94258a1 --- /dev/null +++ b/samples/client/petstore/tiny/cpp/lib/Models/Tag.cpp @@ -0,0 +1,106 @@ + + +#include "Tag.h" + +using namespace Tiny; + +Tag::Tag() +{ + id = long(0); + name = std::string(); +} + +Tag::Tag(std::string jsonString) +{ + this->fromJson(jsonString); +} + +Tag::~Tag() +{ + +} + +void +Tag::fromJson(std::string jsonObj) +{ + bourne::json object = bourne::json::parse(jsonObj); + + const char *idKey = "id"; + + if(object.has_key(idKey)) + { + bourne::json value = object[idKey]; + + + + jsonToValue(&id, value, "long"); + + + } + + const char *nameKey = "name"; + + if(object.has_key(nameKey)) + { + bourne::json value = object[nameKey]; + + + + jsonToValue(&name, value, "std::string"); + + + } + + +} + +bourne::json +Tag::toJson() +{ + bourne::json object = bourne::json::object(); + + + + + + object["id"] = getId(); + + + + + + + object["name"] = getName(); + + + + return object; + +} + +long +Tag::getId() +{ + return id; +} + +void +Tag::setId(long id) +{ + this->id = id; +} + +std::string +Tag::getName() +{ + return name; +} + +void +Tag::setName(std::string name) +{ + this->name = name; +} + + + diff --git a/samples/client/petstore/tiny/cpp/lib/Models/Tag.h b/samples/client/petstore/tiny/cpp/lib/Models/Tag.h new file mode 100644 index 00000000000..e05bcdc9290 --- /dev/null +++ b/samples/client/petstore/tiny/cpp/lib/Models/Tag.h @@ -0,0 +1,70 @@ + +/* + * Tag.h + * + * A tag for a pet + */ + +#ifndef TINY_CPP_CLIENT_Tag_H_ +#define TINY_CPP_CLIENT_Tag_H_ + + +#include +#include "bourne/json.hpp" +#include "Helpers.h" + +namespace Tiny { + + +/*! \brief A tag for a pet + * + * \ingroup Models + * + */ + +class Tag{ +public: + + /*! \brief Constructor. + */ + Tag(); + Tag(std::string jsonString); + + + /*! \brief Destructor. + */ + virtual ~Tag(); + + + /*! \brief Retrieve a bourne JSON representation of this class. + */ + bourne::json toJson(); + + + /*! \brief Fills in members of this class from bourne JSON object representing it. + */ + void fromJson(std::string jsonObj); + + /*! \brief Get + */ + long getId(); + + /*! \brief Set + */ + void setId(long id); + /*! \brief Get + */ + std::string getName(); + + /*! \brief Set + */ + void setName(std::string name); + + + private: + long id{}; + std::string name{}; +}; +} + +#endif /* TINY_CPP_CLIENT_Tag_H_ */ diff --git a/samples/client/petstore/tiny/cpp/lib/Models/User.cpp b/samples/client/petstore/tiny/cpp/lib/Models/User.cpp new file mode 100644 index 00000000000..ac84c40205a --- /dev/null +++ b/samples/client/petstore/tiny/cpp/lib/Models/User.cpp @@ -0,0 +1,304 @@ + + +#include "User.h" + +using namespace Tiny; + +User::User() +{ + id = long(0); + username = std::string(); + firstName = std::string(); + lastName = std::string(); + email = std::string(); + password = std::string(); + phone = std::string(); + userStatus = int(0); +} + +User::User(std::string jsonString) +{ + this->fromJson(jsonString); +} + +User::~User() +{ + +} + +void +User::fromJson(std::string jsonObj) +{ + bourne::json object = bourne::json::parse(jsonObj); + + const char *idKey = "id"; + + if(object.has_key(idKey)) + { + bourne::json value = object[idKey]; + + + + jsonToValue(&id, value, "long"); + + + } + + const char *usernameKey = "username"; + + if(object.has_key(usernameKey)) + { + bourne::json value = object[usernameKey]; + + + + jsonToValue(&username, value, "std::string"); + + + } + + const char *firstNameKey = "firstName"; + + if(object.has_key(firstNameKey)) + { + bourne::json value = object[firstNameKey]; + + + + jsonToValue(&firstName, value, "std::string"); + + + } + + const char *lastNameKey = "lastName"; + + if(object.has_key(lastNameKey)) + { + bourne::json value = object[lastNameKey]; + + + + jsonToValue(&lastName, value, "std::string"); + + + } + + const char *emailKey = "email"; + + if(object.has_key(emailKey)) + { + bourne::json value = object[emailKey]; + + + + jsonToValue(&email, value, "std::string"); + + + } + + const char *passwordKey = "password"; + + if(object.has_key(passwordKey)) + { + bourne::json value = object[passwordKey]; + + + + jsonToValue(&password, value, "std::string"); + + + } + + const char *phoneKey = "phone"; + + if(object.has_key(phoneKey)) + { + bourne::json value = object[phoneKey]; + + + + jsonToValue(&phone, value, "std::string"); + + + } + + const char *userStatusKey = "userStatus"; + + if(object.has_key(userStatusKey)) + { + bourne::json value = object[userStatusKey]; + + + + jsonToValue(&userStatus, value, "int"); + + + } + + +} + +bourne::json +User::toJson() +{ + bourne::json object = bourne::json::object(); + + + + + + object["id"] = getId(); + + + + + + + object["username"] = getUsername(); + + + + + + + object["firstName"] = getFirstName(); + + + + + + + object["lastName"] = getLastName(); + + + + + + + object["email"] = getEmail(); + + + + + + + object["password"] = getPassword(); + + + + + + + object["phone"] = getPhone(); + + + + + + + object["userStatus"] = getUserStatus(); + + + + return object; + +} + +long +User::getId() +{ + return id; +} + +void +User::setId(long id) +{ + this->id = id; +} + +std::string +User::getUsername() +{ + return username; +} + +void +User::setUsername(std::string username) +{ + this->username = username; +} + +std::string +User::getFirstName() +{ + return firstName; +} + +void +User::setFirstName(std::string firstName) +{ + this->firstName = firstName; +} + +std::string +User::getLastName() +{ + return lastName; +} + +void +User::setLastName(std::string lastName) +{ + this->lastName = lastName; +} + +std::string +User::getEmail() +{ + return email; +} + +void +User::setEmail(std::string email) +{ + this->email = email; +} + +std::string +User::getPassword() +{ + return password; +} + +void +User::setPassword(std::string password) +{ + this->password = password; +} + +std::string +User::getPhone() +{ + return phone; +} + +void +User::setPhone(std::string phone) +{ + this->phone = phone; +} + +int +User::getUserStatus() +{ + return userStatus; +} + +void +User::setUserStatus(int userStatus) +{ + this->userStatus = userStatus; +} + + + diff --git a/samples/client/petstore/tiny/cpp/lib/Models/User.h b/samples/client/petstore/tiny/cpp/lib/Models/User.h new file mode 100644 index 00000000000..84de5204ced --- /dev/null +++ b/samples/client/petstore/tiny/cpp/lib/Models/User.h @@ -0,0 +1,118 @@ + +/* + * User.h + * + * A User who is purchasing from the pet store + */ + +#ifndef TINY_CPP_CLIENT_User_H_ +#define TINY_CPP_CLIENT_User_H_ + + +#include +#include "bourne/json.hpp" +#include "Helpers.h" + +namespace Tiny { + + +/*! \brief A User who is purchasing from the pet store + * + * \ingroup Models + * + */ + +class User{ +public: + + /*! \brief Constructor. + */ + User(); + User(std::string jsonString); + + + /*! \brief Destructor. + */ + virtual ~User(); + + + /*! \brief Retrieve a bourne JSON representation of this class. + */ + bourne::json toJson(); + + + /*! \brief Fills in members of this class from bourne JSON object representing it. + */ + void fromJson(std::string jsonObj); + + /*! \brief Get + */ + long getId(); + + /*! \brief Set + */ + void setId(long id); + /*! \brief Get + */ + std::string getUsername(); + + /*! \brief Set + */ + void setUsername(std::string username); + /*! \brief Get + */ + std::string getFirstName(); + + /*! \brief Set + */ + void setFirstName(std::string firstName); + /*! \brief Get + */ + std::string getLastName(); + + /*! \brief Set + */ + void setLastName(std::string lastName); + /*! \brief Get + */ + std::string getEmail(); + + /*! \brief Set + */ + void setEmail(std::string email); + /*! \brief Get + */ + std::string getPassword(); + + /*! \brief Set + */ + void setPassword(std::string password); + /*! \brief Get + */ + std::string getPhone(); + + /*! \brief Set + */ + void setPhone(std::string phone); + /*! \brief Get User Status + */ + int getUserStatus(); + + /*! \brief Set User Status + */ + void setUserStatus(int userStatus); + + + private: + long id{}; + std::string username{}; + std::string firstName{}; + std::string lastName{}; + std::string email{}; + std::string password{}; + std::string phone{}; + int userStatus{}; +}; +} + +#endif /* TINY_CPP_CLIENT_User_H_ */ diff --git a/samples/client/petstore/tiny/cpp/lib/TestFiles/ApiResponseTest.cpp b/samples/client/petstore/tiny/cpp/lib/TestFiles/ApiResponseTest.cpp new file mode 100644 index 00000000000..160f4217f5d --- /dev/null +++ b/samples/client/petstore/tiny/cpp/lib/TestFiles/ApiResponseTest.cpp @@ -0,0 +1,139 @@ + +#include "ApiResponse.h" + +using namespace Tiny; + +#include +#include +#include +#include "bourne/json.hpp" + + + +void test_ApiResponse_code_is_assigned_from_json() +{ + bourne::json input = + { + "code", 1 + }; + + ApiResponse obj(input.dump()); + + TEST_ASSERT_EQUAL_INT(1, obj.getCode()); + + + + + + + + +} + + +void test_ApiResponse_type_is_assigned_from_json() +{ + + + bourne::json input = + { + "type", "hello" + }; + + ApiResponse obj(input.dump()); + + TEST_ASSERT_EQUAL_STRING("hello", obj.getType().c_str()); + + + + + + +} + + +void test_ApiResponse_message_is_assigned_from_json() +{ + + + bourne::json input = + { + "message", "hello" + }; + + ApiResponse obj(input.dump()); + + TEST_ASSERT_EQUAL_STRING("hello", obj.getMessage().c_str()); + + + + + + +} + + + +void test_ApiResponse_code_is_converted_to_json() +{ + bourne::json input = + { + "code", 1 + }; + + ApiResponse obj(input.dump()); + + bourne::json output = bourne::json::object(); + + output = obj.toJson(); + + TEST_ASSERT(input["code"] == output["code"]); + + + + +} + + +void test_ApiResponse_type_is_converted_to_json() +{ + + bourne::json input = + { + "type", "hello" + }; + + ApiResponse obj(input.dump()); + + bourne::json output = bourne::json::object(); + + output = obj.toJson(); + + TEST_ASSERT(input["type"] == output["type"]); + + + +} + + +void test_ApiResponse_message_is_converted_to_json() +{ + + bourne::json input = + { + "message", "hello" + }; + + ApiResponse obj(input.dump()); + + bourne::json output = bourne::json::object(); + + output = obj.toJson(); + + TEST_ASSERT(input["message"] == output["message"]); + + + +} + + diff --git a/samples/client/petstore/tiny/cpp/lib/TestFiles/CategoryTest.cpp b/samples/client/petstore/tiny/cpp/lib/TestFiles/CategoryTest.cpp new file mode 100644 index 00000000000..2951856e6a5 --- /dev/null +++ b/samples/client/petstore/tiny/cpp/lib/TestFiles/CategoryTest.cpp @@ -0,0 +1,97 @@ + +#include "Category.h" + +using namespace Tiny; + +#include +#include +#include +#include "bourne/json.hpp" + + + +void test_Category_id_is_assigned_from_json() +{ + + + + + + + bourne::json input = + { + "id", 1 + }; + + Category obj(input.dump()); + + TEST_ASSERT_EQUAL_INT(1, obj.getId()); + + +} + + +void test_Category_name_is_assigned_from_json() +{ + + + bourne::json input = + { + "name", "hello" + }; + + Category obj(input.dump()); + + TEST_ASSERT_EQUAL_STRING("hello", obj.getName().c_str()); + + + + + + +} + + + +void test_Category_id_is_converted_to_json() +{ + + + + bourne::json input = + { + "id", 1 + }; + + Category obj(input.dump()); + + bourne::json output = bourne::json::object(); + + output = obj.toJson(); + + TEST_ASSERT(input["id"] == output["id"]); + +} + + +void test_Category_name_is_converted_to_json() +{ + + bourne::json input = + { + "name", "hello" + }; + + Category obj(input.dump()); + + bourne::json output = bourne::json::object(); + + output = obj.toJson(); + + TEST_ASSERT(input["name"] == output["name"]); + + + +} + + diff --git a/samples/client/petstore/tiny/cpp/lib/TestFiles/OrderTest.cpp b/samples/client/petstore/tiny/cpp/lib/TestFiles/OrderTest.cpp new file mode 100644 index 00000000000..13125fc8fc5 --- /dev/null +++ b/samples/client/petstore/tiny/cpp/lib/TestFiles/OrderTest.cpp @@ -0,0 +1,245 @@ + +#include "Order.h" + +using namespace Tiny; + +#include +#include +#include +#include "bourne/json.hpp" + + + +void test_Order_id_is_assigned_from_json() +{ + + + + + + + bourne::json input = + { + "id", 1 + }; + + Order obj(input.dump()); + + TEST_ASSERT_EQUAL_INT(1, obj.getId()); + + +} + + +void test_Order_petId_is_assigned_from_json() +{ + + + + + + + bourne::json input = + { + "petId", 1 + }; + + Order obj(input.dump()); + + TEST_ASSERT_EQUAL_INT(1, obj.getPetId()); + + +} + + +void test_Order_quantity_is_assigned_from_json() +{ + bourne::json input = + { + "quantity", 1 + }; + + Order obj(input.dump()); + + TEST_ASSERT_EQUAL_INT(1, obj.getQuantity()); + + + + + + + + +} + + +void test_Order_shipDate_is_assigned_from_json() +{ + + + + + + + + +} + + +void test_Order_status_is_assigned_from_json() +{ + + + bourne::json input = + { + "status", "hello" + }; + + Order obj(input.dump()); + + TEST_ASSERT_EQUAL_STRING("hello", obj.getStatus().c_str()); + + + + + + +} + + +void test_Order_complete_is_assigned_from_json() +{ + + + + + bourne::json input = + { + "complete", true + }; + + Order obj(input.dump()); + + TEST_ASSERT(true == obj.isComplete()); + + + + +} + + + +void test_Order_id_is_converted_to_json() +{ + + + + bourne::json input = + { + "id", 1 + }; + + Order obj(input.dump()); + + bourne::json output = bourne::json::object(); + + output = obj.toJson(); + + TEST_ASSERT(input["id"] == output["id"]); + +} + + +void test_Order_petId_is_converted_to_json() +{ + + + + bourne::json input = + { + "petId", 1 + }; + + Order obj(input.dump()); + + bourne::json output = bourne::json::object(); + + output = obj.toJson(); + + TEST_ASSERT(input["petId"] == output["petId"]); + +} + + +void test_Order_quantity_is_converted_to_json() +{ + bourne::json input = + { + "quantity", 1 + }; + + Order obj(input.dump()); + + bourne::json output = bourne::json::object(); + + output = obj.toJson(); + + TEST_ASSERT(input["quantity"] == output["quantity"]); + + + + +} + + +void test_Order_shipDate_is_converted_to_json() +{ + + + + +} + + +void test_Order_status_is_converted_to_json() +{ + + bourne::json input = + { + "status", "hello" + }; + + Order obj(input.dump()); + + bourne::json output = bourne::json::object(); + + output = obj.toJson(); + + TEST_ASSERT(input["status"] == output["status"]); + + + +} + + +void test_Order_complete_is_converted_to_json() +{ + + + bourne::json input = + { + "complete", true + }; + + Order obj(input.dump()); + + bourne::json output = bourne::json::object(); + + output = obj.toJson(); + + TEST_ASSERT(input["complete"] == output["complete"]); + + +} + + diff --git a/samples/client/petstore/tiny/cpp/lib/TestFiles/PetTest.cpp b/samples/client/petstore/tiny/cpp/lib/TestFiles/PetTest.cpp new file mode 100644 index 00000000000..04dad464093 --- /dev/null +++ b/samples/client/petstore/tiny/cpp/lib/TestFiles/PetTest.cpp @@ -0,0 +1,145 @@ + +#include "Pet.h" + +using namespace Tiny; + +#include +#include +#include +#include "bourne/json.hpp" + + + +void test_Pet_id_is_assigned_from_json() +{ + + + + + + + bourne::json input = + { + "id", 1 + }; + + Pet obj(input.dump()); + + TEST_ASSERT_EQUAL_INT(1, obj.getId()); + + +} + + + +void test_Pet_name_is_assigned_from_json() +{ + + + bourne::json input = + { + "name", "hello" + }; + + Pet obj(input.dump()); + + TEST_ASSERT_EQUAL_STRING("hello", obj.getName().c_str()); + + + + + + +} + + + + +void test_Pet_status_is_assigned_from_json() +{ + + + bourne::json input = + { + "status", "hello" + }; + + Pet obj(input.dump()); + + TEST_ASSERT_EQUAL_STRING("hello", obj.getStatus().c_str()); + + + + + + +} + + + +void test_Pet_id_is_converted_to_json() +{ + + + + bourne::json input = + { + "id", 1 + }; + + Pet obj(input.dump()); + + bourne::json output = bourne::json::object(); + + output = obj.toJson(); + + TEST_ASSERT(input["id"] == output["id"]); + +} + + + +void test_Pet_name_is_converted_to_json() +{ + + bourne::json input = + { + "name", "hello" + }; + + Pet obj(input.dump()); + + bourne::json output = bourne::json::object(); + + output = obj.toJson(); + + TEST_ASSERT(input["name"] == output["name"]); + + + +} + + + + +void test_Pet_status_is_converted_to_json() +{ + + bourne::json input = + { + "status", "hello" + }; + + Pet obj(input.dump()); + + bourne::json output = bourne::json::object(); + + output = obj.toJson(); + + TEST_ASSERT(input["status"] == output["status"]); + + + +} + + diff --git a/samples/client/petstore/tiny/cpp/lib/TestFiles/TagTest.cpp b/samples/client/petstore/tiny/cpp/lib/TestFiles/TagTest.cpp new file mode 100644 index 00000000000..41ea1d0095d --- /dev/null +++ b/samples/client/petstore/tiny/cpp/lib/TestFiles/TagTest.cpp @@ -0,0 +1,97 @@ + +#include "Tag.h" + +using namespace Tiny; + +#include +#include +#include +#include "bourne/json.hpp" + + + +void test_Tag_id_is_assigned_from_json() +{ + + + + + + + bourne::json input = + { + "id", 1 + }; + + Tag obj(input.dump()); + + TEST_ASSERT_EQUAL_INT(1, obj.getId()); + + +} + + +void test_Tag_name_is_assigned_from_json() +{ + + + bourne::json input = + { + "name", "hello" + }; + + Tag obj(input.dump()); + + TEST_ASSERT_EQUAL_STRING("hello", obj.getName().c_str()); + + + + + + +} + + + +void test_Tag_id_is_converted_to_json() +{ + + + + bourne::json input = + { + "id", 1 + }; + + Tag obj(input.dump()); + + bourne::json output = bourne::json::object(); + + output = obj.toJson(); + + TEST_ASSERT(input["id"] == output["id"]); + +} + + +void test_Tag_name_is_converted_to_json() +{ + + bourne::json input = + { + "name", "hello" + }; + + Tag obj(input.dump()); + + bourne::json output = bourne::json::object(); + + output = obj.toJson(); + + TEST_ASSERT(input["name"] == output["name"]); + + + +} + + diff --git a/samples/client/petstore/tiny/cpp/lib/TestFiles/UserTest.cpp b/samples/client/petstore/tiny/cpp/lib/TestFiles/UserTest.cpp new file mode 100644 index 00000000000..689ee582bee --- /dev/null +++ b/samples/client/petstore/tiny/cpp/lib/TestFiles/UserTest.cpp @@ -0,0 +1,349 @@ + +#include "User.h" + +using namespace Tiny; + +#include +#include +#include +#include "bourne/json.hpp" + + + +void test_User_id_is_assigned_from_json() +{ + + + + + + + bourne::json input = + { + "id", 1 + }; + + User obj(input.dump()); + + TEST_ASSERT_EQUAL_INT(1, obj.getId()); + + +} + + +void test_User_username_is_assigned_from_json() +{ + + + bourne::json input = + { + "username", "hello" + }; + + User obj(input.dump()); + + TEST_ASSERT_EQUAL_STRING("hello", obj.getUsername().c_str()); + + + + + + +} + + +void test_User_firstName_is_assigned_from_json() +{ + + + bourne::json input = + { + "firstName", "hello" + }; + + User obj(input.dump()); + + TEST_ASSERT_EQUAL_STRING("hello", obj.getFirstName().c_str()); + + + + + + +} + + +void test_User_lastName_is_assigned_from_json() +{ + + + bourne::json input = + { + "lastName", "hello" + }; + + User obj(input.dump()); + + TEST_ASSERT_EQUAL_STRING("hello", obj.getLastName().c_str()); + + + + + + +} + + +void test_User_email_is_assigned_from_json() +{ + + + bourne::json input = + { + "email", "hello" + }; + + User obj(input.dump()); + + TEST_ASSERT_EQUAL_STRING("hello", obj.getEmail().c_str()); + + + + + + +} + + +void test_User_password_is_assigned_from_json() +{ + + + bourne::json input = + { + "password", "hello" + }; + + User obj(input.dump()); + + TEST_ASSERT_EQUAL_STRING("hello", obj.getPassword().c_str()); + + + + + + +} + + +void test_User_phone_is_assigned_from_json() +{ + + + bourne::json input = + { + "phone", "hello" + }; + + User obj(input.dump()); + + TEST_ASSERT_EQUAL_STRING("hello", obj.getPhone().c_str()); + + + + + + +} + + +void test_User_userStatus_is_assigned_from_json() +{ + bourne::json input = + { + "userStatus", 1 + }; + + User obj(input.dump()); + + TEST_ASSERT_EQUAL_INT(1, obj.getUserStatus()); + + + + + + + + +} + + + +void test_User_id_is_converted_to_json() +{ + + + + bourne::json input = + { + "id", 1 + }; + + User obj(input.dump()); + + bourne::json output = bourne::json::object(); + + output = obj.toJson(); + + TEST_ASSERT(input["id"] == output["id"]); + +} + + +void test_User_username_is_converted_to_json() +{ + + bourne::json input = + { + "username", "hello" + }; + + User obj(input.dump()); + + bourne::json output = bourne::json::object(); + + output = obj.toJson(); + + TEST_ASSERT(input["username"] == output["username"]); + + + +} + + +void test_User_firstName_is_converted_to_json() +{ + + bourne::json input = + { + "firstName", "hello" + }; + + User obj(input.dump()); + + bourne::json output = bourne::json::object(); + + output = obj.toJson(); + + TEST_ASSERT(input["firstName"] == output["firstName"]); + + + +} + + +void test_User_lastName_is_converted_to_json() +{ + + bourne::json input = + { + "lastName", "hello" + }; + + User obj(input.dump()); + + bourne::json output = bourne::json::object(); + + output = obj.toJson(); + + TEST_ASSERT(input["lastName"] == output["lastName"]); + + + +} + + +void test_User_email_is_converted_to_json() +{ + + bourne::json input = + { + "email", "hello" + }; + + User obj(input.dump()); + + bourne::json output = bourne::json::object(); + + output = obj.toJson(); + + TEST_ASSERT(input["email"] == output["email"]); + + + +} + + +void test_User_password_is_converted_to_json() +{ + + bourne::json input = + { + "password", "hello" + }; + + User obj(input.dump()); + + bourne::json output = bourne::json::object(); + + output = obj.toJson(); + + TEST_ASSERT(input["password"] == output["password"]); + + + +} + + +void test_User_phone_is_converted_to_json() +{ + + bourne::json input = + { + "phone", "hello" + }; + + User obj(input.dump()); + + bourne::json output = bourne::json::object(); + + output = obj.toJson(); + + TEST_ASSERT(input["phone"] == output["phone"]); + + + +} + + +void test_User_userStatus_is_converted_to_json() +{ + bourne::json input = + { + "userStatus", 1 + }; + + User obj(input.dump()); + + bourne::json output = bourne::json::object(); + + output = obj.toJson(); + + TEST_ASSERT(input["userStatus"] == output["userStatus"]); + + + + +} + + diff --git a/samples/client/petstore/tiny/cpp/lib/service/AbstractService.cpp b/samples/client/petstore/tiny/cpp/lib/service/AbstractService.cpp new file mode 100644 index 00000000000..ac7e992cecc --- /dev/null +++ b/samples/client/petstore/tiny/cpp/lib/service/AbstractService.cpp @@ -0,0 +1,8 @@ +#include "AbstractService.h" +#include "Arduino.h" + + + +void Tiny::AbstractService::begin(std::string url){ + http.begin(String(url.c_str()), test_root_ca); //HTTPS connection +} diff --git a/samples/client/petstore/tiny/cpp/lib/service/AbstractService.h b/samples/client/petstore/tiny/cpp/lib/service/AbstractService.h new file mode 100644 index 00000000000..07214896d7f --- /dev/null +++ b/samples/client/petstore/tiny/cpp/lib/service/AbstractService.h @@ -0,0 +1,28 @@ +#ifndef TINY_CPP_CLIENT_ABSTRACTSERVICE_H_ +#define TINY_CPP_CLIENT_ABSTRACTSERVICE_H_ + +#include "HTTPClient.h" +#include "Response.h" +namespace Tiny { + +/** +* Class +* Generated with openapi::tiny-cpp-client +*/ +class AbstractService { +public: +HTTPClient http; +std::string basepath = "https://petstore3.swagger.io/api/v3"; // TODO: change to your url + +void begin(std::string url); + +// Go and comment out a certificate in root.cert, if you get an error here +// Certificate from file +const char* test_root_ca = +#include "../../root.cert" +; + +}; // end class +}// namespace Tinyclient + +#endif /* TINY_CPP_CLIENT_ABSTRACTSERVICE_H_ */ diff --git a/samples/client/petstore/tiny/cpp/lib/service/PetApi.cpp b/samples/client/petstore/tiny/cpp/lib/service/PetApi.cpp new file mode 100644 index 00000000000..1fa081a04b4 --- /dev/null +++ b/samples/client/petstore/tiny/cpp/lib/service/PetApi.cpp @@ -0,0 +1,418 @@ +#include "PetApi.h" + +using namespace Tiny; + + + + Response< + Pet + > + PetApi:: + addPet( + + Pet pet + + ) + { + std::string url = basepath + "/pet"; // + // Query | + // Headers | + // Form | + // Body | pet + + + begin(url); + + std::string payload = ""; + // Send Request + // METHOD | POST + http.addHeader("Content-Type", "application/json"); + + + + payload = pet.toJson().dump(); + + int httpCode = http.sendRequest("POST", reinterpret_cast(&payload[0]), payload.length()); + + // Handle Request + String output = http.getString(); + std::string output_string = output.c_str(); + + http.end(); + + + + + Pet obj(output_string); + + + Response response(obj, httpCode); + return response; + } + + Response< + String + > + PetApi:: + deletePet( + + long petId + , + + std::string apiKey + + ) + { + std::string url = basepath + "/pet/{petId}"; //petId + // Query | + // Headers | apiKey + // Form | + // Body | + + std::string s_petId("{"); + s_petId.append("petId"); + s_petId.append("}"); + + int pos = url.find(s_petId); + + url.erase(pos, s_petId.length()); + url.insert(pos, stringify(petId)); + + begin(url); + + std::string payload = ""; + // Send Request + // METHOD | DELETE + int httpCode = http.sendRequest("DELETE", reinterpret_cast(&payload[0]), payload.length()); + + // Handle Request + String output = http.getString(); + std::string output_string = output.c_str(); + + http.end(); + + + Response response(output, httpCode); + return response; + } + + Response< + std::list + > + PetApi:: + findPetsByStatus( + std::list status + + + ) + { + std::string url = basepath + "/pet/findByStatus"; // + // Query | status + // Headers | + // Form | + // Body | + + + begin(url); + + std::string payload = ""; + // Send Request + // METHOD | GET + int httpCode = http.sendRequest("GET", reinterpret_cast(&payload[0]), payload.length()); + + // Handle Request + String output = http.getString(); + std::string output_string = output.c_str(); + + http.end(); + + + + std::list obj = std::list(); + bourne::json jsonPayload(output_string); + + + + + + + + + + for(auto& var : jsonPayload.array_range()) + { + Pet tmp(var.dump()); + obj.push_back(tmp); + } + + + + + + + + + Response> response(obj, httpCode); + return response; + } + + Response< + std::list + > + PetApi:: + findPetsByTags( + std::list tags + + + ) + { + std::string url = basepath + "/pet/findByTags"; // + // Query | tags + // Headers | + // Form | + // Body | + + + begin(url); + + std::string payload = ""; + // Send Request + // METHOD | GET + int httpCode = http.sendRequest("GET", reinterpret_cast(&payload[0]), payload.length()); + + // Handle Request + String output = http.getString(); + std::string output_string = output.c_str(); + + http.end(); + + + + std::list obj = std::list(); + bourne::json jsonPayload(output_string); + + + + + + + + + + for(auto& var : jsonPayload.array_range()) + { + Pet tmp(var.dump()); + obj.push_back(tmp); + } + + + + + + + + + Response> response(obj, httpCode); + return response; + } + + Response< + Pet + > + PetApi:: + getPetById( + + long petId + + ) + { + std::string url = basepath + "/pet/{petId}"; //petId + // Query | + // Headers | + // Form | + // Body | + + std::string s_petId("{"); + s_petId.append("petId"); + s_petId.append("}"); + + int pos = url.find(s_petId); + + url.erase(pos, s_petId.length()); + url.insert(pos, stringify(petId)); + + begin(url); + + std::string payload = ""; + // Send Request + // METHOD | GET + int httpCode = http.sendRequest("GET", reinterpret_cast(&payload[0]), payload.length()); + + // Handle Request + String output = http.getString(); + std::string output_string = output.c_str(); + + http.end(); + + + + + Pet obj(output_string); + + + Response response(obj, httpCode); + return response; + } + + Response< + Pet + > + PetApi:: + updatePet( + + Pet pet + + ) + { + std::string url = basepath + "/pet"; // + // Query | + // Headers | + // Form | + // Body | pet + + + begin(url); + + std::string payload = ""; + // Send Request + // METHOD | PUT + http.addHeader("Content-Type", "application/json"); + + + + payload = pet.toJson().dump(); + + int httpCode = http.sendRequest("PUT", reinterpret_cast(&payload[0]), payload.length()); + + // Handle Request + String output = http.getString(); + std::string output_string = output.c_str(); + + http.end(); + + + + + Pet obj(output_string); + + + Response response(obj, httpCode); + return response; + } + + Response< + String + > + PetApi:: + updatePetWithForm( + + long petId + , + + std::string name + , + + std::string status + + ) + { + std::string url = basepath + "/pet/{petId}"; //petId + // Query | + // Headers | + // Form | name status + // Body | + + std::string s_petId("{"); + s_petId.append("petId"); + s_petId.append("}"); + + int pos = url.find(s_petId); + + url.erase(pos, s_petId.length()); + url.insert(pos, stringify(petId)); + + begin(url); + + std::string payload = ""; + // Send Request + // METHOD | POST + int httpCode = http.sendRequest("POST", reinterpret_cast(&payload[0]), payload.length()); + + // Handle Request + String output = http.getString(); + std::string output_string = output.c_str(); + + http.end(); + + + Response response(output, httpCode); + return response; + } + + Response< + ApiResponse + > + PetApi:: + uploadFile( + + long petId + , + + std::string additionalMetadata + , + + std::string file + + ) + { + std::string url = basepath + "/pet/{petId}/uploadImage"; //petId + // Query | + // Headers | + // Form | additionalMetadata file + // Body | + + std::string s_petId("{"); + s_petId.append("petId"); + s_petId.append("}"); + + int pos = url.find(s_petId); + + url.erase(pos, s_petId.length()); + url.insert(pos, stringify(petId)); + + begin(url); + + std::string payload = ""; + // Send Request + // METHOD | POST + int httpCode = http.sendRequest("POST", reinterpret_cast(&payload[0]), payload.length()); + + // Handle Request + String output = http.getString(); + std::string output_string = output.c_str(); + + http.end(); + + + + + ApiResponse obj(output_string); + + + Response response(obj, httpCode); + return response; + } + + + + diff --git a/samples/client/petstore/tiny/cpp/lib/service/PetApi.h b/samples/client/petstore/tiny/cpp/lib/service/PetApi.h new file mode 100644 index 00000000000..abcb0af0de9 --- /dev/null +++ b/samples/client/petstore/tiny/cpp/lib/service/PetApi.h @@ -0,0 +1,163 @@ +#ifndef TINY_CPP_CLIENT_PetApi_H_ +#define TINY_CPP_CLIENT_PetApi_H_ + + +#include "Response.h" +#include "Arduino.h" +#include "AbstractService.h" +#include "Helpers.h" +#include + +#include "ApiResponse.h" +#include "Pet.h" + +namespace Tiny { + +/** + * Class + * Generated with openapi::tiny-cpp-client + */ + +class PetApi : public AbstractService { +public: + PetApi() = default; + + virtual ~PetApi() = default; + + /** + * Add a new pet to the store. + * + * + * \param pet Pet object that needs to be added to the store *Required* + */ + Response< + Pet + > + addPet( + + Pet pet + + ); + /** + * Deletes a pet. + * + * + * \param petId Pet id to delete *Required* + * \param apiKey + */ + Response< + String + > + deletePet( + + long petId + , + + std::string apiKey + + ); + /** + * 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* + */ + Response< + std::list + > + findPetsByStatus( + std::list status + + + ); + /** + * 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* + */ + Response< + std::list + > + findPetsByTags( + std::list tags + + + ); + /** + * Find pet by ID. + * + * Returns a single pet + * \param petId ID of pet to return *Required* + */ + Response< + Pet + > + getPetById( + + long petId + + ); + /** + * Update an existing pet. + * + * + * \param pet Pet object that needs to be added to the store *Required* + */ + Response< + Pet + > + updatePet( + + Pet pet + + ); + /** + * Updates a pet in the store with form data. + * + * + * \param petId ID of pet that needs to be updated *Required* + * \param name Updated name of the pet + * \param status Updated status of the pet + */ + Response< + String + > + updatePetWithForm( + + long petId + , + + std::string name + , + + std::string status + + ); + /** + * uploads an image. + * + * + * \param petId ID of pet to update *Required* + * \param additionalMetadata Additional data to pass to server + * \param file file to upload + */ + Response< + ApiResponse + > + uploadFile( + + long petId + , + + std::string additionalMetadata + , + + std::string file + + ); +}; + +} + +#endif /* TINY_CPP_CLIENT_PetApi_H_ */ \ No newline at end of file diff --git a/samples/client/petstore/tiny/cpp/lib/service/Response.h b/samples/client/petstore/tiny/cpp/lib/service/Response.h new file mode 100644 index 00000000000..9b7b616b8f1 --- /dev/null +++ b/samples/client/petstore/tiny/cpp/lib/service/Response.h @@ -0,0 +1,25 @@ +#ifndef TINY_CPP_CLIENT_RESPONSE_H_ +#define TINY_CPP_CLIENT_RESPONSE_H_ +#include + +namespace Tiny { + +/** +* Class +* Generated with openapi::tiny-cpp-client +*/ +template + class Response { + public: + + Response(T _obj, int _code){ + obj = _obj; + code = _code; + } + + int code; + T obj; + }; + } // namespace Tinyclient + +#endif /* TINY_CPP_CLIENT_RESPONSE_H_ */ diff --git a/samples/client/petstore/tiny/cpp/lib/service/StoreApi.cpp b/samples/client/petstore/tiny/cpp/lib/service/StoreApi.cpp new file mode 100644 index 00000000000..210eb8277ac --- /dev/null +++ b/samples/client/petstore/tiny/cpp/lib/service/StoreApi.cpp @@ -0,0 +1,185 @@ +#include "StoreApi.h" + +using namespace Tiny; + + + + Response< + String + > + StoreApi:: + deleteOrder( + + std::string orderId + + ) + { + std::string url = basepath + "/store/order/{orderId}"; //orderId + // Query | + // Headers | + // Form | + // Body | + + std::string s_orderId("{"); + s_orderId.append("orderId"); + s_orderId.append("}"); + + int pos = url.find(s_orderId); + + url.erase(pos, s_orderId.length()); + url.insert(pos, stringify(orderId)); + + begin(url); + + std::string payload = ""; + // Send Request + // METHOD | DELETE + int httpCode = http.sendRequest("DELETE", reinterpret_cast(&payload[0]), payload.length()); + + // Handle Request + String output = http.getString(); + std::string output_string = output.c_str(); + + http.end(); + + + Response response(output, httpCode); + return response; + } + + Response< + String + > + StoreApi:: + getInventory( + ) + { + std::string url = basepath + "/store/inventory"; // + // Query | + // Headers | + // Form | + // Body | + + + begin(url); + + std::string payload = ""; + // Send Request + // METHOD | GET + int httpCode = http.sendRequest("GET", reinterpret_cast(&payload[0]), payload.length()); + + // Handle Request + String output = http.getString(); + std::string output_string = output.c_str(); + + http.end(); + + + + //TODO: Implement map logic here + + + + + //TODO: No support for maps. + Response response(output, httpCode); + return response; + } + + Response< + Order + > + StoreApi:: + getOrderById( + + long orderId + + ) + { + std::string url = basepath + "/store/order/{orderId}"; //orderId + // Query | + // Headers | + // Form | + // Body | + + std::string s_orderId("{"); + s_orderId.append("orderId"); + s_orderId.append("}"); + + int pos = url.find(s_orderId); + + url.erase(pos, s_orderId.length()); + url.insert(pos, stringify(orderId)); + + begin(url); + + std::string payload = ""; + // Send Request + // METHOD | GET + int httpCode = http.sendRequest("GET", reinterpret_cast(&payload[0]), payload.length()); + + // Handle Request + String output = http.getString(); + std::string output_string = output.c_str(); + + http.end(); + + + + + Order obj(output_string); + + + Response response(obj, httpCode); + return response; + } + + Response< + Order + > + StoreApi:: + placeOrder( + + Order order + + ) + { + std::string url = basepath + "/store/order"; // + // Query | + // Headers | + // Form | + // Body | order + + + begin(url); + + std::string payload = ""; + // Send Request + // METHOD | POST + http.addHeader("Content-Type", "application/json"); + + + + payload = order.toJson().dump(); + + int httpCode = http.sendRequest("POST", reinterpret_cast(&payload[0]), payload.length()); + + // Handle Request + String output = http.getString(); + std::string output_string = output.c_str(); + + http.end(); + + + + + Order obj(output_string); + + + Response response(obj, httpCode); + return response; + } + + + + diff --git a/samples/client/petstore/tiny/cpp/lib/service/StoreApi.h b/samples/client/petstore/tiny/cpp/lib/service/StoreApi.h new file mode 100644 index 00000000000..1bf0db02373 --- /dev/null +++ b/samples/client/petstore/tiny/cpp/lib/service/StoreApi.h @@ -0,0 +1,83 @@ +#ifndef TINY_CPP_CLIENT_StoreApi_H_ +#define TINY_CPP_CLIENT_StoreApi_H_ + + +#include "Response.h" +#include "Arduino.h" +#include "AbstractService.h" +#include "Helpers.h" +#include + +#include +#include "Order.h" + +namespace Tiny { + +/** + * Class + * Generated with openapi::tiny-cpp-client + */ + +class StoreApi : public AbstractService { +public: + StoreApi() = default; + + virtual ~StoreApi() = default; + + /** + * 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 *Required* + */ + Response< + String + > + deleteOrder( + + std::string orderId + + ); + /** + * Returns pet inventories by status. + * + * Returns a map of status codes to quantities + */ + Response< + String + > + getInventory( + ); + /** + * Find purchase order by ID. + * + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + * \param orderId ID of pet that needs to be fetched *Required* + */ + Response< + Order + > + getOrderById( + + long orderId + + ); + /** + * Place an order for a pet. + * + * + * \param order order placed for purchasing the pet *Required* + */ + Response< + Order + > + placeOrder( + + Order order + + ); +}; + +} + +#endif /* TINY_CPP_CLIENT_StoreApi_H_ */ \ No newline at end of file diff --git a/samples/client/petstore/tiny/cpp/lib/service/UserApi.cpp b/samples/client/petstore/tiny/cpp/lib/service/UserApi.cpp new file mode 100644 index 00000000000..d1cf12b80a9 --- /dev/null +++ b/samples/client/petstore/tiny/cpp/lib/service/UserApi.cpp @@ -0,0 +1,366 @@ +#include "UserApi.h" + +using namespace Tiny; + + + + Response< + String + > + UserApi:: + createUser( + + User user + + ) + { + std::string url = basepath + "/user"; // + // Query | + // Headers | + // Form | + // Body | user + + + begin(url); + + std::string payload = ""; + // Send Request + // METHOD | POST + http.addHeader("Content-Type", "application/json"); + + + + payload = user.toJson().dump(); + + int httpCode = http.sendRequest("POST", reinterpret_cast(&payload[0]), payload.length()); + + // Handle Request + String output = http.getString(); + std::string output_string = output.c_str(); + + http.end(); + + + Response response(output, httpCode); + return response; + } + + Response< + String + > + UserApi:: + createUsersWithArrayInput( + std::list user + + + ) + { + std::string url = basepath + "/user/createWithArray"; // + // Query | + // Headers | + // Form | + // Body | user + + + begin(url); + + std::string payload = ""; + // Send Request + // METHOD | POST + http.addHeader("Content-Type", "application/json"); + + + bourne::json tmp_arr = bourne::json::array(); + for(auto& var : user) + { + auto tmp = var.toJson(); + tmp_arr.append(tmp); + + } + payload = tmp_arr.dump(); + + + int httpCode = http.sendRequest("POST", reinterpret_cast(&payload[0]), payload.length()); + + // Handle Request + String output = http.getString(); + std::string output_string = output.c_str(); + + http.end(); + + + Response response(output, httpCode); + return response; + } + + Response< + String + > + UserApi:: + createUsersWithListInput( + std::list user + + + ) + { + std::string url = basepath + "/user/createWithList"; // + // Query | + // Headers | + // Form | + // Body | user + + + begin(url); + + std::string payload = ""; + // Send Request + // METHOD | POST + http.addHeader("Content-Type", "application/json"); + + + bourne::json tmp_arr = bourne::json::array(); + for(auto& var : user) + { + auto tmp = var.toJson(); + tmp_arr.append(tmp); + + } + payload = tmp_arr.dump(); + + + int httpCode = http.sendRequest("POST", reinterpret_cast(&payload[0]), payload.length()); + + // Handle Request + String output = http.getString(); + std::string output_string = output.c_str(); + + http.end(); + + + Response response(output, httpCode); + return response; + } + + Response< + String + > + UserApi:: + deleteUser( + + std::string username + + ) + { + std::string url = basepath + "/user/{username}"; //username + // Query | + // Headers | + // Form | + // Body | + + std::string s_username("{"); + s_username.append("username"); + s_username.append("}"); + + int pos = url.find(s_username); + + url.erase(pos, s_username.length()); + url.insert(pos, stringify(username)); + + begin(url); + + std::string payload = ""; + // Send Request + // METHOD | DELETE + int httpCode = http.sendRequest("DELETE", reinterpret_cast(&payload[0]), payload.length()); + + // Handle Request + String output = http.getString(); + std::string output_string = output.c_str(); + + http.end(); + + + Response response(output, httpCode); + return response; + } + + Response< + User + > + UserApi:: + getUserByName( + + std::string username + + ) + { + std::string url = basepath + "/user/{username}"; //username + // Query | + // Headers | + // Form | + // Body | + + std::string s_username("{"); + s_username.append("username"); + s_username.append("}"); + + int pos = url.find(s_username); + + url.erase(pos, s_username.length()); + url.insert(pos, stringify(username)); + + begin(url); + + std::string payload = ""; + // Send Request + // METHOD | GET + int httpCode = http.sendRequest("GET", reinterpret_cast(&payload[0]), payload.length()); + + // Handle Request + String output = http.getString(); + std::string output_string = output.c_str(); + + http.end(); + + + + + User obj(output_string); + + + Response response(obj, httpCode); + return response; + } + + Response< + std::string + > + UserApi:: + loginUser( + + std::string username + , + + std::string password + + ) + { + std::string url = basepath + "/user/login"; // + // Query | username password + // Headers | + // Form | + // Body | + + + begin(url); + + std::string payload = ""; + // Send Request + // METHOD | GET + int httpCode = http.sendRequest("GET", reinterpret_cast(&payload[0]), payload.length()); + + // Handle Request + String output = http.getString(); + std::string output_string = output.c_str(); + + http.end(); + + + + bourne::json jsonPayload(output_string); + std::string obj; + jsonToValue(&obj, jsonPayload, "std::string"); + + + + Response response(obj, httpCode); + return response; + } + + Response< + String + > + UserApi:: + logoutUser( + ) + { + std::string url = basepath + "/user/logout"; // + // Query | + // Headers | + // Form | + // Body | + + + begin(url); + + std::string payload = ""; + // Send Request + // METHOD | GET + int httpCode = http.sendRequest("GET", reinterpret_cast(&payload[0]), payload.length()); + + // Handle Request + String output = http.getString(); + std::string output_string = output.c_str(); + + http.end(); + + + Response response(output, httpCode); + return response; + } + + Response< + String + > + UserApi:: + updateUser( + + std::string username + , + + User user + + ) + { + std::string url = basepath + "/user/{username}"; //username + // Query | + // Headers | + // Form | + // Body | user + + std::string s_username("{"); + s_username.append("username"); + s_username.append("}"); + + int pos = url.find(s_username); + + url.erase(pos, s_username.length()); + url.insert(pos, stringify(username)); + + begin(url); + + std::string payload = ""; + // Send Request + // METHOD | PUT + http.addHeader("Content-Type", "application/json"); + + + + payload = user.toJson().dump(); + + int httpCode = http.sendRequest("PUT", reinterpret_cast(&payload[0]), payload.length()); + + // Handle Request + String output = http.getString(); + std::string output_string = output.c_str(); + + http.end(); + + + Response response(output, httpCode); + return response; + } + + + + diff --git a/samples/client/petstore/tiny/cpp/lib/service/UserApi.h b/samples/client/petstore/tiny/cpp/lib/service/UserApi.h new file mode 100644 index 00000000000..afdaefa0f8c --- /dev/null +++ b/samples/client/petstore/tiny/cpp/lib/service/UserApi.h @@ -0,0 +1,147 @@ +#ifndef TINY_CPP_CLIENT_UserApi_H_ +#define TINY_CPP_CLIENT_UserApi_H_ + + +#include "Response.h" +#include "Arduino.h" +#include "AbstractService.h" +#include "Helpers.h" +#include + +#include "User.h" +#include + +namespace Tiny { + +/** + * Class + * Generated with openapi::tiny-cpp-client + */ + +class UserApi : public AbstractService { +public: + UserApi() = default; + + virtual ~UserApi() = default; + + /** + * Create user. + * + * This can only be done by the logged in user. + * \param user Created user object *Required* + */ + Response< + String + > + createUser( + + User user + + ); + /** + * Creates list of users with given input array. + * + * + * \param user List of user object *Required* + */ + Response< + String + > + createUsersWithArrayInput( + std::list user + + + ); + /** + * Creates list of users with given input array. + * + * + * \param user List of user object *Required* + */ + Response< + String + > + createUsersWithListInput( + std::list user + + + ); + /** + * Delete user. + * + * This can only be done by the logged in user. + * \param username The name that needs to be deleted *Required* + */ + Response< + String + > + deleteUser( + + std::string username + + ); + /** + * Get user by user name. + * + * + * \param username The name that needs to be fetched. Use user1 for testing. *Required* + */ + Response< + User + > + getUserByName( + + std::string username + + ); + /** + * Logs user into the system. + * + * + * \param username The user name for login *Required* + * \param password The password for login in clear text *Required* + */ + Response< + std::string + > + loginUser( + + std::string username + , + + std::string password + + ); + /** + * Logs out current logged in user session. + * + * + */ + Response< + String + > + logoutUser( + ); + /** + * Updated user. + * + * This can only be done by the logged in user. + * \param username name that need to be deleted *Required* + * \param user Updated user object *Required* + */ + Response< + String + > + updateUser( + + std::string username + , + + User user + + ); +}; + +} + +#endif /* TINY_CPP_CLIENT_UserApi_H_ */ \ No newline at end of file diff --git a/samples/client/petstore/tiny/cpp/platformio.ini b/samples/client/petstore/tiny/cpp/platformio.ini new file mode 100644 index 00000000000..00781178d10 --- /dev/null +++ b/samples/client/petstore/tiny/cpp/platformio.ini @@ -0,0 +1,7 @@ +[env:esp32] +platform = espressif32 +board = nodemcu-32s +framework = arduino +lib_deps = https://github.com/steinwurf/bourne.git +extra_scripts = pre_compiling_bourne.py + diff --git a/samples/client/petstore/tiny/cpp/pre_compiling_bourne.py b/samples/client/petstore/tiny/cpp/pre_compiling_bourne.py new file mode 100644 index 00000000000..96356dcdf15 --- /dev/null +++ b/samples/client/petstore/tiny/cpp/pre_compiling_bourne.py @@ -0,0 +1,25 @@ +Import("env") + +## Compatibility for bourne to work on microcontrollers +# We insert '#define _GLIBCXX_USE_C99' in files that use std::stoll or std::to_string +def insert_c99_into(file): + import fileinput + + path = env['PROJECT_LIBDEPS_DIR'] + "/" + env['PIOENV'] + "/bourne/src/bourne/" + file + value = '#define _GLIBCXX_USE_C99 1\n' + + for line in fileinput.FileInput(path,inplace=1): + if line.startswith('#define _GLIBCXX_USE_C99'): + continue + elif line.startswith('// D'): + line=line.replace(line,line+value) + print(line, end='') + +def fix_parser(): + insert_c99_into('detail/parser.cpp') + +def fix_json(): + insert_c99_into('json.cpp') + +fix_parser() +fix_json() \ No newline at end of file diff --git a/samples/client/petstore/tiny/cpp/root.cert b/samples/client/petstore/tiny/cpp/root.cert new file mode 100644 index 00000000000..bad9c08efad --- /dev/null +++ b/samples/client/petstore/tiny/cpp/root.cert @@ -0,0 +1,53 @@ +// TODO: Provide your service root certificate. +// Below is two examples of root certificates. + +// Let's encrypt root certificate +/** +"-----BEGIN CERTIFICATE-----\n" \ +"MIIDrzCCApegAwIBAgIQCDvgVpBCRrGhdWrJWZHHSjANBgkqhkiG9w0BAQUFADBh\n" \ +"MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3\n" \ +"d3cuZGlnaWNlcnQuY29tMSAwHgYDVQQDExdEaWdpQ2VydCBHbG9iYWwgUm9vdCBD\n" \ +"QTAeFw0wNjExMTAwMDAwMDBaFw0zMTExMTAwMDAwMDBaMGExCzAJBgNVBAYTAlVT\n" \ +"MRUwEwYDVQQKEwxEaWdpQ2VydCBJbmMxGTAXBgNVBAsTEHd3dy5kaWdpY2VydC5j\n" \ +"b20xIDAeBgNVBAMTF0RpZ2lDZXJ0IEdsb2JhbCBSb290IENBMIIBIjANBgkqhkiG\n" \ +"9w0BAQEFAAOCAQ8AMIIBCgKCAQEA4jvhEXLeqKTTo1eqUKKPC3eQyaKl7hLOllsB\n" \ +"CSDMAZOnTjC3U/dDxGkAV53ijSLdhwZAAIEJzs4bg7/fzTtxRuLWZscFs3YnFo97\n" \ +"nh6Vfe63SKMI2tavegw5BmV/Sl0fvBf4q77uKNd0f3p4mVmFaG5cIzJLv07A6Fpt\n" \ +"43C/dxC//AH2hdmoRBBYMql1GNXRor5H4idq9Joz+EkIYIvUX7Q6hL+hqkpMfT7P\n" \ +"T19sdl6gSzeRntwi5m3OFBqOasv+zbMUZBfHWymeMr/y7vrTC0LUq7dBMtoM1O/4\n" \ +"gdW7jVg/tRvoSSiicNoxBN33shbyTApOB6jtSj1etX+jkMOvJwIDAQABo2MwYTAO\n" \ +"BgNVHQ8BAf8EBAMCAYYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUA95QNVbR\n" \ +"TLtm8KPiGxvDl7I90VUwHwYDVR0jBBgwFoAUA95QNVbRTLtm8KPiGxvDl7I90VUw\n" \ +"DQYJKoZIhvcNAQEFBQADggEBAMucN6pIExIK+t1EnE9SsPTfrgT1eXkIoyQY/Esr\n" \ +"hMAtudXH/vTBH1jLuG2cenTnmCmrEbXjcKChzUyImZOMkXDiqw8cvpOp/2PV5Adg\n" \ +"06O/nVsJ8dWO41P0jmP6P6fbtGbfYmbW0W5BjfIttep3Sp+dWOIrWcBAI+0tKIJF\n" \ +"PnlUkiaY4IBIqDfv8NZ5YBberOgOzW6sRBc4L0na4UU+Krk2U886UAb3LujEV0ls\n" \ +"YSEY1QSteDwsOoBrp+uvFRTp2InBuThs4pFsiv9kuXclVzDAGySj4dzp30d8tbQk\n" \ +"CAUw7C29C79Fv1C5qfPrmAESrciIxpg0X40KPMbp1ZWVbd4=\n" \ +"-----END CERTIFICATE-----\n" +*/ + +// Amazon_Root_CA_1.pem +/** +"-----BEGIN CERTIFICATE-----\n" \ +"MIIDQTCCAimgAwIBAgITBmyfz5m/jAo54vB4ikPmljZbyjANBgkqhkiG9w0BAQsF\n" \ +"ADA5MQswCQYDVQQGEwJVUzEPMA0GA1UEChMGQW1hem9uMRkwFwYDVQQDExBBbWF6\n" \ +"b24gUm9vdCBDQSAxMB4XDTE1MDUyNjAwMDAwMFoXDTM4MDExNzAwMDAwMFowOTEL\n" \ +"MAkGA1UEBhMCVVMxDzANBgNVBAoTBkFtYXpvbjEZMBcGA1UEAxMQQW1hem9uIFJv\n" \ +"b3QgQ0EgMTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALJ4gHHKeNXj\n" \ +"ca9HgFB0fW7Y14h29Jlo91ghYPl0hAEvrAIthtOgQ3pOsqTQNroBvo3bSMgHFzZM\n" \ +"9O6II8c+6zf1tRn4SWiw3te5djgdYZ6k/oI2peVKVuRF4fn9tBb6dNqcmzU5L/qw\n" \ +"IFAGbHrQgLKm+a/sRxmPUDgH3KKHOVj4utWp+UhnMJbulHheb4mjUcAwhmahRWa6\n" \ +"VOujw5H5SNz/0egwLX0tdHA114gk957EWW67c4cX8jJGKLhD+rcdqsq08p8kDi1L\n" \ +"93FcXmn/6pUCyziKrlA4b9v7LWIbxcceVOF34GfID5yHI9Y/QCB/IIDEgEw+OyQm\n" \ +"jgSubJrIqg0CAwEAAaNCMEAwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMC\n" \ +"AYYwHQYDVR0OBBYEFIQYzIU07LwMlJQuCFmcx7IQTgoIMA0GCSqGSIb3DQEBCwUA\n" \ +"A4IBAQCY8jdaQZChGsV2USggNiMOruYou6r4lK5IpDB/G/wkjUu0yKGX9rbxenDI\n" \ +"U5PMCCjjmCXPI6T53iHTfIUJrU6adTrCC2qJeHZERxhlbI1Bjjt/msv0tadQ1wUs\n" \ +"N+gDS63pYaACbvXy8MWy7Vu33PqUXHeeE6V/Uq2V8viTO96LXFvKWlJbYK8U90vv\n" \ +"o/ufQJVtMVT8QtPHRh8jrdkPSHCa2XV4cdFyQzR1bldZwgJcJmApzyMZFo6IQ6XU\n" \ +"5MsI+yMRQ+hDKXJioaldXgjUkK642M4UwtBV8ob2xJNDd2ZhwLnoQdeXeGADbkpy\n" \ +"rqXRfboQnoZsG4q5WTP468SQvvG5\n" \ +"-----END CERTIFICATE-----\n" \ +*/ + diff --git a/samples/client/petstore/tiny/cpp/src/main.cpp b/samples/client/petstore/tiny/cpp/src/main.cpp new file mode 100644 index 00000000000..34ba455fbdd --- /dev/null +++ b/samples/client/petstore/tiny/cpp/src/main.cpp @@ -0,0 +1,37 @@ +#include "PetApi.h" + +const char* ssid = "your wifi name"; // TODO Change wifi name +const char* password = "Your wifi password"; //TODO Change wifi password + + +void setup(){ + //Initialize serial and wait for port to open: + Serial.begin(9600); + delay(100); + + Serial.print("Attempting to connect to SSID: "); + Serial.println(ssid); + WiFi.begin(ssid, password); + + // attempt to connect to Wifi network: + while (WiFi.status() != WL_CONNECTED) { + Serial.print("."); + // wait 1 second for re-trying + delay(1000); + } + + Serial.print("Connected to "); + Serial.println(ssid); + + //Print LAN IP. + Serial.print("IP address set: "); + Serial.println(WiFi.localIP()); + + Tiny::PetApi petapi; + auto resp = petapi.getPetById(10); + Serial.println(resp.code); + Tiny::Pet pet = resp.obj; + Serial.println(pet.toJson().dump().c_str()); +} + +void loop(){} diff --git a/samples/client/petstore/tiny/cpp/test/RunTests.cpp b/samples/client/petstore/tiny/cpp/test/RunTests.cpp new file mode 100644 index 00000000000..4caafb4ee44 --- /dev/null +++ b/samples/client/petstore/tiny/cpp/test/RunTests.cpp @@ -0,0 +1,204 @@ + +#include "ApiResponseTest.cpp" + +#include "CategoryTest.cpp" + +#include "OrderTest.cpp" + +#include "PetTest.cpp" + +#include "TagTest.cpp" + +#include "UserTest.cpp" + + + +void setUp(){} + +void tearDown(){} + +void runTests(){ + + + RUN_TEST(test_ApiResponse_code_is_assigned_from_json); + + + RUN_TEST(test_ApiResponse_type_is_assigned_from_json); + + + RUN_TEST(test_ApiResponse_message_is_assigned_from_json); + + + + RUN_TEST(test_Category_id_is_assigned_from_json); + + + RUN_TEST(test_Category_name_is_assigned_from_json); + + + + RUN_TEST(test_Order_id_is_assigned_from_json); + + + RUN_TEST(test_Order_petId_is_assigned_from_json); + + + RUN_TEST(test_Order_quantity_is_assigned_from_json); + + + RUN_TEST(test_Order_shipDate_is_assigned_from_json); + + + RUN_TEST(test_Order_status_is_assigned_from_json); + + + RUN_TEST(test_Order_complete_is_assigned_from_json); + + + + RUN_TEST(test_Pet_id_is_assigned_from_json); + + + + RUN_TEST(test_Pet_name_is_assigned_from_json); + + + + + RUN_TEST(test_Pet_status_is_assigned_from_json); + + + + RUN_TEST(test_Tag_id_is_assigned_from_json); + + + RUN_TEST(test_Tag_name_is_assigned_from_json); + + + + RUN_TEST(test_User_id_is_assigned_from_json); + + + RUN_TEST(test_User_username_is_assigned_from_json); + + + RUN_TEST(test_User_firstName_is_assigned_from_json); + + + RUN_TEST(test_User_lastName_is_assigned_from_json); + + + RUN_TEST(test_User_email_is_assigned_from_json); + + + RUN_TEST(test_User_password_is_assigned_from_json); + + + RUN_TEST(test_User_phone_is_assigned_from_json); + + + RUN_TEST(test_User_userStatus_is_assigned_from_json); + + + + + + RUN_TEST(test_ApiResponse_code_is_converted_to_json); + + + RUN_TEST(test_ApiResponse_type_is_converted_to_json); + + + RUN_TEST(test_ApiResponse_message_is_converted_to_json); + + + + RUN_TEST(test_Category_id_is_converted_to_json); + + + RUN_TEST(test_Category_name_is_converted_to_json); + + + + RUN_TEST(test_Order_id_is_converted_to_json); + + + RUN_TEST(test_Order_petId_is_converted_to_json); + + + RUN_TEST(test_Order_quantity_is_converted_to_json); + + + RUN_TEST(test_Order_shipDate_is_converted_to_json); + + + RUN_TEST(test_Order_status_is_converted_to_json); + + + RUN_TEST(test_Order_complete_is_converted_to_json); + + + + RUN_TEST(test_Pet_id_is_converted_to_json); + + + + RUN_TEST(test_Pet_name_is_converted_to_json); + + + + + RUN_TEST(test_Pet_status_is_converted_to_json); + + + + RUN_TEST(test_Tag_id_is_converted_to_json); + + + RUN_TEST(test_Tag_name_is_converted_to_json); + + + + RUN_TEST(test_User_id_is_converted_to_json); + + + RUN_TEST(test_User_username_is_converted_to_json); + + + RUN_TEST(test_User_firstName_is_converted_to_json); + + + RUN_TEST(test_User_lastName_is_converted_to_json); + + + RUN_TEST(test_User_email_is_converted_to_json); + + + RUN_TEST(test_User_password_is_converted_to_json); + + + RUN_TEST(test_User_phone_is_converted_to_json); + + + RUN_TEST(test_User_userStatus_is_converted_to_json); + + + + +} + +int main(void) { + UNITY_BEGIN(); + runTests(); + return UNITY_END(); +} + +void setup() { + UNITY_BEGIN(); + runTests(); + UNITY_END(); +} + +void loop() { + +} diff --git a/samples/client/petstore/typescript-angular-v10-provided-in-root/builds/default/.openapi-generator/VERSION b/samples/client/petstore/typescript-angular-v10-provided-in-root/builds/default/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/client/petstore/typescript-angular-v10-provided-in-root/builds/default/.openapi-generator/VERSION +++ b/samples/client/petstore/typescript-angular-v10-provided-in-root/builds/default/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/client/petstore/typescript-angular-v10-provided-in-root/builds/with-npm/.openapi-generator/VERSION b/samples/client/petstore/typescript-angular-v10-provided-in-root/builds/with-npm/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/client/petstore/typescript-angular-v10-provided-in-root/builds/with-npm/.openapi-generator/VERSION +++ b/samples/client/petstore/typescript-angular-v10-provided-in-root/builds/with-npm/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/client/petstore/typescript-angular-v11-oneOf/builds/default/.gitignore b/samples/client/petstore/typescript-angular-v11-oneOf/builds/default/.gitignore new file mode 100644 index 00000000000..149b5765472 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v11-oneOf/builds/default/.gitignore @@ -0,0 +1,4 @@ +wwwroot/*.js +node_modules +typings +dist diff --git a/samples/client/petstore/typescript-angular-v11-oneOf/builds/default/.openapi-generator-ignore b/samples/client/petstore/typescript-angular-v11-oneOf/builds/default/.openapi-generator-ignore new file mode 100644 index 00000000000..7484ee590a3 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v11-oneOf/builds/default/.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/typescript-angular-v11-oneOf/builds/default/.openapi-generator/FILES b/samples/client/petstore/typescript-angular-v11-oneOf/builds/default/.openapi-generator/FILES new file mode 100644 index 00000000000..e646d434eee --- /dev/null +++ b/samples/client/petstore/typescript-angular-v11-oneOf/builds/default/.openapi-generator/FILES @@ -0,0 +1,14 @@ +.gitignore +README.md +api.module.ts +api/api.ts +api/default.service.ts +configuration.ts +encoder.ts +git_push.sh +index.ts +model/apple.ts +model/fruit.ts +model/grape.ts +model/models.ts +variables.ts diff --git a/samples/client/petstore/typescript-angular-v11-oneOf/builds/default/.openapi-generator/VERSION b/samples/client/petstore/typescript-angular-v11-oneOf/builds/default/.openapi-generator/VERSION new file mode 100644 index 00000000000..4b448de535c --- /dev/null +++ b/samples/client/petstore/typescript-angular-v11-oneOf/builds/default/.openapi-generator/VERSION @@ -0,0 +1 @@ +5.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/typescript-angular-v11-oneOf/builds/default/README.md b/samples/client/petstore/typescript-angular-v11-oneOf/builds/default/README.md new file mode 100644 index 00000000000..f16604dcfff --- /dev/null +++ b/samples/client/petstore/typescript-angular-v11-oneOf/builds/default/README.md @@ -0,0 +1,203 @@ +## @ + +### Building + +To install the required dependencies and to build the typescript sources run: +``` +npm install +npm run build +``` + +### publishing + +First build the package then run ```npm publish dist``` (don't forget to specify the `dist` folder!) + +### consuming + +Navigate to the folder of your consuming project and run one of next commands. + +_published:_ + +``` +npm install @ --save +``` + +_without publishing (not recommended):_ + +``` +npm install PATH_TO_GENERATED_PACKAGE/dist.tgz --save +``` + +_It's important to take the tgz file, otherwise you'll get trouble with links on windows_ + +_using `npm link`:_ + +In PATH_TO_GENERATED_PACKAGE/dist: +``` +npm link +``` + +In your project: +``` +npm link +``` + +__Note for Windows users:__ The Angular CLI has troubles to use linked npm packages. +Please refer to this issue https://github.com/angular/angular-cli/issues/8284 for a solution / workaround. +Published packages are not effected by this issue. + + +#### General usage + +In your Angular project: + + +``` +// without configuring providers +import { ApiModule } from ''; +import { HttpClientModule } from '@angular/common/http'; + +@NgModule({ + imports: [ + ApiModule, + // make sure to import the HttpClientModule in the AppModule only, + // see https://github.com/angular/angular/issues/20575 + HttpClientModule + ], + declarations: [ AppComponent ], + providers: [], + bootstrap: [ AppComponent ] +}) +export class AppModule {} +``` + +``` +// configuring providers +import { ApiModule, Configuration, ConfigurationParameters } from ''; + +export function apiConfigFactory (): Configuration { + const params: ConfigurationParameters = { + // set configuration parameters here. + } + return new Configuration(params); +} + +@NgModule({ + imports: [ ApiModule.forRoot(apiConfigFactory) ], + declarations: [ AppComponent ], + providers: [], + bootstrap: [ AppComponent ] +}) +export class AppModule {} +``` + +``` +// configuring providers with an authentication service that manages your access tokens +import { ApiModule, Configuration } from ''; + +@NgModule({ + imports: [ ApiModule ], + declarations: [ AppComponent ], + providers: [ + { + provide: Configuration, + useFactory: (authService: AuthService) => new Configuration( + { + basePath: environment.apiUrl, + accessToken: authService.getAccessToken.bind(authService) + } + ), + deps: [AuthService], + multi: false + } + ], + bootstrap: [ AppComponent ] +}) +export class AppModule {} +``` + +``` +import { DefaultApi } from ''; + +export class AppComponent { + constructor(private apiGateway: DefaultApi) { } +} +``` + +Note: The ApiModule is restricted to being instantiated once app wide. +This is to ensure that all services are treated as singletons. + +#### Using multiple OpenAPI files / APIs / ApiModules +In order to use multiple `ApiModules` generated from different OpenAPI files, +you can create an alias name when importing the modules +in order to avoid naming conflicts: +``` +import { ApiModule } from 'my-api-path'; +import { ApiModule as OtherApiModule } from 'my-other-api-path'; +import { HttpClientModule } from '@angular/common/http'; + +@NgModule({ + imports: [ + ApiModule, + OtherApiModule, + // make sure to import the HttpClientModule in the AppModule only, + // see https://github.com/angular/angular/issues/20575 + HttpClientModule + ] +}) +export class AppModule { + +} +``` + + +### Set service base path +If different than the generated base path, during app bootstrap, you can provide the base path to your service. + +``` +import { BASE_PATH } from ''; + +bootstrap(AppComponent, [ + { provide: BASE_PATH, useValue: 'https://your-web-service.com' }, +]); +``` +or + +``` +import { BASE_PATH } from ''; + +@NgModule({ + imports: [], + declarations: [ AppComponent ], + providers: [ provide: BASE_PATH, useValue: 'https://your-web-service.com' ], + bootstrap: [ AppComponent ] +}) +export class AppModule {} +``` + + +#### Using @angular/cli +First extend your `src/environments/*.ts` files by adding the corresponding base path: + +``` +export const environment = { + production: false, + API_BASE_PATH: 'http://127.0.0.1:8080' +}; +``` + +In the src/app/app.module.ts: +``` +import { BASE_PATH } from ''; +import { environment } from '../environments/environment'; + +@NgModule({ + declarations: [ + AppComponent + ], + imports: [ ], + providers: [{ provide: BASE_PATH, useValue: environment.API_BASE_PATH }], + bootstrap: [ AppComponent ] +}) +export class AppModule { } +``` diff --git a/samples/client/petstore/typescript-angular-v11-oneOf/builds/default/api.module.ts b/samples/client/petstore/typescript-angular-v11-oneOf/builds/default/api.module.ts new file mode 100644 index 00000000000..6eca9cc5418 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v11-oneOf/builds/default/api.module.ts @@ -0,0 +1,31 @@ +import { NgModule, ModuleWithProviders, SkipSelf, Optional } from '@angular/core'; +import { Configuration } from './configuration'; +import { HttpClient } from '@angular/common/http'; + +import { DefaultService } from './api/default.service'; + +@NgModule({ + imports: [], + declarations: [], + exports: [], + providers: [] +}) +export class ApiModule { + public static forRoot(configurationFactory: () => Configuration): ModuleWithProviders { + return { + ngModule: ApiModule, + providers: [ { provide: Configuration, useFactory: configurationFactory } ] + }; + } + + constructor( @Optional() @SkipSelf() parentModule: ApiModule, + @Optional() http: HttpClient) { + if (parentModule) { + throw new Error('ApiModule is already loaded. Import in your base AppModule only.'); + } + if (!http) { + throw new Error('You need to import the HttpClientModule in your AppModule! \n' + + 'See also https://github.com/angular/angular/issues/20575'); + } + } +} diff --git a/samples/client/petstore/typescript-angular-v11-oneOf/builds/default/api/api.ts b/samples/client/petstore/typescript-angular-v11-oneOf/builds/default/api/api.ts new file mode 100644 index 00000000000..8e76619647f --- /dev/null +++ b/samples/client/petstore/typescript-angular-v11-oneOf/builds/default/api/api.ts @@ -0,0 +1,3 @@ +export * from './default.service'; +import { DefaultService } from './default.service'; +export const APIS = [DefaultService]; diff --git a/samples/client/petstore/typescript-angular-v11-oneOf/builds/default/api/default.service.ts b/samples/client/petstore/typescript-angular-v11-oneOf/builds/default/api/default.service.ts new file mode 100644 index 00000000000..a008d370d56 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v11-oneOf/builds/default/api/default.service.ts @@ -0,0 +1,127 @@ +/** + * fruity + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: 0.0.1 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +/* tslint:disable:no-unused-variable member-ordering */ + +import { Inject, Injectable, Optional } from '@angular/core'; +import { HttpClient, HttpHeaders, HttpParams, + HttpResponse, HttpEvent, HttpParameterCodec } from '@angular/common/http'; +import { CustomHttpParameterCodec } from '../encoder'; +import { Observable } from 'rxjs'; + +import { Fruit } from '../model/models'; + +import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; +import { Configuration } from '../configuration'; + + + +@Injectable({ + providedIn: 'root' +}) +export class DefaultService { + + protected basePath = 'http://localhost'; + public defaultHeaders = new HttpHeaders(); + public configuration = new Configuration(); + public encoder: HttpParameterCodec; + + constructor(protected httpClient: HttpClient, @Optional()@Inject(BASE_PATH) basePath: string, @Optional() configuration: Configuration) { + if (configuration) { + this.configuration = configuration; + } + if (typeof this.configuration.basePath !== 'string') { + if (typeof basePath !== 'string') { + basePath = this.basePath; + } + this.configuration.basePath = basePath; + } + this.encoder = this.configuration.encoder || new CustomHttpParameterCodec(); + } + + + private addToHttpParams(httpParams: HttpParams, value: any, key?: string): HttpParams { + if (typeof value === "object" && value instanceof Date === false) { + httpParams = this.addToHttpParamsRecursive(httpParams, value); + } else { + httpParams = this.addToHttpParamsRecursive(httpParams, value, key); + } + return httpParams; + } + + private addToHttpParamsRecursive(httpParams: HttpParams, value?: any, key?: string): HttpParams { + if (value == null) { + return httpParams; + } + + if (typeof value === "object") { + if (Array.isArray(value)) { + (value as any[]).forEach( elem => httpParams = this.addToHttpParamsRecursive(httpParams, elem, key)); + } else if (value instanceof Date) { + if (key != null) { + httpParams = httpParams.append(key, + (value as Date).toISOString().substr(0, 10)); + } else { + throw Error("key may not be null if value is Date"); + } + } else { + Object.keys(value).forEach( k => httpParams = this.addToHttpParamsRecursive( + httpParams, value[k], key != null ? `${key}.${k}` : k)); + } + } else if (key != null) { + httpParams = httpParams.append(key, value); + } else { + throw Error("key may not be null if value is not object or array"); + } + return httpParams; + } + + /** + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public rootGet(observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable; + public rootGet(observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable>; + public rootGet(observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable>; + public rootGet(observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json'}): Observable { + + let headers = this.defaultHeaders; + + let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (httpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/json' + ]; + httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (httpHeaderAcceptSelected !== undefined) { + headers = headers.set('Accept', httpHeaderAcceptSelected); + } + + + let responseType_: 'text' | 'json' = 'json'; + if(httpHeaderAcceptSelected && httpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } + + return this.httpClient.get(`${this.configuration.basePath}/`, + { + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: headers, + observe: observe, + reportProgress: reportProgress + } + ); + } + +} diff --git a/samples/client/petstore/typescript-angular-v11-oneOf/builds/default/configuration.ts b/samples/client/petstore/typescript-angular-v11-oneOf/builds/default/configuration.ts new file mode 100644 index 00000000000..4ca3546927f --- /dev/null +++ b/samples/client/petstore/typescript-angular-v11-oneOf/builds/default/configuration.ts @@ -0,0 +1,121 @@ +import { HttpParameterCodec } from '@angular/common/http'; + +export interface ConfigurationParameters { + /** + * @deprecated Since 5.0. Use credentials instead + */ + apiKeys?: {[ key: string ]: string}; + username?: string; + password?: string; + /** + * @deprecated Since 5.0. Use credentials instead + */ + accessToken?: string | (() => string); + basePath?: string; + withCredentials?: boolean; + encoder?: HttpParameterCodec; + /** + * The keys are the names in the securitySchemes section of the OpenAPI + * document. They should map to the value used for authentication + * minus any standard prefixes such as 'Basic' or 'Bearer'. + */ + credentials?: {[ key: string ]: string | (() => string | undefined)}; +} + +export class Configuration { + /** + * @deprecated Since 5.0. Use credentials instead + */ + apiKeys?: {[ key: string ]: string}; + username?: string; + password?: string; + /** + * @deprecated Since 5.0. Use credentials instead + */ + accessToken?: string | (() => string); + basePath?: string; + withCredentials?: boolean; + encoder?: HttpParameterCodec; + /** + * The keys are the names in the securitySchemes section of the OpenAPI + * document. They should map to the value used for authentication + * minus any standard prefixes such as 'Basic' or 'Bearer'. + */ + credentials: {[ key: string ]: string | (() => string | undefined)}; + + constructor(configurationParameters: ConfigurationParameters = {}) { + this.apiKeys = configurationParameters.apiKeys; + this.username = configurationParameters.username; + this.password = configurationParameters.password; + this.accessToken = configurationParameters.accessToken; + this.basePath = configurationParameters.basePath; + this.withCredentials = configurationParameters.withCredentials; + this.encoder = configurationParameters.encoder; + if (configurationParameters.credentials) { + this.credentials = configurationParameters.credentials; + } + else { + this.credentials = {}; + } + } + + /** + * Select the correct content-type to use for a request. + * Uses {@link Configuration#isJsonMime} to determine the correct content-type. + * If no content type is found return the first found type if the contentTypes is not empty + * @param contentTypes - the array of content types that are available for selection + * @returns the selected content-type or undefined if no selection could be made. + */ + public selectHeaderContentType (contentTypes: string[]): string | undefined { + if (contentTypes.length === 0) { + return undefined; + } + + const type = contentTypes.find((x: string) => this.isJsonMime(x)); + if (type === undefined) { + return contentTypes[0]; + } + return type; + } + + /** + * Select the correct accept content-type to use for a request. + * Uses {@link Configuration#isJsonMime} to determine the correct accept content-type. + * If no content type is found return the first found type if the contentTypes is not empty + * @param accepts - the array of content types that are available for selection. + * @returns the selected content-type or undefined if no selection could be made. + */ + public selectHeaderAccept(accepts: string[]): string | undefined { + if (accepts.length === 0) { + return undefined; + } + + const type = accepts.find((x: string) => this.isJsonMime(x)); + if (type === undefined) { + return accepts[0]; + } + return type; + } + + /** + * 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'); + } + + public lookupCredential(key: string): string | undefined { + const value = this.credentials[key]; + return typeof value === 'function' + ? value() + : value; + } +} diff --git a/samples/client/petstore/typescript-angular-v11-oneOf/builds/default/encoder.ts b/samples/client/petstore/typescript-angular-v11-oneOf/builds/default/encoder.ts new file mode 100644 index 00000000000..138c4d5cf2c --- /dev/null +++ b/samples/client/petstore/typescript-angular-v11-oneOf/builds/default/encoder.ts @@ -0,0 +1,20 @@ +import { HttpParameterCodec } from '@angular/common/http'; + +/** + * Custom HttpParameterCodec + * Workaround for https://github.com/angular/angular/issues/18261 + */ +export class CustomHttpParameterCodec implements HttpParameterCodec { + encodeKey(k: string): string { + return encodeURIComponent(k); + } + encodeValue(v: string): string { + return encodeURIComponent(v); + } + decodeKey(k: string): string { + return decodeURIComponent(k); + } + decodeValue(v: string): string { + return decodeURIComponent(v); + } +} diff --git a/samples/client/petstore/typescript-angular-v11-oneOf/builds/default/git_push.sh b/samples/client/petstore/typescript-angular-v11-oneOf/builds/default/git_push.sh new file mode 100644 index 00000000000..ced3be2b0c7 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v11-oneOf/builds/default/git_push.sh @@ -0,0 +1,58 @@ +#!/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-pestore-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/typescript-angular-v11-oneOf/builds/default/index.ts b/samples/client/petstore/typescript-angular-v11-oneOf/builds/default/index.ts new file mode 100644 index 00000000000..c312b70fa3e --- /dev/null +++ b/samples/client/petstore/typescript-angular-v11-oneOf/builds/default/index.ts @@ -0,0 +1,5 @@ +export * from './api/api'; +export * from './model/models'; +export * from './variables'; +export * from './configuration'; +export * from './api.module'; \ No newline at end of file diff --git a/samples/client/petstore/typescript-angular-v11-oneOf/builds/default/model/apple.ts b/samples/client/petstore/typescript-angular-v11-oneOf/builds/default/model/apple.ts new file mode 100644 index 00000000000..ced6d899e32 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v11-oneOf/builds/default/model/apple.ts @@ -0,0 +1,17 @@ +/** + * fruity + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: 0.0.1 + * + * + * 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 Apple { + kind?: string; +} + diff --git a/samples/client/petstore/typescript-angular-v11-oneOf/builds/default/model/banana.ts b/samples/client/petstore/typescript-angular-v11-oneOf/builds/default/model/banana.ts new file mode 100644 index 00000000000..bf67fa8256d --- /dev/null +++ b/samples/client/petstore/typescript-angular-v11-oneOf/builds/default/model/banana.ts @@ -0,0 +1,17 @@ +/** + * fruity + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: 0.0.1 + * + * + * 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 Banana { + count?: number; +} + diff --git a/samples/client/petstore/typescript-angular-v11-oneOf/builds/default/model/fruit.ts b/samples/client/petstore/typescript-angular-v11-oneOf/builds/default/model/fruit.ts new file mode 100644 index 00000000000..c7131e502f0 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v11-oneOf/builds/default/model/fruit.ts @@ -0,0 +1,21 @@ +/** + * fruity + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: 0.0.1 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +import { Apple } from './apple'; +import { Grape } from './grape'; + + +/** + * @type Fruit + * @export + */ +export type Fruit = Array | { [key: string]: Apple; }; + diff --git a/samples/client/petstore/typescript-angular-v11-oneOf/builds/default/model/grape.ts b/samples/client/petstore/typescript-angular-v11-oneOf/builds/default/model/grape.ts new file mode 100644 index 00000000000..0dc06634c30 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v11-oneOf/builds/default/model/grape.ts @@ -0,0 +1,17 @@ +/** + * fruity + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: 0.0.1 + * + * + * 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 Grape { + color?: string; +} + diff --git a/samples/client/petstore/typescript-angular-v11-oneOf/builds/default/model/models.ts b/samples/client/petstore/typescript-angular-v11-oneOf/builds/default/model/models.ts new file mode 100644 index 00000000000..ca547da2ee3 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v11-oneOf/builds/default/model/models.ts @@ -0,0 +1,3 @@ +export * from './apple'; +export * from './fruit'; +export * from './grape'; diff --git a/samples/client/petstore/typescript-angular-v11-oneOf/builds/default/variables.ts b/samples/client/petstore/typescript-angular-v11-oneOf/builds/default/variables.ts new file mode 100644 index 00000000000..6fe58549f39 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v11-oneOf/builds/default/variables.ts @@ -0,0 +1,9 @@ +import { InjectionToken } from '@angular/core'; + +export const BASE_PATH = new InjectionToken('basePath'); +export const COLLECTION_FORMATS = { + 'csv': ',', + 'tsv': ' ', + 'ssv': ' ', + 'pipes': '|' +} diff --git a/samples/client/petstore/typescript-angular-v11-provided-in-root/builds/default/.openapi-generator/VERSION b/samples/client/petstore/typescript-angular-v11-provided-in-root/builds/default/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/client/petstore/typescript-angular-v11-provided-in-root/builds/default/.openapi-generator/VERSION +++ b/samples/client/petstore/typescript-angular-v11-provided-in-root/builds/default/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/client/petstore/typescript-angular-v11-provided-in-root/builds/with-npm/.openapi-generator/VERSION b/samples/client/petstore/typescript-angular-v11-provided-in-root/builds/with-npm/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/client/petstore/typescript-angular-v11-provided-in-root/builds/with-npm/.openapi-generator/VERSION +++ b/samples/client/petstore/typescript-angular-v11-provided-in-root/builds/with-npm/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/client/petstore/typescript-angular-v6-not-provided-in-root/builds/default/.openapi-generator/VERSION b/samples/client/petstore/typescript-angular-v6-not-provided-in-root/builds/default/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/client/petstore/typescript-angular-v6-not-provided-in-root/builds/default/.openapi-generator/VERSION +++ b/samples/client/petstore/typescript-angular-v6-not-provided-in-root/builds/default/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/client/petstore/typescript-angular-v6-not-provided-in-root/builds/with-npm/.openapi-generator/VERSION b/samples/client/petstore/typescript-angular-v6-not-provided-in-root/builds/with-npm/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/client/petstore/typescript-angular-v6-not-provided-in-root/builds/with-npm/.openapi-generator/VERSION +++ b/samples/client/petstore/typescript-angular-v6-not-provided-in-root/builds/with-npm/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/client/petstore/typescript-angular-v6-provided-in-root/builds/default/.openapi-generator/VERSION b/samples/client/petstore/typescript-angular-v6-provided-in-root/builds/default/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/client/petstore/typescript-angular-v6-provided-in-root/builds/default/.openapi-generator/VERSION +++ b/samples/client/petstore/typescript-angular-v6-provided-in-root/builds/default/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/client/petstore/typescript-angular-v6-provided-in-root/builds/with-npm/.openapi-generator/VERSION b/samples/client/petstore/typescript-angular-v6-provided-in-root/builds/with-npm/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/client/petstore/typescript-angular-v6-provided-in-root/builds/with-npm/.openapi-generator/VERSION +++ b/samples/client/petstore/typescript-angular-v6-provided-in-root/builds/with-npm/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/client/petstore/typescript-angular-v7-not-provided-in-root/builds/default/.openapi-generator/VERSION b/samples/client/petstore/typescript-angular-v7-not-provided-in-root/builds/default/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/client/petstore/typescript-angular-v7-not-provided-in-root/builds/default/.openapi-generator/VERSION +++ b/samples/client/petstore/typescript-angular-v7-not-provided-in-root/builds/default/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/client/petstore/typescript-angular-v7-not-provided-in-root/builds/with-npm/.openapi-generator/VERSION b/samples/client/petstore/typescript-angular-v7-not-provided-in-root/builds/with-npm/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/client/petstore/typescript-angular-v7-not-provided-in-root/builds/with-npm/.openapi-generator/VERSION +++ b/samples/client/petstore/typescript-angular-v7-not-provided-in-root/builds/with-npm/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/client/petstore/typescript-angular-v7-provided-in-root/builds/default/.openapi-generator/VERSION b/samples/client/petstore/typescript-angular-v7-provided-in-root/builds/default/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/client/petstore/typescript-angular-v7-provided-in-root/builds/default/.openapi-generator/VERSION +++ b/samples/client/petstore/typescript-angular-v7-provided-in-root/builds/default/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/client/petstore/typescript-angular-v7-provided-in-root/builds/with-npm/.openapi-generator/VERSION b/samples/client/petstore/typescript-angular-v7-provided-in-root/builds/with-npm/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/client/petstore/typescript-angular-v7-provided-in-root/builds/with-npm/.openapi-generator/VERSION +++ b/samples/client/petstore/typescript-angular-v7-provided-in-root/builds/with-npm/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/client/petstore/typescript-angular-v8-provided-in-root/builds/single-request-parameter/.openapi-generator/VERSION b/samples/client/petstore/typescript-angular-v8-provided-in-root/builds/single-request-parameter/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/client/petstore/typescript-angular-v8-provided-in-root/builds/single-request-parameter/.openapi-generator/VERSION +++ b/samples/client/petstore/typescript-angular-v8-provided-in-root/builds/single-request-parameter/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/client/petstore/typescript-angular-v8-provided-in-root/builds/with-npm/.openapi-generator/VERSION b/samples/client/petstore/typescript-angular-v8-provided-in-root/builds/with-npm/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/client/petstore/typescript-angular-v8-provided-in-root/builds/with-npm/.openapi-generator/VERSION +++ b/samples/client/petstore/typescript-angular-v8-provided-in-root/builds/with-npm/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/client/petstore/typescript-angular-v8-provided-in-root/builds/with-prefixed-module-name/.openapi-generator/VERSION b/samples/client/petstore/typescript-angular-v8-provided-in-root/builds/with-prefixed-module-name/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/client/petstore/typescript-angular-v8-provided-in-root/builds/with-prefixed-module-name/.openapi-generator/VERSION +++ b/samples/client/petstore/typescript-angular-v8-provided-in-root/builds/with-prefixed-module-name/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/client/petstore/typescript-angular-v9-provided-in-any/builds/default/.openapi-generator/VERSION b/samples/client/petstore/typescript-angular-v9-provided-in-any/builds/default/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/client/petstore/typescript-angular-v9-provided-in-any/builds/default/.openapi-generator/VERSION +++ b/samples/client/petstore/typescript-angular-v9-provided-in-any/builds/default/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/client/petstore/typescript-angular-v9-provided-in-root/builds/default/.openapi-generator/VERSION b/samples/client/petstore/typescript-angular-v9-provided-in-root/builds/default/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/client/petstore/typescript-angular-v9-provided-in-root/builds/default/.openapi-generator/VERSION +++ b/samples/client/petstore/typescript-angular-v9-provided-in-root/builds/default/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/client/petstore/typescript-angular-v9-provided-in-root/builds/with-npm/.openapi-generator/VERSION b/samples/client/petstore/typescript-angular-v9-provided-in-root/builds/with-npm/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/client/petstore/typescript-angular-v9-provided-in-root/builds/with-npm/.openapi-generator/VERSION +++ b/samples/client/petstore/typescript-angular-v9-provided-in-root/builds/with-npm/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/client/petstore/typescript-aurelia/default/.openapi-generator/VERSION b/samples/client/petstore/typescript-aurelia/default/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/client/petstore/typescript-aurelia/default/.openapi-generator/VERSION +++ b/samples/client/petstore/typescript-aurelia/default/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x 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 5f68295fc19..e8415097f3a 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,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x 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 5f68295fc19..e8415097f3a 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,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/client/petstore/typescript-axios/builds/default/api.ts b/samples/client/petstore/typescript-axios/builds/default/api.ts index 856fb0a4829..0ce81cf1174 100644 --- a/samples/client/petstore/typescript-axios/builds/default/api.ts +++ b/samples/client/petstore/typescript-axios/builds/default/api.ts @@ -383,6 +383,7 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) * @summary Finds Pets by tags * @param {Array} tags Tags to filter by * @param {*} [options] Override http request option. + * @deprecated * @throws {RequiredError} */ findPetsByTags: async (tags: Array, options: any = {}): Promise => { @@ -649,6 +650,7 @@ export const PetApiFp = function(configuration?: Configuration) { * @summary Finds Pets by tags * @param {Array} tags Tags to filter by * @param {*} [options] Override http request option. + * @deprecated * @throws {RequiredError} */ async findPetsByTags(tags: Array, options?: any): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise>> { @@ -749,6 +751,7 @@ export const PetApiFactory = function (configuration?: Configuration, basePath?: * @summary Finds Pets by tags * @param {Array} tags Tags to filter by * @param {*} [options] Override http request option. + * @deprecated * @throws {RequiredError} */ findPetsByTags(tags: Array, options?: any): AxiosPromise> { @@ -850,6 +853,7 @@ export class PetApi extends BaseAPI { * @summary Finds Pets by tags * @param {Array} tags Tags to filter by * @param {*} [options] Override http request option. + * @deprecated * @throws {RequiredError} * @memberof PetApi */ 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 5f68295fc19..e8415097f3a 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,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x 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 856fb0a4829..0ce81cf1174 100644 --- a/samples/client/petstore/typescript-axios/builds/es6-target/api.ts +++ b/samples/client/petstore/typescript-axios/builds/es6-target/api.ts @@ -383,6 +383,7 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) * @summary Finds Pets by tags * @param {Array} tags Tags to filter by * @param {*} [options] Override http request option. + * @deprecated * @throws {RequiredError} */ findPetsByTags: async (tags: Array, options: any = {}): Promise => { @@ -649,6 +650,7 @@ export const PetApiFp = function(configuration?: Configuration) { * @summary Finds Pets by tags * @param {Array} tags Tags to filter by * @param {*} [options] Override http request option. + * @deprecated * @throws {RequiredError} */ async findPetsByTags(tags: Array, options?: any): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise>> { @@ -749,6 +751,7 @@ export const PetApiFactory = function (configuration?: Configuration, basePath?: * @summary Finds Pets by tags * @param {Array} tags Tags to filter by * @param {*} [options] Override http request option. + * @deprecated * @throws {RequiredError} */ findPetsByTags(tags: Array, options?: any): AxiosPromise> { @@ -850,6 +853,7 @@ export class PetApi extends BaseAPI { * @summary Finds Pets by tags * @param {Array} tags Tags to filter by * @param {*} [options] Override http request option. + * @deprecated * @throws {RequiredError} * @memberof PetApi */ 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 5f68295fc19..e8415097f3a 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,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x 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 85c32a979e2..15fa56e5e78 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 @@ -394,6 +394,7 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) * @summary Finds Pets by tags * @param {Array} tags Tags to filter by * @param {*} [options] Override http request option. + * @deprecated * @throws {RequiredError} */ findPetsByTags: async (tags: Array, options: any = {}): Promise => { @@ -662,6 +663,7 @@ export const PetApiFp = function(configuration?: Configuration) { * @summary Finds Pets by tags * @param {Array} tags Tags to filter by * @param {*} [options] Override http request option. + * @deprecated * @throws {RequiredError} */ async findPetsByTags(tags: Array, options?: any): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise>> { @@ -764,6 +766,7 @@ export const PetApiFactory = function (configuration?: Configuration, basePath?: * @summary Finds Pets by tags * @param {Array} tags Tags to filter by * @param {*} [options] Override http request option. + * @deprecated * @throws {RequiredError} */ findPetsByTags(tags: Array, options?: any): AxiosPromise> { @@ -867,6 +870,7 @@ export class PetApi extends BaseAPI { * @summary Finds Pets by tags * @param {Array} tags Tags to filter by * @param {*} [options] Override http request option. + * @deprecated * @throws {RequiredError} * @memberof PetApi */ 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 5f68295fc19..e8415097f3a 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,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x 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 832e63b1f4e..afcfb41b258 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 @@ -383,6 +383,7 @@ export enum EnumArraysArrayEnumEnum { * @export * @enum {string} */ + export enum EnumClass { Abc = '_abc', Efg = '-efg', @@ -1017,6 +1018,7 @@ export interface OuterComposite { * @export * @enum {string} */ + export enum OuterEnum { Placed = 'placed', Approved = 'approved', @@ -1028,6 +1030,7 @@ export enum OuterEnum { * @export * @enum {string} */ + export enum OuterEnumDefaultValue { Placed = 'placed', Approved = 'approved', @@ -1039,6 +1042,7 @@ export enum OuterEnumDefaultValue { * @export * @enum {string} */ + export enum OuterEnumInteger { NUMBER_0 = 0, NUMBER_1 = 1, @@ -1050,6 +1054,7 @@ export enum OuterEnumInteger { * @export * @enum {string} */ + export enum OuterEnumIntegerDefaultValue { NUMBER_0 = 0, NUMBER_1 = 1, @@ -3089,6 +3094,7 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) * @summary Finds Pets by tags * @param {Array} tags Tags to filter by * @param {*} [options] Override http request option. + * @deprecated * @throws {RequiredError} */ findPetsByTags: async (tags: Array, options: any = {}): Promise => { @@ -3413,6 +3419,7 @@ export const PetApiFp = function(configuration?: Configuration) { * @summary Finds Pets by tags * @param {Array} tags Tags to filter by * @param {*} [options] Override http request option. + * @deprecated * @throws {RequiredError} */ async findPetsByTags(tags: Array, options?: any): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise>> { @@ -3526,6 +3533,7 @@ export const PetApiFactory = function (configuration?: Configuration, basePath?: * @summary Finds Pets by tags * @param {Array} tags Tags to filter by * @param {*} [options] Override http request option. + * @deprecated * @throws {RequiredError} */ findPetsByTags(tags: Array, options?: any): AxiosPromise> { @@ -3639,6 +3647,7 @@ export class PetApi extends BaseAPI { * @summary Finds Pets by tags * @param {Array} tags Tags to filter by * @param {*} [options] Override http request option. + * @deprecated * @throws {RequiredError} * @memberof PetApi */ 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 5f68295fc19..e8415097f3a 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,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x 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 0368b1d5703..c6cda5b6503 100644 --- a/samples/client/petstore/typescript-axios/builds/with-interfaces/api.ts +++ b/samples/client/petstore/typescript-axios/builds/with-interfaces/api.ts @@ -383,6 +383,7 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) * @summary Finds Pets by tags * @param {Array} tags Tags to filter by * @param {*} [options] Override http request option. + * @deprecated * @throws {RequiredError} */ findPetsByTags: async (tags: Array, options: any = {}): Promise => { @@ -649,6 +650,7 @@ export const PetApiFp = function(configuration?: Configuration) { * @summary Finds Pets by tags * @param {Array} tags Tags to filter by * @param {*} [options] Override http request option. + * @deprecated * @throws {RequiredError} */ async findPetsByTags(tags: Array, options?: any): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise>> { @@ -749,6 +751,7 @@ export const PetApiFactory = function (configuration?: Configuration, basePath?: * @summary Finds Pets by tags * @param {Array} tags Tags to filter by * @param {*} [options] Override http request option. + * @deprecated * @throws {RequiredError} */ findPetsByTags(tags: Array, options?: any): AxiosPromise> { @@ -843,6 +846,7 @@ export interface PetApiInterface { * @summary Finds Pets by tags * @param {Array} tags Tags to filter by * @param {*} [options] Override http request option. + * @deprecated * @throws {RequiredError} * @memberof PetApiInterface */ @@ -943,6 +947,7 @@ export class PetApi extends BaseAPI implements PetApiInterface { * @summary Finds Pets by tags * @param {Array} tags Tags to filter by * @param {*} [options] Override http request option. + * @deprecated * @throws {RequiredError} * @memberof PetApi */ 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 5f68295fc19..e8415097f3a 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,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x 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 fc66c5184fa..03545d554fc 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 @@ -159,6 +159,7 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) * @summary Finds Pets by tags * @param {Array} tags Tags to filter by * @param {*} [options] Override http request option. + * @deprecated * @throws {RequiredError} */ findPetsByTags: async (tags: Array, options: any = {}): Promise => { @@ -425,6 +426,7 @@ export const PetApiFp = function(configuration?: Configuration) { * @summary Finds Pets by tags * @param {Array} tags Tags to filter by * @param {*} [options] Override http request option. + * @deprecated * @throws {RequiredError} */ async findPetsByTags(tags: Array, options?: any): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise>> { @@ -525,6 +527,7 @@ export const PetApiFactory = function (configuration?: Configuration, basePath?: * @summary Finds Pets by tags * @param {Array} tags Tags to filter by * @param {*} [options] Override http request option. + * @deprecated * @throws {RequiredError} */ findPetsByTags(tags: Array, options?: any): AxiosPromise> { @@ -626,6 +629,7 @@ export class PetApi extends BaseAPI { * @summary Finds Pets by tags * @param {Array} tags Tags to filter by * @param {*} [options] Override http request option. + * @deprecated * @throws {RequiredError} * @memberof PetApi */ 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 5f68295fc19..e8415097f3a 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,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x 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 856fb0a4829..0ce81cf1174 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 @@ -383,6 +383,7 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) * @summary Finds Pets by tags * @param {Array} tags Tags to filter by * @param {*} [options] Override http request option. + * @deprecated * @throws {RequiredError} */ findPetsByTags: async (tags: Array, options: any = {}): Promise => { @@ -649,6 +650,7 @@ export const PetApiFp = function(configuration?: Configuration) { * @summary Finds Pets by tags * @param {Array} tags Tags to filter by * @param {*} [options] Override http request option. + * @deprecated * @throws {RequiredError} */ async findPetsByTags(tags: Array, options?: any): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise>> { @@ -749,6 +751,7 @@ export const PetApiFactory = function (configuration?: Configuration, basePath?: * @summary Finds Pets by tags * @param {Array} tags Tags to filter by * @param {*} [options] Override http request option. + * @deprecated * @throws {RequiredError} */ findPetsByTags(tags: Array, options?: any): AxiosPromise> { @@ -850,6 +853,7 @@ export class PetApi extends BaseAPI { * @summary Finds Pets by tags * @param {Array} tags Tags to filter by * @param {*} [options] Override http request option. + * @deprecated * @throws {RequiredError} * @memberof PetApi */ 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 5f68295fc19..e8415097f3a 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,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x 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 ec156334713..1f8764baaf0 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 @@ -383,6 +383,7 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) * @summary Finds Pets by tags * @param {Array} tags Tags to filter by * @param {*} [options] Override http request option. + * @deprecated * @throws {RequiredError} */ findPetsByTags: async (tags: Array, options: any = {}): Promise => { @@ -649,6 +650,7 @@ export const PetApiFp = function(configuration?: Configuration) { * @summary Finds Pets by tags * @param {Array} tags Tags to filter by * @param {*} [options] Override http request option. + * @deprecated * @throws {RequiredError} */ async findPetsByTags(tags: Array, options?: any): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise>> { @@ -749,6 +751,7 @@ export const PetApiFactory = function (configuration?: Configuration, basePath?: * @summary Finds Pets by tags * @param {Array} tags Tags to filter by * @param {*} [options] Override http request option. + * @deprecated * @throws {RequiredError} */ findPetsByTags(tags: Array, options?: any): AxiosPromise> { @@ -996,6 +999,7 @@ export class PetApi extends BaseAPI { * @summary Finds Pets by tags * @param {PetApiFindPetsByTagsRequest} requestParameters Request parameters. * @param {*} [options] Override http request option. + * @deprecated * @throws {RequiredError} * @memberof PetApi */ 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 5f68295fc19..e8415097f3a 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,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x 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 358d9a5b09b..31f05a52858 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 @@ -64,6 +64,10 @@ export interface FakePropertyEnumIntegerSerializeRequest { outerObjectWithEnumProperty: OuterObjectWithEnumProperty; } +export interface TestBodyWithBinaryRequest { + body: Blob | null; +} + export interface TestBodyWithFileSchemaRequest { fileSchemaTestClass: FileSchemaTestClass; } @@ -352,7 +356,39 @@ export class FakeApi extends runtime.BaseAPI { } /** - * For this test, the body for this request much reference a schema named `File`. + * For this test, the body has to be a binary file. + */ + async testBodyWithBinaryRaw(requestParameters: TestBodyWithBinaryRequest): Promise> { + if (requestParameters.body === null || requestParameters.body === undefined) { + throw new runtime.RequiredError('body','Required parameter requestParameters.body was null or undefined when calling testBodyWithBinary.'); + } + + const queryParameters: any = {}; + + const headerParameters: runtime.HTTPHeaders = {}; + + headerParameters['Content-Type'] = 'image/png'; + + const response = await this.request({ + path: `/fake/body-with-binary`, + method: 'PUT', + headers: headerParameters, + query: queryParameters, + body: requestParameters.body as any, + }); + + return new runtime.VoidApiResponse(response); + } + + /** + * For this test, the body has to be a binary file. + */ + async testBodyWithBinary(requestParameters: TestBodyWithBinaryRequest): Promise { + await this.testBodyWithBinaryRaw(requestParameters); + } + + /** + * For this test, the body for this request must reference a schema named `File`. */ async testBodyWithFileSchemaRaw(requestParameters: TestBodyWithFileSchemaRequest): Promise> { if (requestParameters.fileSchemaTestClass === null || requestParameters.fileSchemaTestClass === undefined) { @@ -377,7 +413,7 @@ export class FakeApi extends runtime.BaseAPI { } /** - * For this test, the body for this request much reference a schema named `File`. + * For this test, the body for this request must reference a schema named `File`. */ async testBodyWithFileSchema(requestParameters: TestBodyWithFileSchemaRequest): Promise { await this.testBodyWithFileSchemaRaw(requestParameters); @@ -696,7 +732,7 @@ export class FakeApi extends runtime.BaseAPI { if (this.configuration && this.configuration.accessToken) { const token = this.configuration.accessToken; - const tokenString = typeof token === 'function' ? token("bearer_test", []) : token; + const tokenString = await token("bearer_test", []); if (tokenString) { headerParameters["Authorization"] = `Bearer ${tokenString}`; @@ -835,7 +871,7 @@ export class FakeApi extends runtime.BaseAPI { const queryParameters: any = {}; if (requestParameters.pipe) { - queryParameters['pipe'] = requestParameters.pipe; + queryParameters['pipe'] = requestParameters.pipe.join(runtime.COLLECTION_FORMATS["pipes"]); } if (requestParameters.ioutil) { 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 854c14d7dcd..198794ce8b0 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 @@ -87,11 +87,7 @@ export class PetApi extends runtime.BaseAPI { if (this.configuration && this.configuration.accessToken) { // oauth required - if (typeof this.configuration.accessToken === 'function') { - headerParameters["Authorization"] = this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); - } else { - headerParameters["Authorization"] = this.configuration.accessToken; - } + headerParameters["Authorization"] = await this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); } const response = await this.request({ @@ -130,11 +126,7 @@ export class PetApi extends runtime.BaseAPI { if (this.configuration && this.configuration.accessToken) { // oauth required - if (typeof this.configuration.accessToken === 'function') { - headerParameters["Authorization"] = this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); - } else { - headerParameters["Authorization"] = this.configuration.accessToken; - } + headerParameters["Authorization"] = await this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); } const response = await this.request({ @@ -173,11 +165,7 @@ export class PetApi extends runtime.BaseAPI { if (this.configuration && this.configuration.accessToken) { // oauth required - if (typeof this.configuration.accessToken === 'function') { - headerParameters["Authorization"] = this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); - } else { - headerParameters["Authorization"] = this.configuration.accessToken; - } + headerParameters["Authorization"] = await this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); } const response = await this.request({ @@ -218,11 +206,7 @@ export class PetApi extends runtime.BaseAPI { if (this.configuration && this.configuration.accessToken) { // oauth required - if (typeof this.configuration.accessToken === 'function') { - headerParameters["Authorization"] = this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); - } else { - headerParameters["Authorization"] = this.configuration.accessToken; - } + headerParameters["Authorization"] = await this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); } const response = await this.request({ @@ -296,11 +280,7 @@ export class PetApi extends runtime.BaseAPI { if (this.configuration && this.configuration.accessToken) { // oauth required - if (typeof this.configuration.accessToken === 'function') { - headerParameters["Authorization"] = this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); - } else { - headerParameters["Authorization"] = this.configuration.accessToken; - } + headerParameters["Authorization"] = await this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); } const response = await this.request({ @@ -335,11 +315,7 @@ export class PetApi extends runtime.BaseAPI { if (this.configuration && this.configuration.accessToken) { // oauth required - if (typeof this.configuration.accessToken === 'function') { - headerParameters["Authorization"] = this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); - } else { - headerParameters["Authorization"] = this.configuration.accessToken; - } + headerParameters["Authorization"] = await this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); } const consumes: runtime.Consume[] = [ @@ -396,11 +372,7 @@ export class PetApi extends runtime.BaseAPI { if (this.configuration && this.configuration.accessToken) { // oauth required - if (typeof this.configuration.accessToken === 'function') { - headerParameters["Authorization"] = this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); - } else { - headerParameters["Authorization"] = this.configuration.accessToken; - } + headerParameters["Authorization"] = await this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); } const consumes: runtime.Consume[] = [ @@ -464,11 +436,7 @@ export class PetApi extends runtime.BaseAPI { if (this.configuration && this.configuration.accessToken) { // oauth required - if (typeof this.configuration.accessToken === 'function') { - headerParameters["Authorization"] = this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); - } else { - headerParameters["Authorization"] = this.configuration.accessToken; - } + headerParameters["Authorization"] = await this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); } const consumes: runtime.Consume[] = [ 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 cb001046c5b..6924269e546 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 @@ -90,8 +90,8 @@ export class BaseAPI { if (middleware.post) { response = await middleware.post({ fetch: this.fetchApi, - url, - init, + url: fetchParams.url, + init: fetchParams.init, response: response.clone(), }) || response; } @@ -135,7 +135,7 @@ export interface ConfigurationParameters { username?: string; // parameter for basic security password?: string; // parameter for basic security apiKey?: string | ((name: string) => string); // parameter for apiKey security - accessToken?: string | ((name?: string, scopes?: string[]) => string); // parameter for oauth2 security + accessToken?: string | Promise | ((name?: string, scopes?: string[]) => string | Promise); // parameter for oauth2 security headers?: HTTPHeaders; //header params we want to use on every request credentials?: RequestCredentials; //value for the credentials param we want to use on each request } @@ -175,10 +175,10 @@ export class Configuration { return undefined; } - get accessToken(): ((name: string, scopes?: string[]) => string) | undefined { + get accessToken(): ((name?: string, scopes?: string[]) => string | Promise) | undefined { const accessToken = this.configuration.accessToken; if (accessToken) { - return typeof accessToken === 'function' ? accessToken : () => accessToken; + return typeof accessToken === 'function' ? accessToken : async () => accessToken; } return undefined; } 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 5f68295fc19..e8415097f3a 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,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x 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 a219f15f7e2..3bf150e489b 100644 --- a/samples/client/petstore/typescript-fetch/builds/default/apis/PetApi.ts +++ b/samples/client/petstore/typescript-fetch/builds/default/apis/PetApi.ts @@ -81,11 +81,7 @@ export class PetApi extends runtime.BaseAPI { if (this.configuration && this.configuration.accessToken) { // oauth required - if (typeof this.configuration.accessToken === 'function') { - headerParameters["Authorization"] = this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); - } else { - headerParameters["Authorization"] = this.configuration.accessToken; - } + headerParameters["Authorization"] = await this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); } const response = await this.request({ @@ -124,11 +120,7 @@ export class PetApi extends runtime.BaseAPI { if (this.configuration && this.configuration.accessToken) { // oauth required - if (typeof this.configuration.accessToken === 'function') { - headerParameters["Authorization"] = this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); - } else { - headerParameters["Authorization"] = this.configuration.accessToken; - } + headerParameters["Authorization"] = await this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); } const response = await this.request({ @@ -167,11 +159,7 @@ export class PetApi extends runtime.BaseAPI { if (this.configuration && this.configuration.accessToken) { // oauth required - if (typeof this.configuration.accessToken === 'function') { - headerParameters["Authorization"] = this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); - } else { - headerParameters["Authorization"] = this.configuration.accessToken; - } + headerParameters["Authorization"] = await this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); } const response = await this.request({ @@ -212,11 +200,7 @@ export class PetApi extends runtime.BaseAPI { if (this.configuration && this.configuration.accessToken) { // oauth required - if (typeof this.configuration.accessToken === 'function') { - headerParameters["Authorization"] = this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); - } else { - headerParameters["Authorization"] = this.configuration.accessToken; - } + headerParameters["Authorization"] = await this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); } const response = await this.request({ @@ -290,11 +274,7 @@ export class PetApi extends runtime.BaseAPI { if (this.configuration && this.configuration.accessToken) { // oauth required - if (typeof this.configuration.accessToken === 'function') { - headerParameters["Authorization"] = this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); - } else { - headerParameters["Authorization"] = this.configuration.accessToken; - } + headerParameters["Authorization"] = await this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); } const response = await this.request({ @@ -329,11 +309,7 @@ export class PetApi extends runtime.BaseAPI { if (this.configuration && this.configuration.accessToken) { // oauth required - if (typeof this.configuration.accessToken === 'function') { - headerParameters["Authorization"] = this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); - } else { - headerParameters["Authorization"] = this.configuration.accessToken; - } + headerParameters["Authorization"] = await this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); } const consumes: runtime.Consume[] = [ @@ -390,11 +366,7 @@ export class PetApi extends runtime.BaseAPI { if (this.configuration && this.configuration.accessToken) { // oauth required - if (typeof this.configuration.accessToken === 'function') { - headerParameters["Authorization"] = this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); - } else { - headerParameters["Authorization"] = this.configuration.accessToken; - } + headerParameters["Authorization"] = await this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); } const consumes: runtime.Consume[] = [ diff --git a/samples/client/petstore/typescript-fetch/builds/default/runtime.ts b/samples/client/petstore/typescript-fetch/builds/default/runtime.ts index f7a51f623ff..8ae5f65348c 100644 --- a/samples/client/petstore/typescript-fetch/builds/default/runtime.ts +++ b/samples/client/petstore/typescript-fetch/builds/default/runtime.ts @@ -90,8 +90,8 @@ export class BaseAPI { if (middleware.post) { response = await middleware.post({ fetch: this.fetchApi, - url, - init, + url: fetchParams.url, + init: fetchParams.init, response: response.clone(), }) || response; } @@ -135,7 +135,7 @@ export interface ConfigurationParameters { username?: string; // parameter for basic security password?: string; // parameter for basic security apiKey?: string | ((name: string) => string); // parameter for apiKey security - accessToken?: string | ((name?: string, scopes?: string[]) => string); // parameter for oauth2 security + accessToken?: string | Promise | ((name?: string, scopes?: string[]) => string | Promise); // parameter for oauth2 security headers?: HTTPHeaders; //header params we want to use on every request credentials?: RequestCredentials; //value for the credentials param we want to use on each request } @@ -175,10 +175,10 @@ export class Configuration { return undefined; } - get accessToken(): ((name: string, scopes?: string[]) => string) | undefined { + get accessToken(): ((name?: string, scopes?: string[]) => string | Promise) | undefined { const accessToken = this.configuration.accessToken; if (accessToken) { - return typeof accessToken === 'function' ? accessToken : () => accessToken; + return typeof accessToken === 'function' ? accessToken : async () => accessToken; } return undefined; } 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 5f68295fc19..e8415097f3a 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,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/client/petstore/typescript-fetch/builds/enum/runtime.ts b/samples/client/petstore/typescript-fetch/builds/enum/runtime.ts index ccb0370bdc4..c4d82bccb8f 100644 --- a/samples/client/petstore/typescript-fetch/builds/enum/runtime.ts +++ b/samples/client/petstore/typescript-fetch/builds/enum/runtime.ts @@ -90,8 +90,8 @@ export class BaseAPI { if (middleware.post) { response = await middleware.post({ fetch: this.fetchApi, - url, - init, + url: fetchParams.url, + init: fetchParams.init, response: response.clone(), }) || response; } @@ -135,7 +135,7 @@ export interface ConfigurationParameters { username?: string; // parameter for basic security password?: string; // parameter for basic security apiKey?: string | ((name: string) => string); // parameter for apiKey security - accessToken?: string | ((name?: string, scopes?: string[]) => string); // parameter for oauth2 security + accessToken?: string | Promise | ((name?: string, scopes?: string[]) => string | Promise); // parameter for oauth2 security headers?: HTTPHeaders; //header params we want to use on every request credentials?: RequestCredentials; //value for the credentials param we want to use on each request } @@ -175,10 +175,10 @@ export class Configuration { return undefined; } - get accessToken(): ((name: string, scopes?: string[]) => string) | undefined { + get accessToken(): ((name?: string, scopes?: string[]) => string | Promise) | undefined { const accessToken = this.configuration.accessToken; if (accessToken) { - return typeof accessToken === 'function' ? accessToken : () => accessToken; + return typeof accessToken === 'function' ? accessToken : async () => accessToken; } return undefined; } 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 5f68295fc19..e8415097f3a 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,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x 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 a219f15f7e2..3bf150e489b 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 @@ -81,11 +81,7 @@ export class PetApi extends runtime.BaseAPI { if (this.configuration && this.configuration.accessToken) { // oauth required - if (typeof this.configuration.accessToken === 'function') { - headerParameters["Authorization"] = this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); - } else { - headerParameters["Authorization"] = this.configuration.accessToken; - } + headerParameters["Authorization"] = await this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); } const response = await this.request({ @@ -124,11 +120,7 @@ export class PetApi extends runtime.BaseAPI { if (this.configuration && this.configuration.accessToken) { // oauth required - if (typeof this.configuration.accessToken === 'function') { - headerParameters["Authorization"] = this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); - } else { - headerParameters["Authorization"] = this.configuration.accessToken; - } + headerParameters["Authorization"] = await this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); } const response = await this.request({ @@ -167,11 +159,7 @@ export class PetApi extends runtime.BaseAPI { if (this.configuration && this.configuration.accessToken) { // oauth required - if (typeof this.configuration.accessToken === 'function') { - headerParameters["Authorization"] = this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); - } else { - headerParameters["Authorization"] = this.configuration.accessToken; - } + headerParameters["Authorization"] = await this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); } const response = await this.request({ @@ -212,11 +200,7 @@ export class PetApi extends runtime.BaseAPI { if (this.configuration && this.configuration.accessToken) { // oauth required - if (typeof this.configuration.accessToken === 'function') { - headerParameters["Authorization"] = this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); - } else { - headerParameters["Authorization"] = this.configuration.accessToken; - } + headerParameters["Authorization"] = await this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); } const response = await this.request({ @@ -290,11 +274,7 @@ export class PetApi extends runtime.BaseAPI { if (this.configuration && this.configuration.accessToken) { // oauth required - if (typeof this.configuration.accessToken === 'function') { - headerParameters["Authorization"] = this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); - } else { - headerParameters["Authorization"] = this.configuration.accessToken; - } + headerParameters["Authorization"] = await this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); } const response = await this.request({ @@ -329,11 +309,7 @@ export class PetApi extends runtime.BaseAPI { if (this.configuration && this.configuration.accessToken) { // oauth required - if (typeof this.configuration.accessToken === 'function') { - headerParameters["Authorization"] = this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); - } else { - headerParameters["Authorization"] = this.configuration.accessToken; - } + headerParameters["Authorization"] = await this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); } const consumes: runtime.Consume[] = [ @@ -390,11 +366,7 @@ export class PetApi extends runtime.BaseAPI { if (this.configuration && this.configuration.accessToken) { // oauth required - if (typeof this.configuration.accessToken === 'function') { - headerParameters["Authorization"] = this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); - } else { - headerParameters["Authorization"] = this.configuration.accessToken; - } + headerParameters["Authorization"] = await this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); } const consumes: runtime.Consume[] = [ 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 f7a51f623ff..8ae5f65348c 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 @@ -90,8 +90,8 @@ export class BaseAPI { if (middleware.post) { response = await middleware.post({ fetch: this.fetchApi, - url, - init, + url: fetchParams.url, + init: fetchParams.init, response: response.clone(), }) || response; } @@ -135,7 +135,7 @@ export interface ConfigurationParameters { username?: string; // parameter for basic security password?: string; // parameter for basic security apiKey?: string | ((name: string) => string); // parameter for apiKey security - accessToken?: string | ((name?: string, scopes?: string[]) => string); // parameter for oauth2 security + accessToken?: string | Promise | ((name?: string, scopes?: string[]) => string | Promise); // parameter for oauth2 security headers?: HTTPHeaders; //header params we want to use on every request credentials?: RequestCredentials; //value for the credentials param we want to use on each request } @@ -175,10 +175,10 @@ export class Configuration { return undefined; } - get accessToken(): ((name: string, scopes?: string[]) => string) | undefined { + get accessToken(): ((name?: string, scopes?: string[]) => string | Promise) | undefined { const accessToken = this.configuration.accessToken; if (accessToken) { - return typeof accessToken === 'function' ? accessToken : () => accessToken; + return typeof accessToken === 'function' ? accessToken : async () => accessToken; } return undefined; } 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 5f68295fc19..e8415097f3a 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,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x 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 4c47ea2e1f1..db5971d0ad5 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 @@ -81,11 +81,7 @@ export class PetApi extends runtime.BaseAPI { if (this.configuration && this.configuration.accessToken) { // oauth required - if (typeof this.configuration.accessToken === 'function') { - headerParameters["Authorization"] = this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); - } else { - headerParameters["Authorization"] = this.configuration.accessToken; - } + headerParameters["Authorization"] = await this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); } const response = await this.request({ @@ -124,11 +120,7 @@ export class PetApi extends runtime.BaseAPI { if (this.configuration && this.configuration.accessToken) { // oauth required - if (typeof this.configuration.accessToken === 'function') { - headerParameters["Authorization"] = this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); - } else { - headerParameters["Authorization"] = this.configuration.accessToken; - } + headerParameters["Authorization"] = await this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); } const response = await this.request({ @@ -167,11 +159,7 @@ export class PetApi extends runtime.BaseAPI { if (this.configuration && this.configuration.accessToken) { // oauth required - if (typeof this.configuration.accessToken === 'function') { - headerParameters["Authorization"] = this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); - } else { - headerParameters["Authorization"] = this.configuration.accessToken; - } + headerParameters["Authorization"] = await this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); } const response = await this.request({ @@ -212,11 +200,7 @@ export class PetApi extends runtime.BaseAPI { if (this.configuration && this.configuration.accessToken) { // oauth required - if (typeof this.configuration.accessToken === 'function') { - headerParameters["Authorization"] = this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); - } else { - headerParameters["Authorization"] = this.configuration.accessToken; - } + headerParameters["Authorization"] = await this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); } const response = await this.request({ @@ -290,11 +274,7 @@ export class PetApi extends runtime.BaseAPI { if (this.configuration && this.configuration.accessToken) { // oauth required - if (typeof this.configuration.accessToken === 'function') { - headerParameters["Authorization"] = this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); - } else { - headerParameters["Authorization"] = this.configuration.accessToken; - } + headerParameters["Authorization"] = await this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); } const response = await this.request({ @@ -329,11 +309,7 @@ export class PetApi extends runtime.BaseAPI { if (this.configuration && this.configuration.accessToken) { // oauth required - if (typeof this.configuration.accessToken === 'function') { - headerParameters["Authorization"] = this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); - } else { - headerParameters["Authorization"] = this.configuration.accessToken; - } + headerParameters["Authorization"] = await this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); } const consumes: runtime.Consume[] = [ @@ -390,11 +366,7 @@ export class PetApi extends runtime.BaseAPI { if (this.configuration && this.configuration.accessToken) { // oauth required - if (typeof this.configuration.accessToken === 'function') { - headerParameters["Authorization"] = this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); - } else { - headerParameters["Authorization"] = this.configuration.accessToken; - } + headerParameters["Authorization"] = await this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); } const consumes: runtime.Consume[] = [ 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 f7a51f623ff..8ae5f65348c 100644 --- a/samples/client/petstore/typescript-fetch/builds/multiple-parameters/runtime.ts +++ b/samples/client/petstore/typescript-fetch/builds/multiple-parameters/runtime.ts @@ -90,8 +90,8 @@ export class BaseAPI { if (middleware.post) { response = await middleware.post({ fetch: this.fetchApi, - url, - init, + url: fetchParams.url, + init: fetchParams.init, response: response.clone(), }) || response; } @@ -135,7 +135,7 @@ export interface ConfigurationParameters { username?: string; // parameter for basic security password?: string; // parameter for basic security apiKey?: string | ((name: string) => string); // parameter for apiKey security - accessToken?: string | ((name?: string, scopes?: string[]) => string); // parameter for oauth2 security + accessToken?: string | Promise | ((name?: string, scopes?: string[]) => string | Promise); // parameter for oauth2 security headers?: HTTPHeaders; //header params we want to use on every request credentials?: RequestCredentials; //value for the credentials param we want to use on each request } @@ -175,10 +175,10 @@ export class Configuration { return undefined; } - get accessToken(): ((name: string, scopes?: string[]) => string) | undefined { + get accessToken(): ((name?: string, scopes?: string[]) => string | Promise) | undefined { const accessToken = this.configuration.accessToken; if (accessToken) { - return typeof accessToken === 'function' ? accessToken : () => accessToken; + return typeof accessToken === 'function' ? accessToken : async () => accessToken; } return undefined; } 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 5f68295fc19..e8415097f3a 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,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x 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 b98247c01da..e2fd699fd73 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 @@ -81,11 +81,7 @@ export class PetApi extends runtime.BaseAPI { if (this.configuration && this.configuration.accessToken) { // oauth required - if (typeof this.configuration.accessToken === 'function') { - headerParameters["Authorization"] = this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); - } else { - headerParameters["Authorization"] = this.configuration.accessToken; - } + headerParameters["Authorization"] = await this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); } const response = await this.request({ @@ -124,11 +120,7 @@ export class PetApi extends runtime.BaseAPI { if (this.configuration && this.configuration.accessToken) { // oauth required - if (typeof this.configuration.accessToken === 'function') { - headerParameters["Authorization"] = this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); - } else { - headerParameters["Authorization"] = this.configuration.accessToken; - } + headerParameters["Authorization"] = await this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); } const response = await this.request({ @@ -167,11 +159,7 @@ export class PetApi extends runtime.BaseAPI { if (this.configuration && this.configuration.accessToken) { // oauth required - if (typeof this.configuration.accessToken === 'function') { - headerParameters["Authorization"] = this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); - } else { - headerParameters["Authorization"] = this.configuration.accessToken; - } + headerParameters["Authorization"] = await this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); } const response = await this.request({ @@ -212,11 +200,7 @@ export class PetApi extends runtime.BaseAPI { if (this.configuration && this.configuration.accessToken) { // oauth required - if (typeof this.configuration.accessToken === 'function') { - headerParameters["Authorization"] = this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); - } else { - headerParameters["Authorization"] = this.configuration.accessToken; - } + headerParameters["Authorization"] = await this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); } const response = await this.request({ @@ -290,11 +274,7 @@ export class PetApi extends runtime.BaseAPI { if (this.configuration && this.configuration.accessToken) { // oauth required - if (typeof this.configuration.accessToken === 'function') { - headerParameters["Authorization"] = this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); - } else { - headerParameters["Authorization"] = this.configuration.accessToken; - } + headerParameters["Authorization"] = await this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); } const response = await this.request({ @@ -329,11 +309,7 @@ export class PetApi extends runtime.BaseAPI { if (this.configuration && this.configuration.accessToken) { // oauth required - if (typeof this.configuration.accessToken === 'function') { - headerParameters["Authorization"] = this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); - } else { - headerParameters["Authorization"] = this.configuration.accessToken; - } + headerParameters["Authorization"] = await this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); } const consumes: runtime.Consume[] = [ @@ -390,11 +366,7 @@ export class PetApi extends runtime.BaseAPI { if (this.configuration && this.configuration.accessToken) { // oauth required - if (typeof this.configuration.accessToken === 'function') { - headerParameters["Authorization"] = this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); - } else { - headerParameters["Authorization"] = this.configuration.accessToken; - } + headerParameters["Authorization"] = await this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); } const consumes: runtime.Consume[] = [ 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 f7a51f623ff..8ae5f65348c 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 @@ -90,8 +90,8 @@ export class BaseAPI { if (middleware.post) { response = await middleware.post({ fetch: this.fetchApi, - url, - init, + url: fetchParams.url, + init: fetchParams.init, response: response.clone(), }) || response; } @@ -135,7 +135,7 @@ export interface ConfigurationParameters { username?: string; // parameter for basic security password?: string; // parameter for basic security apiKey?: string | ((name: string) => string); // parameter for apiKey security - accessToken?: string | ((name?: string, scopes?: string[]) => string); // parameter for oauth2 security + accessToken?: string | Promise | ((name?: string, scopes?: string[]) => string | Promise); // parameter for oauth2 security headers?: HTTPHeaders; //header params we want to use on every request credentials?: RequestCredentials; //value for the credentials param we want to use on each request } @@ -175,10 +175,10 @@ export class Configuration { return undefined; } - get accessToken(): ((name: string, scopes?: string[]) => string) | undefined { + get accessToken(): ((name?: string, scopes?: string[]) => string | Promise) | undefined { const accessToken = this.configuration.accessToken; if (accessToken) { - return typeof accessToken === 'function' ? accessToken : () => accessToken; + return typeof accessToken === 'function' ? accessToken : async () => accessToken; } return undefined; } diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/.gitignore b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/.gitignore new file mode 100644 index 00000000000..149b5765472 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/.gitignore @@ -0,0 +1,4 @@ +wwwroot/*.js +node_modules +typings +dist diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/.npmignore b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/.npmignore new file mode 100644 index 00000000000..42061c01a1c --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/.npmignore @@ -0,0 +1 @@ +README.md \ No newline at end of file diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/.openapi-generator-ignore b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/.openapi-generator-ignore new file mode 100644 index 00000000000..7484ee590a3 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/.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/typescript-fetch/builds/sagas-and-records/.openapi-generator/FILES b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/.openapi-generator/FILES new file mode 100644 index 00000000000..354b10210e0 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/.openapi-generator/FILES @@ -0,0 +1,71 @@ +.gitignore +.npmignore +README.md +package.json +src/ApiEntitiesRecord.ts +src/ApiEntitiesReducer.ts +src/ApiEntitiesSelectors.ts +src/apis/BehaviorApi.ts +src/apis/BehaviorApiSagas.ts +src/apis/PetApi.ts +src/apis/PetApiSagas.ts +src/apis/PetPartApi.ts +src/apis/PetPartApiSagas.ts +src/apis/SagaApiManager.ts +src/apis/StoreApi.ts +src/apis/StoreApiSagas.ts +src/apis/UserApi.ts +src/apis/UserApiSagas.ts +src/apis/allSagas.ts +src/apis/index.ts +src/index.ts +src/models/BehaviorType.ts +src/models/BehaviorTypeRecord.ts +src/models/Category.ts +src/models/CategoryRecord.ts +src/models/DefaultMetaOnlyResponse.ts +src/models/DefaultMetaOnlyResponseRecord.ts +src/models/DeploymentRequestStatus.ts +src/models/DeploymentRequestStatusRecord.ts +src/models/ErrorCode.ts +src/models/ErrorCodeRecord.ts +src/models/FindPetsByStatusResponse.ts +src/models/FindPetsByStatusResponseRecord.ts +src/models/FindPetsByUserResponse.ts +src/models/FindPetsByUserResponseRecord.ts +src/models/GetBehaviorPermissionsResponse.ts +src/models/GetBehaviorPermissionsResponseRecord.ts +src/models/GetBehaviorTypeResponse.ts +src/models/GetBehaviorTypeResponseRecord.ts +src/models/GetMatchingPartsResponse.ts +src/models/GetMatchingPartsResponseRecord.ts +src/models/GetPetPartTypeResponse.ts +src/models/GetPetPartTypeResponseRecord.ts +src/models/ItemId.ts +src/models/ItemIdRecord.ts +src/models/MatchingParts.ts +src/models/MatchingPartsRecord.ts +src/models/ModelApiResponse.ts +src/models/ModelApiResponseRecord.ts +src/models/ModelError.ts +src/models/ModelErrorRecord.ts +src/models/Order.ts +src/models/OrderRecord.ts +src/models/Part.ts +src/models/PartRecord.ts +src/models/Pet.ts +src/models/PetPartType.ts +src/models/PetPartTypeRecord.ts +src/models/PetRecord.ts +src/models/ResponseMeta.ts +src/models/ResponseMetaRecord.ts +src/models/Tag.ts +src/models/TagRecord.ts +src/models/User.ts +src/models/UserRecord.ts +src/models/WarningCode.ts +src/models/WarningCodeRecord.ts +src/models/index.ts +src/runtime.ts +src/runtimeSagasAndRecords.ts +tsconfig.json 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 new file mode 100644 index 00000000000..4b448de535c --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/.openapi-generator/VERSION @@ -0,0 +1 @@ +5.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/README.md b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/README.md new file mode 100644 index 00000000000..8c188be0ead --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/README.md @@ -0,0 +1,45 @@ +## @openapitools/typescript-fetch-petstore@1.0.0 + +This generator creates TypeScript/JavaScript client that utilizes [Fetch API](https://fetch.spec.whatwg.org/). 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-fetch-petstore@1.0.0 --save +``` + +_unPublished (not recommended):_ + +``` +npm install PATH_TO_GENERATED_PACKAGE --save diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/package.json b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/package.json new file mode 100644 index 00000000000..3b5c84b1eee --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/package.json @@ -0,0 +1,21 @@ +{ + "name": "@openapitools/typescript-fetch-petstore", + "version": "1.0.0", + "description": "OpenAPI client for @openapitools/typescript-fetch-petstore", + "author": "OpenAPI-Generator", + "main": "./dist/index.js", + "typings": "./dist/index.d.ts", + "scripts": { + "build": "tsc" }, + "devDependencies": { + "immutable": "^4.0.0-rc.12", + "normalizr": "^3.6.1", + "redux-saga": "^1.1.3", + "redux-ts-simple": "^3.2.0", + "reselect": "^4.0.0", + "typescript": "^3.9.5" + }, + "publishConfig": { + "registry": "https://skimdb.npmjs.com/registry" + } +} diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/ApiEntitiesRecord.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/ApiEntitiesRecord.ts new file mode 100644 index 00000000000..edf89903eec --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/ApiEntitiesRecord.ts @@ -0,0 +1,22 @@ +import {Map, Record, RecordOf} from 'immutable'; + +import { + CategoryRecordEntity, + OrderRecordEntity, + PetRecordEntity, + TagRecordEntity, + UserRecordEntity, +} from "./models" + +export const ApiEntitiesRecordProps = { + recType: "ApiEntitiesRecord" as "ApiEntitiesRecord", + category: (CategoryRecordEntity(), Map()), + order: (OrderRecordEntity(), Map()), + pet: (PetRecordEntity(), Map()), + tag: (TagRecordEntity(), Map()), + user: (UserRecordEntity(), Map()), +}; + +export type ApiEntitiesRecordPropsType = typeof ApiEntitiesRecordProps; +export const ApiEntitiesRecord = Record(ApiEntitiesRecordProps, ApiEntitiesRecordProps.recType); +export type ApiEntitiesRecord = RecordOf; \ No newline at end of file diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/ApiEntitiesReducer.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/ApiEntitiesReducer.ts new file mode 100644 index 00000000000..9f607ac090f --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/ApiEntitiesReducer.ts @@ -0,0 +1,21 @@ +import {ApiEntitiesRecord} from "./ApiEntitiesRecord"; +import {ReducerBuilder} from "redux-ts-simple"; +import {normalizedEntities} from "./runtimeSagasAndRecords"; + +export const ApiEntitiesReducer = new ReducerBuilder(ApiEntitiesRecord()) + .on(normalizedEntities, (state, action): ApiEntitiesRecord => { + const {entities} = action.payload; + return state.withMutations(mutableState => { + for (const entityKey in entities) { + const entityMap = entities[entityKey]; + const currentEntityMap = mutableState.get(entityKey as any); + if (currentEntityMap) { + let mergedEntityMap = currentEntityMap.mergeDeep(entityMap); + if (!mergedEntityMap.equals(currentEntityMap)) { + mutableState.set(entityKey as any, mergedEntityMap); + } + } + } + }); + }) + .build(); \ No newline at end of file diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/ApiEntitiesSelectors.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/ApiEntitiesSelectors.ts new file mode 100644 index 00000000000..9eaffec0dfe --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/ApiEntitiesSelectors.ts @@ -0,0 +1,5 @@ +export let getApiEntitiesState: (state: any) => any = (state: any) => state.app.apiEntities; + +export function setApiEntitiesStateGetter(getter: (state: any) => any) { // Use this to customize the location where you have placed your ApiEntitiesRecord in your project. + getApiEntitiesState = getter; +} \ No newline at end of file diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/apis/BehaviorApi.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/apis/BehaviorApi.ts new file mode 100644 index 00000000000..82adc068a8a --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/apis/BehaviorApi.ts @@ -0,0 +1,99 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * 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. + */ + + +import * as runtime from '../runtime'; +import { + GetBehaviorPermissionsResponse, + GetBehaviorPermissionsResponseFromJSON, + GetBehaviorPermissionsResponseToJSON, + GetBehaviorTypeResponse, + GetBehaviorTypeResponseFromJSON, + GetBehaviorTypeResponseToJSON, +} from '../models'; + +export interface GetBehaviorPermissionsRequest { + behaviorId: number; +} + +export interface GetBehaviorTypeRequest { + behaviorId: number; +} + +/** + * + */ +export class BehaviorApi extends runtime.BaseAPI { + + /** + * Get permissions for the behavior + */ + async getBehaviorPermissionsRaw(requestParameters: GetBehaviorPermissionsRequest): Promise> { + if (requestParameters.behaviorId === null || requestParameters.behaviorId === undefined) { + throw new runtime.RequiredError('behaviorId','Required parameter requestParameters.behaviorId was null or undefined when calling getBehaviorPermissions.'); + } + + const queryParameters: any = {}; + + const headerParameters: runtime.HTTPHeaders = {}; + + const response = await this.request({ + path: `/fake_behavior/{behavior-id}/permissions`.replace(`{${"behavior-id"}}`, encodeURIComponent(String(requestParameters.behaviorId))), + method: 'GET', + headers: headerParameters, + query: queryParameters, + }); + + return new runtime.JSONApiResponse(response, (jsonValue) => GetBehaviorPermissionsResponseFromJSON(jsonValue)); + } + + /** + * Get permissions for the behavior + */ + async getBehaviorPermissions(behaviorId: number): Promise { + const response = await this.getBehaviorPermissionsRaw({ behaviorId: behaviorId }); + return await response.value(); + } + + /** + * Get the type of behavior + */ + async getBehaviorTypeRaw(requestParameters: GetBehaviorTypeRequest): Promise> { + if (requestParameters.behaviorId === null || requestParameters.behaviorId === undefined) { + throw new runtime.RequiredError('behaviorId','Required parameter requestParameters.behaviorId was null or undefined when calling getBehaviorType.'); + } + + const queryParameters: any = {}; + + const headerParameters: runtime.HTTPHeaders = {}; + + const response = await this.request({ + path: `/fake_behavior/{behavior-id}/type`.replace(`{${"behavior-id"}}`, encodeURIComponent(String(requestParameters.behaviorId))), + method: 'GET', + headers: headerParameters, + query: queryParameters, + }); + + return new runtime.JSONApiResponse(response, (jsonValue) => GetBehaviorTypeResponseFromJSON(jsonValue)); + } + + /** + * Get the type of behavior + */ + async getBehaviorType(behaviorId: number): Promise { + const response = await this.getBehaviorTypeRaw({ behaviorId: behaviorId }); + return await response.value(); + } + +} diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/apis/BehaviorApiSagas.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/apis/BehaviorApiSagas.ts new file mode 100644 index 00000000000..5d671f274d3 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/apis/BehaviorApiSagas.ts @@ -0,0 +1,131 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * 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. + */ + + +import {Api} from './'; +import {List} from 'immutable'; +import {all, fork, put, takeLatest} from "redux-saga/effects"; +import {apiCall, createSagaAction as originalCreateSagaAction, BaseEntitySupportPayloadApiAction, BasePayloadApiAction, NormalizedRecordEntities, normalizedEntities} from "../runtimeSagasAndRecords"; +import {Action} from "redux-ts-simple"; + +import { + GetBehaviorPermissionsResponse, + GetBehaviorPermissionsResponseRecord, + getBehaviorPermissionsResponseRecordUtils, + GetBehaviorTypeResponse, + GetBehaviorTypeResponseRecord, + getBehaviorTypeResponseRecordUtils, + BehaviorType, +} from '../models'; + +const createSagaAction = (type: string) => originalCreateSagaAction(type, {namespace: "api_behaviorApi"}); + +export const behaviorApiSagaMap = new Map Generator>([ + ["getBehaviorPermissions", getBehaviorPermissionsSaga], + ["getBehaviorType", getBehaviorTypeSaga], + ] +); + +export function *behaviorApiAllSagas() { + yield all([...behaviorApiSagaMap.values()].map(actionSaga => fork(actionSaga))); +} + +//region getBehaviorPermissions + +export interface PayloadGetBehaviorPermissions extends PayloadGetBehaviorPermissionsRequest, BasePayloadApiAction { +} + +export interface PayloadGetBehaviorPermissionsRequest { + behaviorId: string; +} + +export const getBehaviorPermissionsRequest = createSagaAction("getBehaviorPermissionsRequest"); +export const getBehaviorPermissionsSuccess = createSagaAction<{ [key: string]: boolean; }>("getBehaviorPermissionsSuccess"); +export const getBehaviorPermissionsFailure = createSagaAction<{error: any, requestPayload: PayloadGetBehaviorPermissions}>("getBehaviorPermissionsFailure"); + +export const getBehaviorPermissions = createSagaAction("getBehaviorPermissions"); + +export function *getBehaviorPermissionsSaga() { + yield takeLatest(getBehaviorPermissions, getBehaviorPermissionsSagaImp); +} + +export function *getBehaviorPermissionsSagaImp(_action_: Action) { + const {markErrorsAsHandled, ..._payloadRest_} = _action_.payload; + try { + const { + behaviorId, + } = _payloadRest_; + + yield put(getBehaviorPermissionsRequest(_action_.payload)); + + const response: Required = yield apiCall(Api.behaviorApi, Api.behaviorApi.getBehaviorPermissions, + parseFloat(behaviorId), + ); + + let successReturnValue: any = undefined; + successReturnValue = getBehaviorPermissionsResponseRecordUtils.fromApiPassthrough(response); + yield put(getBehaviorPermissionsSuccess(successReturnValue)); + + return successReturnValue; + } catch (error) { + if (markErrorsAsHandled) {error.wasHandled = true; } + yield put(getBehaviorPermissionsFailure({error, requestPayload: _action_.payload})); + return error; + } +} +//endregion +//region getBehaviorType + +export interface PayloadGetBehaviorType extends PayloadGetBehaviorTypeRequest, BasePayloadApiAction { +} + +export interface PayloadGetBehaviorTypeRequest { + behaviorId: string; +} + +export const getBehaviorTypeRequest = createSagaAction("getBehaviorTypeRequest"); +export const getBehaviorTypeSuccess = createSagaAction("getBehaviorTypeSuccess"); +export const getBehaviorTypeFailure = createSagaAction<{error: any, requestPayload: PayloadGetBehaviorType}>("getBehaviorTypeFailure"); + +export const getBehaviorType = createSagaAction("getBehaviorType"); + +export function *getBehaviorTypeSaga() { + yield takeLatest(getBehaviorType, getBehaviorTypeSagaImp); +} + +export function *getBehaviorTypeSagaImp(_action_: Action) { + const {markErrorsAsHandled, ..._payloadRest_} = _action_.payload; + try { + const { + behaviorId, + } = _payloadRest_; + + yield put(getBehaviorTypeRequest(_action_.payload)); + + const response: Required = yield apiCall(Api.behaviorApi, Api.behaviorApi.getBehaviorType, + parseFloat(behaviorId), + ); + + let successReturnValue: any = undefined; + successReturnValue = getBehaviorTypeResponseRecordUtils.fromApiPassthrough(response); + yield put(getBehaviorTypeSuccess(successReturnValue)); + + return successReturnValue; + } catch (error) { + if (markErrorsAsHandled) {error.wasHandled = true; } + yield put(getBehaviorTypeFailure({error, requestPayload: _action_.payload})); + return error; + } +} +//endregion 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 new file mode 100644 index 00000000000..5c881e816cd --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/apis/PetApi.ts @@ -0,0 +1,524 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * 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. + */ + + +import * as runtime from '../runtime'; +import { + Category, + CategoryFromJSON, + CategoryToJSON, + FindPetsByStatusResponse, + FindPetsByStatusResponseFromJSON, + FindPetsByStatusResponseToJSON, + FindPetsByUserResponse, + FindPetsByUserResponseFromJSON, + FindPetsByUserResponseToJSON, + ModelApiResponse, + ModelApiResponseFromJSON, + ModelApiResponseToJSON, + Pet, + PetFromJSON, + PetToJSON, +} from '../models'; + +export interface AddPetRequest { + dummyCat: Category; +} + +export interface DeletePetRequest { + petId: number; + apiKey?: string; +} + +export interface FindPetsByIdsRequest { + ids: Array; +} + +export interface FindPetsByStatusRequest { + status: Array; +} + +export interface FindPetsByTagsRequest { + tags: Array; +} + +export interface FindPetsByUserIdsRequest { + ids: Array; +} + +export interface GetPetByIdRequest { + petId: number; +} + +export interface UpdatePetRequest { + body: Pet; +} + +export interface UpdatePetWithFormRequest { + petId: number; + name?: string; + status?: string; +} + +export interface UploadFileRequest { + petId: number; + additionalMetadata?: string; + file?: Blob; +} + +/** + * + */ +export class PetApi extends runtime.BaseAPI { + + /** + * Add a new pet to the store + */ + async addPetRaw(requestParameters: AddPetRequest): Promise> { + if (requestParameters.dummyCat === null || requestParameters.dummyCat === undefined) { + throw new runtime.RequiredError('dummyCat','Required parameter requestParameters.dummyCat was null or undefined when calling addPet.'); + } + + const queryParameters: any = {}; + + const headerParameters: runtime.HTTPHeaders = {}; + + headerParameters['Content-Type'] = 'application/json'; + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); + } + + const response = await this.request({ + path: `/pet`, + method: 'POST', + headers: headerParameters, + query: queryParameters, + body: CategoryToJSON(requestParameters.dummyCat), + }); + + return new runtime.VoidApiResponse(response); + } + + /** + * Add a new pet to the store + */ + async addPet(dummyCat: Category): Promise { + await this.addPetRaw({ dummyCat: dummyCat }); + } + + /** + * Deletes a pet + */ + async deletePetRaw(requestParameters: DeletePetRequest): Promise> { + if (requestParameters.petId === null || requestParameters.petId === undefined) { + throw new runtime.RequiredError('petId','Required parameter requestParameters.petId was null or undefined when calling deletePet.'); + } + + const queryParameters: any = {}; + + const headerParameters: runtime.HTTPHeaders = {}; + + if (requestParameters.apiKey !== undefined && requestParameters.apiKey !== null) { + headerParameters['api_key'] = String(requestParameters.apiKey); + } + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); + } + + const response = await this.request({ + path: `/pet/{petId}`.replace(`{${"petId"}}`, encodeURIComponent(String(requestParameters.petId))), + method: 'DELETE', + headers: headerParameters, + query: queryParameters, + }); + + return new runtime.VoidApiResponse(response); + } + + /** + * Deletes a pet + */ + async deletePet(petId: number, apiKey?: string): Promise { + await this.deletePetRaw({ petId: petId, apiKey: apiKey }); + } + + /** + * Multiple ids can be provided with comma separated strings. + * Finds Pets by ids + */ + async findPetsByIdsRaw(requestParameters: FindPetsByIdsRequest): Promise>> { + if (requestParameters.ids === null || requestParameters.ids === undefined) { + throw new runtime.RequiredError('ids','Required parameter requestParameters.ids was null or undefined when calling findPetsByIds.'); + } + + const queryParameters: any = {}; + + if (requestParameters.ids) { + queryParameters['ids'] = requestParameters.ids.join(runtime.COLLECTION_FORMATS["csv"]); + } + + const headerParameters: runtime.HTTPHeaders = {}; + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); + } + + const response = await this.request({ + path: `/pet/findByIds`, + method: 'GET', + headers: headerParameters, + query: queryParameters, + }); + + return new runtime.JSONApiResponse(response, (jsonValue) => jsonValue.map(PetFromJSON)); + } + + /** + * Multiple ids can be provided with comma separated strings. + * Finds Pets by ids + */ + async findPetsByIds(ids: Array): Promise> { + const response = await this.findPetsByIdsRaw({ ids: ids }); + return await response.value(); + } + + /** + * Multiple status values can be provided with comma separated strings + * Finds Pets by status + */ + async findPetsByStatusRaw(requestParameters: FindPetsByStatusRequest): Promise> { + if (requestParameters.status === null || requestParameters.status === undefined) { + throw new runtime.RequiredError('status','Required parameter requestParameters.status was null or undefined when calling findPetsByStatus.'); + } + + const queryParameters: any = {}; + + if (requestParameters.status) { + queryParameters['status'] = requestParameters.status.join(runtime.COLLECTION_FORMATS["csv"]); + } + + const headerParameters: runtime.HTTPHeaders = {}; + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); + } + + const response = await this.request({ + path: `/pet/findByStatus`, + method: 'GET', + headers: headerParameters, + query: queryParameters, + }); + + return new runtime.JSONApiResponse(response, (jsonValue) => FindPetsByStatusResponseFromJSON(jsonValue)); + } + + /** + * Multiple status values can be provided with comma separated strings + * Finds Pets by status + */ + async findPetsByStatus(status: Array): Promise { + const response = await this.findPetsByStatusRaw({ status: status }); + return await response.value(); + } + + /** + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + * Finds Pets by tags + */ + async findPetsByTagsRaw(requestParameters: FindPetsByTagsRequest): Promise>> { + if (requestParameters.tags === null || requestParameters.tags === undefined) { + throw new runtime.RequiredError('tags','Required parameter requestParameters.tags was null or undefined when calling findPetsByTags.'); + } + + const queryParameters: any = {}; + + if (requestParameters.tags) { + queryParameters['tags'] = requestParameters.tags.join(runtime.COLLECTION_FORMATS["csv"]); + } + + const headerParameters: runtime.HTTPHeaders = {}; + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); + } + + const response = await this.request({ + path: `/pet/findByTags`, + method: 'GET', + headers: headerParameters, + query: queryParameters, + }); + + return new runtime.JSONApiResponse(response, (jsonValue) => jsonValue.map(PetFromJSON)); + } + + /** + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + * Finds Pets by tags + */ + async findPetsByTags(tags: Array): Promise> { + const response = await this.findPetsByTagsRaw({ tags: tags }); + return await response.value(); + } + + /** + * Multiple ids can be provided with comma separated strings. + * Finds Pets by user ids + */ + async findPetsByUserIdsRaw(requestParameters: FindPetsByUserIdsRequest): Promise> { + if (requestParameters.ids === null || requestParameters.ids === undefined) { + throw new runtime.RequiredError('ids','Required parameter requestParameters.ids was null or undefined when calling findPetsByUserIds.'); + } + + const queryParameters: any = {}; + + if (requestParameters.ids) { + queryParameters['ids'] = requestParameters.ids.join(runtime.COLLECTION_FORMATS["csv"]); + } + + const headerParameters: runtime.HTTPHeaders = {}; + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); + } + + const response = await this.request({ + path: `/pet/findByUserIds`, + method: 'GET', + headers: headerParameters, + query: queryParameters, + }); + + return new runtime.JSONApiResponse(response, (jsonValue) => FindPetsByUserResponseFromJSON(jsonValue)); + } + + /** + * Multiple ids can be provided with comma separated strings. + * Finds Pets by user ids + */ + async findPetsByUserIds(ids: Array): Promise { + const response = await this.findPetsByUserIdsRaw({ ids: ids }); + return await response.value(); + } + + /** + * Returns a single pet + * Find pet by ID + */ + async getPetByIdRaw(requestParameters: GetPetByIdRequest): Promise> { + if (requestParameters.petId === null || requestParameters.petId === undefined) { + throw new runtime.RequiredError('petId','Required parameter requestParameters.petId was null or undefined when calling getPetById.'); + } + + const queryParameters: any = {}; + + const headerParameters: runtime.HTTPHeaders = {}; + + if (this.configuration && this.configuration.apiKey) { + headerParameters["api_key"] = this.configuration.apiKey("api_key"); // api_key authentication + } + + const response = await this.request({ + path: `/pet/{petId}`.replace(`{${"petId"}}`, encodeURIComponent(String(requestParameters.petId))), + method: 'GET', + headers: headerParameters, + query: queryParameters, + }); + + return new runtime.JSONApiResponse(response, (jsonValue) => PetFromJSON(jsonValue)); + } + + /** + * Returns a single pet + * Find pet by ID + */ + async getPetById(petId: number): Promise { + const response = await this.getPetByIdRaw({ petId: petId }); + return await response.value(); + } + + /** + * Update an existing pet + */ + async updatePetRaw(requestParameters: UpdatePetRequest): Promise> { + if (requestParameters.body === null || requestParameters.body === undefined) { + throw new runtime.RequiredError('body','Required parameter requestParameters.body was null or undefined when calling updatePet.'); + } + + const queryParameters: any = {}; + + const headerParameters: runtime.HTTPHeaders = {}; + + headerParameters['Content-Type'] = 'application/json'; + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); + } + + const response = await this.request({ + path: `/pet`, + method: 'PUT', + headers: headerParameters, + query: queryParameters, + body: PetToJSON(requestParameters.body), + }); + + return new runtime.VoidApiResponse(response); + } + + /** + * Update an existing pet + */ + async updatePet(body: Pet): Promise { + await this.updatePetRaw({ body: body }); + } + + /** + * Updates a pet in the store with form data + */ + async updatePetWithFormRaw(requestParameters: UpdatePetWithFormRequest): Promise> { + if (requestParameters.petId === null || requestParameters.petId === undefined) { + throw new runtime.RequiredError('petId','Required parameter requestParameters.petId was null or undefined when calling updatePetWithForm.'); + } + + const queryParameters: any = {}; + + const headerParameters: runtime.HTTPHeaders = {}; + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); + } + + const consumes: runtime.Consume[] = [ + { contentType: 'application/x-www-form-urlencoded' }, + ]; + // @ts-ignore: canConsumeForm may be unused + const canConsumeForm = runtime.canConsumeForm(consumes); + + let formParams: { append(param: string, value: any): any }; + let useForm = false; + if (useForm) { + formParams = new FormData(); + } else { + formParams = new URLSearchParams(); + } + + if (requestParameters.name !== undefined) { + formParams.append('name', requestParameters.name as any); + } + + if (requestParameters.status !== undefined) { + formParams.append('status', requestParameters.status as any); + } + + const response = await this.request({ + path: `/pet/{petId}`.replace(`{${"petId"}}`, encodeURIComponent(String(requestParameters.petId))), + method: 'POST', + headers: headerParameters, + query: queryParameters, + body: formParams, + }); + + return new runtime.VoidApiResponse(response); + } + + /** + * Updates a pet in the store with form data + */ + async updatePetWithForm(petId: number, name?: string, status?: string): Promise { + await this.updatePetWithFormRaw({ petId: petId, name: name, status: status }); + } + + /** + * uploads an image + */ + async uploadFileRaw(requestParameters: UploadFileRequest): Promise> { + if (requestParameters.petId === null || requestParameters.petId === undefined) { + throw new runtime.RequiredError('petId','Required parameter requestParameters.petId was null or undefined when calling uploadFile.'); + } + + const queryParameters: any = {}; + + const headerParameters: runtime.HTTPHeaders = {}; + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); + } + + const consumes: runtime.Consume[] = [ + { contentType: 'multipart/form-data' }, + ]; + // @ts-ignore: canConsumeForm may be unused + const canConsumeForm = runtime.canConsumeForm(consumes); + + let formParams: { append(param: string, value: any): any }; + let useForm = false; + // use FormData to transmit files using content-type "multipart/form-data" + useForm = canConsumeForm; + if (useForm) { + formParams = new FormData(); + } else { + formParams = new URLSearchParams(); + } + + if (requestParameters.additionalMetadata !== undefined) { + formParams.append('additionalMetadata', requestParameters.additionalMetadata as any); + } + + if (requestParameters.file !== undefined) { + formParams.append('file', requestParameters.file as any); + } + + const response = await this.request({ + path: `/pet/{petId}/uploadImage`.replace(`{${"petId"}}`, encodeURIComponent(String(requestParameters.petId))), + method: 'POST', + headers: headerParameters, + query: queryParameters, + body: formParams, + }); + + return new runtime.JSONApiResponse(response, (jsonValue) => ModelApiResponseFromJSON(jsonValue)); + } + + /** + * uploads an image + */ + async uploadFile(petId: number, additionalMetadata?: string, file?: Blob): Promise { + const response = await this.uploadFileRaw({ petId: petId, additionalMetadata: additionalMetadata, file: file }); + return await response.value(); + } + +} + +/** + * @export + * @enum {string} + */ +export enum FindPetsByStatusStatusEnum { + Available = 'available', + Pending = 'pending', + Sold = 'sold' +} diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/apis/PetApiSagas.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/apis/PetApiSagas.ts new file mode 100644 index 00000000000..202ec780b63 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/apis/PetApiSagas.ts @@ -0,0 +1,565 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * 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. + */ + + +import {Api} from './'; +import {List} from 'immutable'; +import {all, fork, put, takeLatest} from "redux-saga/effects"; +import {apiCall, createSagaAction as originalCreateSagaAction, BaseEntitySupportPayloadApiAction, BasePayloadApiAction, NormalizedRecordEntities, normalizedEntities} from "../runtimeSagasAndRecords"; +import {Action} from "redux-ts-simple"; + +import { + Category, + CategoryRecord, + categoryRecordUtils, + FindPetsByStatusResponse, + FindPetsByStatusResponseRecord, + findPetsByStatusResponseRecordUtils, + FindPetsByUserResponse, + FindPetsByUserResponseRecord, + findPetsByUserResponseRecordUtils, + ModelApiResponse, + ModelApiResponseRecord, + modelApiResponseRecordUtils, + Pet, + PetRecord, + petRecordUtils, + UserRecord, +} from '../models'; + +import { + FindPetsByStatusStatusEnum, +} from './PetApi'; + +const createSagaAction = (type: string) => originalCreateSagaAction(type, {namespace: "api_petApi"}); + +export const petApiSagaMap = new Map Generator>([ + ["addPet", addPetSaga], + ["deletePet", deletePetSaga], + ["findPetsByIds", findPetsByIdsSaga], + ["findPetsByStatus", findPetsByStatusSaga], + ["findPetsByTags", findPetsByTagsSaga], + ["findPetsByUserIds", findPetsByUserIdsSaga], + ["getPetById", getPetByIdSaga], + ["updatePet", updatePetSaga], + ["updatePetWithForm", updatePetWithFormSaga], + ["uploadFile", uploadFileSaga], + ] +); + +export function *petApiAllSagas() { + yield all([...petApiSagaMap.values()].map(actionSaga => fork(actionSaga))); +} + +//region addPet + +export interface PayloadAddPet extends PayloadAddPetRequest, BasePayloadApiAction { +} + +export interface PayloadAddPetRequest { + dummyCat: CategoryRecord; +} + +export const addPetRequest = createSagaAction("addPetRequest"); +export const addPetSuccess = createSagaAction("addPetSuccess"); +export const addPetFailure = createSagaAction<{error: any, requestPayload: PayloadAddPet}>("addPetFailure"); + +export const addPet = createSagaAction("addPet"); + +export function *addPetSaga() { + yield takeLatest(addPet, addPetSagaImp); +} + +export function *addPetSagaImp(_action_: Action) { + const {markErrorsAsHandled, ..._payloadRest_} = _action_.payload; + try { + const { + dummyCat, + } = _payloadRest_; + + yield put(addPetRequest(_action_.payload)); + + const response = yield apiCall(Api.petApi, Api.petApi.addPet, + categoryRecordUtils.toApi(dummyCat), + ); + + yield put(addPetSuccess()); + + return undefined; + } catch (error) { + if (markErrorsAsHandled) {error.wasHandled = true; } + yield put(addPetFailure({error, requestPayload: _action_.payload})); + return error; + } +} +//endregion +//region deletePet + +export interface PayloadDeletePet extends PayloadDeletePetRequest, BasePayloadApiAction { +} + +export interface PayloadDeletePetRequest { + petId: string; + apiKey?: string; +} + +export const deletePetRequest = createSagaAction("deletePetRequest"); +export const deletePetSuccess = createSagaAction("deletePetSuccess"); +export const deletePetFailure = createSagaAction<{error: any, requestPayload: PayloadDeletePet}>("deletePetFailure"); + +export const deletePet = createSagaAction("deletePet"); + +export function *deletePetSaga() { + yield takeLatest(deletePet, deletePetSagaImp); +} + +export function *deletePetSagaImp(_action_: Action) { + const {markErrorsAsHandled, ..._payloadRest_} = _action_.payload; + try { + const { + petId, + apiKey, + } = _payloadRest_; + + yield put(deletePetRequest(_action_.payload)); + + const response = yield apiCall(Api.petApi, Api.petApi.deletePet, + parseFloat(petId), + apiKey, + ); + + yield put(deletePetSuccess()); + + return undefined; + } catch (error) { + if (markErrorsAsHandled) {error.wasHandled = true; } + yield put(deletePetFailure({error, requestPayload: _action_.payload})); + return error; + } +} +//endregion +//region findPetsByIds + +export interface PayloadFindPetsByIds extends PayloadFindPetsByIdsRequest, BaseEntitySupportPayloadApiAction { +} + +export interface PayloadFindPetsByIdsRequest { + ids: List; +} + +export const findPetsByIdsRequest = createSagaAction("findPetsByIdsRequest"); +export const findPetsByIdsSuccess = createSagaAction>("findPetsByIdsSuccess"); +export const findPetsByIdsSuccess_Entities = createSagaAction("findPetsByIdsSuccess_Entities"); +export const findPetsByIdsFailure = createSagaAction<{error: any, requestPayload: PayloadFindPetsByIds}>("findPetsByIdsFailure"); + +export const findPetsByIds = createSagaAction("findPetsByIds"); + +export function *findPetsByIdsSaga() { + yield takeLatest(findPetsByIds, findPetsByIdsSagaImp); +} + +export function *findPetsByIdsSagaImp(_action_: Action) { + const {markErrorsAsHandled, ..._payloadRest_} = _action_.payload; + try { + const {toEntities, toInlined = !toEntities, ...requestPayload} = _payloadRest_; + const { + ids, + } = _payloadRest_; + + yield put(findPetsByIdsRequest(requestPayload)); + + const response: Required> = yield apiCall(Api.petApi, Api.petApi.findPetsByIds, + ids.map(p => parseFloat(p)).toArray(), + ); + + let successReturnValue: any = undefined; + if (toEntities) { + successReturnValue = petRecordUtils.fromApiArrayAsEntities(response); + yield put(normalizedEntities(successReturnValue)); + yield put(findPetsByIdsSuccess_Entities(successReturnValue)); + } + if (toInlined) { + successReturnValue = petRecordUtils.fromApiArray(response); + yield put(findPetsByIdsSuccess(successReturnValue)); + } + + return successReturnValue; + } catch (error) { + if (markErrorsAsHandled) {error.wasHandled = true; } + yield put(findPetsByIdsFailure({error, requestPayload: _action_.payload})); + return error; + } +} +//endregion +//region findPetsByStatus + +export interface PayloadFindPetsByStatus extends PayloadFindPetsByStatusRequest, BaseEntitySupportPayloadApiAction { +} + +export interface PayloadFindPetsByStatusRequest { + status: List; +} + +export const findPetsByStatusRequest = createSagaAction("findPetsByStatusRequest"); +export const findPetsByStatusSuccess = createSagaAction>("findPetsByStatusSuccess"); +export const findPetsByStatusSuccess_Entities = createSagaAction("findPetsByStatusSuccess_Entities"); +export const findPetsByStatusFailure = createSagaAction<{error: any, requestPayload: PayloadFindPetsByStatus}>("findPetsByStatusFailure"); + +export const findPetsByStatus = createSagaAction("findPetsByStatus"); + +export function *findPetsByStatusSaga() { + yield takeLatest(findPetsByStatus, findPetsByStatusSagaImp); +} + +export function *findPetsByStatusSagaImp(_action_: Action) { + const {markErrorsAsHandled, ..._payloadRest_} = _action_.payload; + try { + const {toEntities, toInlined = !toEntities, ...requestPayload} = _payloadRest_; + const { + status, + } = _payloadRest_; + + yield put(findPetsByStatusRequest(requestPayload)); + + const response: Required = yield apiCall(Api.petApi, Api.petApi.findPetsByStatus, + status.toJS(), + ); + + let successReturnValue: any = undefined; + if (toEntities) { + successReturnValue = findPetsByStatusResponseRecordUtils.fromApiPassthroughAsEntities(response); + yield put(normalizedEntities(successReturnValue)); + yield put(findPetsByStatusSuccess_Entities(successReturnValue)); + } + if (toInlined) { + successReturnValue = findPetsByStatusResponseRecordUtils.fromApiPassthrough(response); + yield put(findPetsByStatusSuccess(successReturnValue)); + } + + return successReturnValue; + } catch (error) { + if (markErrorsAsHandled) {error.wasHandled = true; } + yield put(findPetsByStatusFailure({error, requestPayload: _action_.payload})); + return error; + } +} +//endregion +//region findPetsByTags + +export interface PayloadFindPetsByTags extends PayloadFindPetsByTagsRequest, BaseEntitySupportPayloadApiAction { +} + +export interface PayloadFindPetsByTagsRequest { + tags: List; +} + +export const findPetsByTagsRequest = createSagaAction("findPetsByTagsRequest"); +export const findPetsByTagsSuccess = createSagaAction>("findPetsByTagsSuccess"); +export const findPetsByTagsSuccess_Entities = createSagaAction("findPetsByTagsSuccess_Entities"); +export const findPetsByTagsFailure = createSagaAction<{error: any, requestPayload: PayloadFindPetsByTags}>("findPetsByTagsFailure"); + +export const findPetsByTags = createSagaAction("findPetsByTags"); + +export function *findPetsByTagsSaga() { + yield takeLatest(findPetsByTags, findPetsByTagsSagaImp); +} + +export function *findPetsByTagsSagaImp(_action_: Action) { + const {markErrorsAsHandled, ..._payloadRest_} = _action_.payload; + try { + const {toEntities, toInlined = !toEntities, ...requestPayload} = _payloadRest_; + const { + tags, + } = _payloadRest_; + + yield put(findPetsByTagsRequest(requestPayload)); + + const response: Required> = yield apiCall(Api.petApi, Api.petApi.findPetsByTags, + tags.toJS(), + ); + + let successReturnValue: any = undefined; + if (toEntities) { + successReturnValue = petRecordUtils.fromApiArrayAsEntities(response); + yield put(normalizedEntities(successReturnValue)); + yield put(findPetsByTagsSuccess_Entities(successReturnValue)); + } + if (toInlined) { + successReturnValue = petRecordUtils.fromApiArray(response); + yield put(findPetsByTagsSuccess(successReturnValue)); + } + + return successReturnValue; + } catch (error) { + if (markErrorsAsHandled) {error.wasHandled = true; } + yield put(findPetsByTagsFailure({error, requestPayload: _action_.payload})); + return error; + } +} +//endregion +//region findPetsByUserIds + +export interface PayloadFindPetsByUserIds extends PayloadFindPetsByUserIdsRequest, BaseEntitySupportPayloadApiAction { +} + +export interface PayloadFindPetsByUserIdsRequest { + ids: List; +} + +export const findPetsByUserIdsRequest = createSagaAction("findPetsByUserIdsRequest"); +export const findPetsByUserIdsSuccess = createSagaAction>("findPetsByUserIdsSuccess"); +export const findPetsByUserIdsSuccess_Entities = createSagaAction("findPetsByUserIdsSuccess_Entities"); +export const findPetsByUserIdsFailure = createSagaAction<{error: any, requestPayload: PayloadFindPetsByUserIds}>("findPetsByUserIdsFailure"); + +export const findPetsByUserIds = createSagaAction("findPetsByUserIds"); + +export function *findPetsByUserIdsSaga() { + yield takeLatest(findPetsByUserIds, findPetsByUserIdsSagaImp); +} + +export function *findPetsByUserIdsSagaImp(_action_: Action) { + const {markErrorsAsHandled, ..._payloadRest_} = _action_.payload; + try { + const {toEntities, toInlined = !toEntities, ...requestPayload} = _payloadRest_; + const { + ids, + } = _payloadRest_; + + yield put(findPetsByUserIdsRequest(requestPayload)); + + const response: Required = yield apiCall(Api.petApi, Api.petApi.findPetsByUserIds, + ids.map(p => parseFloat(p)).toArray(), + ); + + let successReturnValue: any = undefined; + if (toEntities) { + successReturnValue = findPetsByUserResponseRecordUtils.fromApiPassthroughAsEntities(response); + yield put(normalizedEntities(successReturnValue)); + yield put(findPetsByUserIdsSuccess_Entities(successReturnValue)); + } + if (toInlined) { + successReturnValue = findPetsByUserResponseRecordUtils.fromApiPassthrough(response); + yield put(findPetsByUserIdsSuccess(successReturnValue)); + } + + return successReturnValue; + } catch (error) { + if (markErrorsAsHandled) {error.wasHandled = true; } + yield put(findPetsByUserIdsFailure({error, requestPayload: _action_.payload})); + return error; + } +} +//endregion +//region getPetById + +export interface PayloadGetPetById extends PayloadGetPetByIdRequest, BaseEntitySupportPayloadApiAction { +} + +export interface PayloadGetPetByIdRequest { + petId: string; +} + +export const getPetByIdRequest = createSagaAction("getPetByIdRequest"); +export const getPetByIdSuccess = createSagaAction("getPetByIdSuccess"); +export const getPetByIdSuccess_Entities = createSagaAction("getPetByIdSuccess_Entities"); +export const getPetByIdFailure = createSagaAction<{error: any, requestPayload: PayloadGetPetById}>("getPetByIdFailure"); + +export const getPetById = createSagaAction("getPetById"); + +export function *getPetByIdSaga() { + yield takeLatest(getPetById, getPetByIdSagaImp); +} + +export function *getPetByIdSagaImp(_action_: Action) { + const {markErrorsAsHandled, ..._payloadRest_} = _action_.payload; + try { + const {toEntities, toInlined = !toEntities, ...requestPayload} = _payloadRest_; + const { + petId, + } = _payloadRest_; + + yield put(getPetByIdRequest(requestPayload)); + + const response: Required = yield apiCall(Api.petApi, Api.petApi.getPetById, + parseFloat(petId), + ); + + let successReturnValue: any = undefined; + if (toEntities) { + successReturnValue = petRecordUtils.fromApiArrayAsEntities([response]); + yield put(normalizedEntities(successReturnValue)); + yield put(getPetByIdSuccess_Entities(successReturnValue)); + } + if (toInlined) { + successReturnValue = petRecordUtils.fromApi(response); + yield put(getPetByIdSuccess(successReturnValue)); + } + + return successReturnValue; + } catch (error) { + if (markErrorsAsHandled) {error.wasHandled = true; } + yield put(getPetByIdFailure({error, requestPayload: _action_.payload})); + return error; + } +} +//endregion +//region updatePet + +export interface PayloadUpdatePet extends PayloadUpdatePetRequest, BasePayloadApiAction { +} + +export interface PayloadUpdatePetRequest { + body: PetRecord; +} + +export const updatePetRequest = createSagaAction("updatePetRequest"); +export const updatePetSuccess = createSagaAction("updatePetSuccess"); +export const updatePetFailure = createSagaAction<{error: any, requestPayload: PayloadUpdatePet}>("updatePetFailure"); + +export const updatePet = createSagaAction("updatePet"); + +export function *updatePetSaga() { + yield takeLatest(updatePet, updatePetSagaImp); +} + +export function *updatePetSagaImp(_action_: Action) { + const {markErrorsAsHandled, ..._payloadRest_} = _action_.payload; + try { + const { + body, + } = _payloadRest_; + + yield put(updatePetRequest(_action_.payload)); + + const response = yield apiCall(Api.petApi, Api.petApi.updatePet, + petRecordUtils.toApi(body), + ); + + yield put(updatePetSuccess()); + + return undefined; + } catch (error) { + if (markErrorsAsHandled) {error.wasHandled = true; } + yield put(updatePetFailure({error, requestPayload: _action_.payload})); + return error; + } +} +//endregion +//region updatePetWithForm + +export interface PayloadUpdatePetWithForm extends PayloadUpdatePetWithFormRequest, BasePayloadApiAction { +} + +export interface PayloadUpdatePetWithFormRequest { + petId: string; + name?: string; + status?: string; +} + +export const updatePetWithFormRequest = createSagaAction("updatePetWithFormRequest"); +export const updatePetWithFormSuccess = createSagaAction("updatePetWithFormSuccess"); +export const updatePetWithFormFailure = createSagaAction<{error: any, requestPayload: PayloadUpdatePetWithForm}>("updatePetWithFormFailure"); + +export const updatePetWithForm = createSagaAction("updatePetWithForm"); + +export function *updatePetWithFormSaga() { + yield takeLatest(updatePetWithForm, updatePetWithFormSagaImp); +} + +export function *updatePetWithFormSagaImp(_action_: Action) { + const {markErrorsAsHandled, ..._payloadRest_} = _action_.payload; + try { + const { + petId, + name, + status, + } = _payloadRest_; + + yield put(updatePetWithFormRequest(_action_.payload)); + + const response = yield apiCall(Api.petApi, Api.petApi.updatePetWithForm, + parseFloat(petId), + name, + status, + ); + + yield put(updatePetWithFormSuccess()); + + return undefined; + } catch (error) { + if (markErrorsAsHandled) {error.wasHandled = true; } + yield put(updatePetWithFormFailure({error, requestPayload: _action_.payload})); + return error; + } +} +//endregion +//region uploadFile + +export interface PayloadUploadFile extends PayloadUploadFileRequest, BaseEntitySupportPayloadApiAction { +} + +export interface PayloadUploadFileRequest { + petId: string; + additionalMetadata?: string; + file?: Blob; +} + +export const uploadFileRequest = createSagaAction("uploadFileRequest"); +export const uploadFileSuccess = createSagaAction("uploadFileSuccess"); +export const uploadFileSuccess_Entities = createSagaAction("uploadFileSuccess_Entities"); +export const uploadFileFailure = createSagaAction<{error: any, requestPayload: PayloadUploadFile}>("uploadFileFailure"); + +export const uploadFile = createSagaAction("uploadFile"); + +export function *uploadFileSaga() { + yield takeLatest(uploadFile, uploadFileSagaImp); +} + +export function *uploadFileSagaImp(_action_: Action) { + const {markErrorsAsHandled, ..._payloadRest_} = _action_.payload; + try { + const {toEntities, toInlined = !toEntities, ...requestPayload} = _payloadRest_; + const { + petId, + additionalMetadata, + file, + } = _payloadRest_; + + yield put(uploadFileRequest(requestPayload)); + + const response: Required = yield apiCall(Api.petApi, Api.petApi.uploadFile, + parseFloat(petId), + additionalMetadata, + file, + ); + + let successReturnValue: any = undefined; + if (toEntities) { + successReturnValue = modelApiResponseRecordUtils.fromApiArrayAsEntities([response]); + yield put(normalizedEntities(successReturnValue)); + yield put(uploadFileSuccess_Entities(successReturnValue)); + } + if (toInlined) { + successReturnValue = modelApiResponseRecordUtils.fromApi(response); + yield put(uploadFileSuccess(successReturnValue)); + } + + return successReturnValue; + } catch (error) { + if (markErrorsAsHandled) {error.wasHandled = true; } + yield put(uploadFileFailure({error, requestPayload: _action_.payload})); + return error; + } +} +//endregion diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/apis/PetPartApi.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/apis/PetPartApi.ts new file mode 100644 index 00000000000..535059660a0 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/apis/PetPartApi.ts @@ -0,0 +1,136 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * 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. + */ + + +import * as runtime from '../runtime'; +import { + GetMatchingPartsResponse, + GetMatchingPartsResponseFromJSON, + GetMatchingPartsResponseToJSON, + GetPetPartTypeResponse, + GetPetPartTypeResponseFromJSON, + GetPetPartTypeResponseToJSON, +} from '../models'; + +export interface GetFakePetPartTypeRequest { + fakePetPartId: number; +} + +export interface GetMatchingPartsRequest { + fakePetPartId: number; + _long: boolean; + smooth: boolean; + _short: boolean; + name?: string; + connectedPart?: string; +} + +/** + * + */ +export class PetPartApi extends runtime.BaseAPI { + + /** + * Returns single pet part type for the petPart id. + */ + async getFakePetPartTypeRaw(requestParameters: GetFakePetPartTypeRequest): Promise> { + if (requestParameters.fakePetPartId === null || requestParameters.fakePetPartId === undefined) { + throw new runtime.RequiredError('fakePetPartId','Required parameter requestParameters.fakePetPartId was null or undefined when calling getFakePetPartType.'); + } + + const queryParameters: any = {}; + + const headerParameters: runtime.HTTPHeaders = {}; + + const response = await this.request({ + path: `/fake_petParts/{fake_petPart-id}/part-type`.replace(`{${"fake_petPart-id"}}`, encodeURIComponent(String(requestParameters.fakePetPartId))), + method: 'GET', + headers: headerParameters, + query: queryParameters, + }); + + return new runtime.JSONApiResponse(response, (jsonValue) => GetPetPartTypeResponseFromJSON(jsonValue)); + } + + /** + * Returns single pet part type for the petPart id. + */ + async getFakePetPartType(fakePetPartId: number): Promise { + const response = await this.getFakePetPartTypeRaw({ fakePetPartId: fakePetPartId }); + return await response.value(); + } + + /** + * Get the matching parts for the given pet part. + */ + async getMatchingPartsRaw(requestParameters: GetMatchingPartsRequest): Promise> { + if (requestParameters.fakePetPartId === null || requestParameters.fakePetPartId === undefined) { + throw new runtime.RequiredError('fakePetPartId','Required parameter requestParameters.fakePetPartId was null or undefined when calling getMatchingParts.'); + } + + if (requestParameters._long === null || requestParameters._long === undefined) { + throw new runtime.RequiredError('_long','Required parameter requestParameters._long was null or undefined when calling getMatchingParts.'); + } + + if (requestParameters.smooth === null || requestParameters.smooth === undefined) { + throw new runtime.RequiredError('smooth','Required parameter requestParameters.smooth was null or undefined when calling getMatchingParts.'); + } + + if (requestParameters._short === null || requestParameters._short === undefined) { + throw new runtime.RequiredError('_short','Required parameter requestParameters._short was null or undefined when calling getMatchingParts.'); + } + + const queryParameters: any = {}; + + if (requestParameters._long !== undefined) { + queryParameters['long'] = requestParameters._long; + } + + if (requestParameters.smooth !== undefined) { + queryParameters['smooth'] = requestParameters.smooth; + } + + if (requestParameters.name !== undefined) { + queryParameters['name'] = requestParameters.name; + } + + if (requestParameters.connectedPart !== undefined) { + queryParameters['connected-part'] = requestParameters.connectedPart; + } + + if (requestParameters._short !== undefined) { + queryParameters['short'] = requestParameters._short; + } + + const headerParameters: runtime.HTTPHeaders = {}; + + const response = await this.request({ + path: `/fake_petParts/{fake_petPart-id}/matching-parts`.replace(`{${"fake_petPart-id"}}`, encodeURIComponent(String(requestParameters.fakePetPartId))), + method: 'GET', + headers: headerParameters, + query: queryParameters, + }); + + return new runtime.JSONApiResponse(response, (jsonValue) => GetMatchingPartsResponseFromJSON(jsonValue)); + } + + /** + * Get the matching parts for the given pet part. + */ + async getMatchingParts(fakePetPartId: number, _long: boolean, smooth: boolean, _short: boolean, name?: string, connectedPart?: string): Promise { + const response = await this.getMatchingPartsRaw({ fakePetPartId: fakePetPartId, _long: _long, smooth: smooth, _short: _short, name: name, connectedPart: connectedPart }); + return await response.value(); + } + +} diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/apis/PetPartApiSagas.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/apis/PetPartApiSagas.ts new file mode 100644 index 00000000000..3111c06e17e --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/apis/PetPartApiSagas.ts @@ -0,0 +1,156 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * 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. + */ + + +import {Api} from './'; +import {List} from 'immutable'; +import {all, fork, put, takeLatest} from "redux-saga/effects"; +import {apiCall, createSagaAction as originalCreateSagaAction, BaseEntitySupportPayloadApiAction, BasePayloadApiAction, NormalizedRecordEntities, normalizedEntities} from "../runtimeSagasAndRecords"; +import {Action} from "redux-ts-simple"; + +import { + GetMatchingPartsResponse, + GetMatchingPartsResponseRecord, + getMatchingPartsResponseRecordUtils, + GetPetPartTypeResponse, + GetPetPartTypeResponseRecord, + getPetPartTypeResponseRecordUtils, + MatchingPartsRecord, + PetPartType, +} from '../models'; + +const createSagaAction = (type: string) => originalCreateSagaAction(type, {namespace: "api_petPartApi"}); + +export const petPartApiSagaMap = new Map Generator>([ + ["getFakePetPartType", getFakePetPartTypeSaga], + ["getMatchingParts", getMatchingPartsSaga], + ] +); + +export function *petPartApiAllSagas() { + yield all([...petPartApiSagaMap.values()].map(actionSaga => fork(actionSaga))); +} + +//region getFakePetPartType + +export interface PayloadGetFakePetPartType extends PayloadGetFakePetPartTypeRequest, BasePayloadApiAction { +} + +export interface PayloadGetFakePetPartTypeRequest { + fakePetPartId: string; +} + +export const getFakePetPartTypeRequest = createSagaAction("getFakePetPartTypeRequest"); +export const getFakePetPartTypeSuccess = createSagaAction("getFakePetPartTypeSuccess"); +export const getFakePetPartTypeFailure = createSagaAction<{error: any, requestPayload: PayloadGetFakePetPartType}>("getFakePetPartTypeFailure"); + +export const getFakePetPartType = createSagaAction("getFakePetPartType"); + +export function *getFakePetPartTypeSaga() { + yield takeLatest(getFakePetPartType, getFakePetPartTypeSagaImp); +} + +export function *getFakePetPartTypeSagaImp(_action_: Action) { + const {markErrorsAsHandled, ..._payloadRest_} = _action_.payload; + try { + const { + fakePetPartId, + } = _payloadRest_; + + yield put(getFakePetPartTypeRequest(_action_.payload)); + + const response: Required = yield apiCall(Api.petPartApi, Api.petPartApi.getFakePetPartType, + parseFloat(fakePetPartId), + ); + + let successReturnValue: any = undefined; + successReturnValue = getPetPartTypeResponseRecordUtils.fromApiPassthrough(response); + yield put(getFakePetPartTypeSuccess(successReturnValue)); + + return successReturnValue; + } catch (error) { + if (markErrorsAsHandled) {error.wasHandled = true; } + yield put(getFakePetPartTypeFailure({error, requestPayload: _action_.payload})); + return error; + } +} +//endregion +//region getMatchingParts + +export interface PayloadGetMatchingParts extends PayloadGetMatchingPartsRequest, BaseEntitySupportPayloadApiAction { +} + +export interface PayloadGetMatchingPartsRequest { + fakePetPartId: string; + _long: boolean; + smooth: boolean; + _short: boolean; + name?: string; + connectedPart?: string; +} + +export const getMatchingPartsRequest = createSagaAction("getMatchingPartsRequest"); +export const getMatchingPartsSuccess = createSagaAction("getMatchingPartsSuccess"); +export const getMatchingPartsSuccess_Entities = createSagaAction("getMatchingPartsSuccess_Entities"); +export const getMatchingPartsFailure = createSagaAction<{error: any, requestPayload: PayloadGetMatchingParts}>("getMatchingPartsFailure"); + +export const getMatchingParts = createSagaAction("getMatchingParts"); + +export function *getMatchingPartsSaga() { + yield takeLatest(getMatchingParts, getMatchingPartsSagaImp); +} + +export function *getMatchingPartsSagaImp(_action_: Action) { + const {markErrorsAsHandled, ..._payloadRest_} = _action_.payload; + try { + const {toEntities, toInlined = !toEntities, ...requestPayload} = _payloadRest_; + const { + fakePetPartId, + _long, + smooth, + _short, + name, + connectedPart, + } = _payloadRest_; + + yield put(getMatchingPartsRequest(requestPayload)); + + const response: Required = yield apiCall(Api.petPartApi, Api.petPartApi.getMatchingParts, + parseFloat(fakePetPartId), + _long, + smooth, + _short, + name, + connectedPart, + ); + + let successReturnValue: any = undefined; + if (toEntities) { + successReturnValue = getMatchingPartsResponseRecordUtils.fromApiPassthroughAsEntities(response); + yield put(normalizedEntities(successReturnValue)); + yield put(getMatchingPartsSuccess_Entities(successReturnValue)); + } + if (toInlined) { + successReturnValue = getMatchingPartsResponseRecordUtils.fromApiPassthrough(response); + yield put(getMatchingPartsSuccess(successReturnValue)); + } + + return successReturnValue; + } catch (error) { + if (markErrorsAsHandled) {error.wasHandled = true; } + yield put(getMatchingPartsFailure({error, requestPayload: _action_.payload})); + return error; + } +} +//endregion diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/apis/SagaApiManager.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/apis/SagaApiManager.ts new file mode 100644 index 00000000000..21a49677e50 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/apis/SagaApiManager.ts @@ -0,0 +1,36 @@ +import { + Configuration, + ConfigurationParameters, +} from "../"; + +import { + BehaviorApi, + PetApi, + PetPartApi, + StoreApi, + UserApi, +} from "./"; + +export class Api { + public static behaviorApi: BehaviorApi; + public static petApi: PetApi; + public static petPartApi: PetPartApi; + public static storeApi: StoreApi; + public static userApi: UserApi; + + public static init(apiBasePath: string) { + const apiBaseConfig: ConfigurationParameters = { + basePath: apiBasePath, + credentials: "include", + headers: { + 'Cache-Control': 'no-cache, no-store' // this is needed to prevent stalling issues in Chrome. Also it is a good behavior for api calls. + } + }; + + Api.behaviorApi = new BehaviorApi(new Configuration(apiBaseConfig)); + Api.petApi = new PetApi(new Configuration(apiBaseConfig)); + Api.petPartApi = new PetPartApi(new Configuration(apiBaseConfig)); + Api.storeApi = new StoreApi(new Configuration(apiBaseConfig)); + Api.userApi = new UserApi(new Configuration(apiBaseConfig)); + } +} \ No newline at end of file diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/apis/StoreApi.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/apis/StoreApi.ts new file mode 100644 index 00000000000..51382e766aa --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/apis/StoreApi.ts @@ -0,0 +1,168 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * 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. + */ + + +import * as runtime from '../runtime'; +import { + Order, + OrderFromJSON, + OrderToJSON, +} from '../models'; + +export interface DeleteOrderRequest { + orderId: string; +} + +export interface GetOrderByIdRequest { + orderId: number; +} + +export interface PlaceOrderRequest { + body: Order; +} + +/** + * + */ +export class StoreApi extends runtime.BaseAPI { + + /** + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * Delete purchase order by ID + */ + async deleteOrderRaw(requestParameters: DeleteOrderRequest): Promise> { + if (requestParameters.orderId === null || requestParameters.orderId === undefined) { + throw new runtime.RequiredError('orderId','Required parameter requestParameters.orderId was null or undefined when calling deleteOrder.'); + } + + const queryParameters: any = {}; + + const headerParameters: runtime.HTTPHeaders = {}; + + const response = await this.request({ + path: `/store/order/{orderId}`.replace(`{${"orderId"}}`, encodeURIComponent(String(requestParameters.orderId))), + method: 'DELETE', + headers: headerParameters, + query: queryParameters, + }); + + return new runtime.VoidApiResponse(response); + } + + /** + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * Delete purchase order by ID + */ + async deleteOrder(orderId: string): Promise { + await this.deleteOrderRaw({ orderId: orderId }); + } + + /** + * Returns a map of status codes to quantities + * Returns pet inventories by status + */ + async getInventoryRaw(): Promise> { + const queryParameters: any = {}; + + const headerParameters: runtime.HTTPHeaders = {}; + + if (this.configuration && this.configuration.apiKey) { + headerParameters["api_key"] = this.configuration.apiKey("api_key"); // api_key authentication + } + + const response = await this.request({ + path: `/store/inventory`, + method: 'GET', + headers: headerParameters, + query: queryParameters, + }); + + return new runtime.JSONApiResponse(response); + } + + /** + * Returns a map of status codes to quantities + * Returns pet inventories by status + */ + async getInventory(): Promise<{ [key: string]: number; }> { + const response = await this.getInventoryRaw(); + return await response.value(); + } + + /** + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + * Find purchase order by ID + */ + async getOrderByIdRaw(requestParameters: GetOrderByIdRequest): Promise> { + if (requestParameters.orderId === null || requestParameters.orderId === undefined) { + throw new runtime.RequiredError('orderId','Required parameter requestParameters.orderId was null or undefined when calling getOrderById.'); + } + + const queryParameters: any = {}; + + const headerParameters: runtime.HTTPHeaders = {}; + + const response = await this.request({ + path: `/store/order/{orderId}`.replace(`{${"orderId"}}`, encodeURIComponent(String(requestParameters.orderId))), + method: 'GET', + headers: headerParameters, + query: queryParameters, + }); + + return new runtime.JSONApiResponse(response, (jsonValue) => OrderFromJSON(jsonValue)); + } + + /** + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + * Find purchase order by ID + */ + async getOrderById(orderId: number): Promise { + const response = await this.getOrderByIdRaw({ orderId: orderId }); + return await response.value(); + } + + /** + * Place an order for a pet + */ + async placeOrderRaw(requestParameters: PlaceOrderRequest): Promise> { + if (requestParameters.body === null || requestParameters.body === undefined) { + throw new runtime.RequiredError('body','Required parameter requestParameters.body was null or undefined when calling placeOrder.'); + } + + const queryParameters: any = {}; + + const headerParameters: runtime.HTTPHeaders = {}; + + headerParameters['Content-Type'] = 'application/json'; + + const response = await this.request({ + path: `/store/order`, + method: 'POST', + headers: headerParameters, + query: queryParameters, + body: OrderToJSON(requestParameters.body), + }); + + return new runtime.JSONApiResponse(response, (jsonValue) => OrderFromJSON(jsonValue)); + } + + /** + * Place an order for a pet + */ + async placeOrder(body: Order): Promise { + const response = await this.placeOrderRaw({ body: body }); + return await response.value(); + } + +} diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/apis/StoreApiSagas.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/apis/StoreApiSagas.ts new file mode 100644 index 00000000000..9752a7ea0fb --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/apis/StoreApiSagas.ts @@ -0,0 +1,225 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * 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. + */ + + +import {Api} from './'; +import {List} from 'immutable'; +import {all, fork, put, takeLatest} from "redux-saga/effects"; +import {apiCall, createSagaAction as originalCreateSagaAction, BaseEntitySupportPayloadApiAction, BasePayloadApiAction, NormalizedRecordEntities, normalizedEntities} from "../runtimeSagasAndRecords"; +import {Action} from "redux-ts-simple"; + +import { + Order, + OrderRecord, + orderRecordUtils, +} from '../models'; + +const createSagaAction = (type: string) => originalCreateSagaAction(type, {namespace: "api_storeApi"}); + +export const storeApiSagaMap = new Map Generator>([ + ["deleteOrder", deleteOrderSaga], + ["getInventory", getInventorySaga], + ["getOrderById", getOrderByIdSaga], + ["placeOrder", placeOrderSaga], + ] +); + +export function *storeApiAllSagas() { + yield all([...storeApiSagaMap.values()].map(actionSaga => fork(actionSaga))); +} + +//region deleteOrder + +export interface PayloadDeleteOrder extends PayloadDeleteOrderRequest, BasePayloadApiAction { +} + +export interface PayloadDeleteOrderRequest { + orderId: string; +} + +export const deleteOrderRequest = createSagaAction("deleteOrderRequest"); +export const deleteOrderSuccess = createSagaAction("deleteOrderSuccess"); +export const deleteOrderFailure = createSagaAction<{error: any, requestPayload: PayloadDeleteOrder}>("deleteOrderFailure"); + +export const deleteOrder = createSagaAction("deleteOrder"); + +export function *deleteOrderSaga() { + yield takeLatest(deleteOrder, deleteOrderSagaImp); +} + +export function *deleteOrderSagaImp(_action_: Action) { + const {markErrorsAsHandled, ..._payloadRest_} = _action_.payload; + try { + const { + orderId, + } = _payloadRest_; + + yield put(deleteOrderRequest(_action_.payload)); + + const response = yield apiCall(Api.storeApi, Api.storeApi.deleteOrder, + orderId, + ); + + yield put(deleteOrderSuccess()); + + return undefined; + } catch (error) { + if (markErrorsAsHandled) {error.wasHandled = true; } + yield put(deleteOrderFailure({error, requestPayload: _action_.payload})); + return error; + } +} +//endregion +//region getInventory + +export interface PayloadGetInventory extends BasePayloadApiAction { +} + + +export const getInventoryRequest = createSagaAction("getInventoryRequest"); +export const getInventorySuccess = createSagaAction<{ [key: string]: number; }>("getInventorySuccess"); +export const getInventoryFailure = createSagaAction<{error: any, requestPayload: PayloadGetInventory}>("getInventoryFailure"); + +export const getInventory = createSagaAction("getInventory"); + +export function *getInventorySaga() { + yield takeLatest(getInventory, getInventorySagaImp); +} + +export function *getInventorySagaImp(_action_: Action) { + const {markErrorsAsHandled, ..._payloadRest_} = _action_.payload; + try { + + yield put(getInventoryRequest()); + + const response: Required<{ [key: string]: number; }> = yield apiCall(Api.storeApi, Api.storeApi.getInventory, + ); + + let successReturnValue: any = undefined; + yield put(getInventorySuccess(response)); + + return response; + } catch (error) { + if (markErrorsAsHandled) {error.wasHandled = true; } + yield put(getInventoryFailure({error, requestPayload: _action_.payload})); + return error; + } +} +//endregion +//region getOrderById + +export interface PayloadGetOrderById extends PayloadGetOrderByIdRequest, BaseEntitySupportPayloadApiAction { +} + +export interface PayloadGetOrderByIdRequest { + orderId: string; +} + +export const getOrderByIdRequest = createSagaAction("getOrderByIdRequest"); +export const getOrderByIdSuccess = createSagaAction("getOrderByIdSuccess"); +export const getOrderByIdSuccess_Entities = createSagaAction("getOrderByIdSuccess_Entities"); +export const getOrderByIdFailure = createSagaAction<{error: any, requestPayload: PayloadGetOrderById}>("getOrderByIdFailure"); + +export const getOrderById = createSagaAction("getOrderById"); + +export function *getOrderByIdSaga() { + yield takeLatest(getOrderById, getOrderByIdSagaImp); +} + +export function *getOrderByIdSagaImp(_action_: Action) { + const {markErrorsAsHandled, ..._payloadRest_} = _action_.payload; + try { + const {toEntities, toInlined = !toEntities, ...requestPayload} = _payloadRest_; + const { + orderId, + } = _payloadRest_; + + yield put(getOrderByIdRequest(requestPayload)); + + const response: Required = yield apiCall(Api.storeApi, Api.storeApi.getOrderById, + parseFloat(orderId), + ); + + let successReturnValue: any = undefined; + if (toEntities) { + successReturnValue = orderRecordUtils.fromApiArrayAsEntities([response]); + yield put(normalizedEntities(successReturnValue)); + yield put(getOrderByIdSuccess_Entities(successReturnValue)); + } + if (toInlined) { + successReturnValue = orderRecordUtils.fromApi(response); + yield put(getOrderByIdSuccess(successReturnValue)); + } + + return successReturnValue; + } catch (error) { + if (markErrorsAsHandled) {error.wasHandled = true; } + yield put(getOrderByIdFailure({error, requestPayload: _action_.payload})); + return error; + } +} +//endregion +//region placeOrder + +export interface PayloadPlaceOrder extends PayloadPlaceOrderRequest, BaseEntitySupportPayloadApiAction { +} + +export interface PayloadPlaceOrderRequest { + body: OrderRecord; +} + +export const placeOrderRequest = createSagaAction("placeOrderRequest"); +export const placeOrderSuccess = createSagaAction("placeOrderSuccess"); +export const placeOrderSuccess_Entities = createSagaAction("placeOrderSuccess_Entities"); +export const placeOrderFailure = createSagaAction<{error: any, requestPayload: PayloadPlaceOrder}>("placeOrderFailure"); + +export const placeOrder = createSagaAction("placeOrder"); + +export function *placeOrderSaga() { + yield takeLatest(placeOrder, placeOrderSagaImp); +} + +export function *placeOrderSagaImp(_action_: Action) { + const {markErrorsAsHandled, ..._payloadRest_} = _action_.payload; + try { + const {toEntities, toInlined = !toEntities, ...requestPayload} = _payloadRest_; + const { + body, + } = _payloadRest_; + + yield put(placeOrderRequest(requestPayload)); + + const response: Required = yield apiCall(Api.storeApi, Api.storeApi.placeOrder, + orderRecordUtils.toApi(body), + ); + + let successReturnValue: any = undefined; + if (toEntities) { + successReturnValue = orderRecordUtils.fromApiArrayAsEntities([response]); + yield put(normalizedEntities(successReturnValue)); + yield put(placeOrderSuccess_Entities(successReturnValue)); + } + if (toInlined) { + successReturnValue = orderRecordUtils.fromApi(response); + yield put(placeOrderSuccess(successReturnValue)); + } + + return successReturnValue; + } catch (error) { + if (markErrorsAsHandled) {error.wasHandled = true; } + yield put(placeOrderFailure({error, requestPayload: _action_.payload})); + return error; + } +} +//endregion diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/apis/UserApi.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/apis/UserApi.ts new file mode 100644 index 00000000000..1bc763f8066 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/apis/UserApi.ts @@ -0,0 +1,326 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * 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. + */ + + +import * as runtime from '../runtime'; +import { + DefaultMetaOnlyResponse, + DefaultMetaOnlyResponseFromJSON, + DefaultMetaOnlyResponseToJSON, + User, + UserFromJSON, + UserToJSON, +} from '../models'; + +export interface CreateUserRequest { + body: User; +} + +export interface CreateUsersWithArrayInputRequest { + body: Array; +} + +export interface CreateUsersWithListInputRequest { + body: Array; +} + +export interface DeleteUserRequest { + username: string; +} + +export interface GetUserByNameRequest { + username: string; +} + +export interface LoginUserRequest { + username: string; + password: string; +} + +export interface UpdateUserRequest { + username: string; + body: User; +} + +/** + * + */ +export class UserApi extends runtime.BaseAPI { + + /** + * This can only be done by the logged in user. + * Create user + */ + async createUserRaw(requestParameters: CreateUserRequest): Promise> { + if (requestParameters.body === null || requestParameters.body === undefined) { + throw new runtime.RequiredError('body','Required parameter requestParameters.body was null or undefined when calling createUser.'); + } + + const queryParameters: any = {}; + + const headerParameters: runtime.HTTPHeaders = {}; + + headerParameters['Content-Type'] = 'application/json'; + + const response = await this.request({ + path: `/user`, + method: 'POST', + headers: headerParameters, + query: queryParameters, + body: UserToJSON(requestParameters.body), + }); + + return new runtime.VoidApiResponse(response); + } + + /** + * This can only be done by the logged in user. + * Create user + */ + async createUser(body: User): Promise { + await this.createUserRaw({ body: body }); + } + + /** + * Creates list of users with given input array + */ + async createUsersWithArrayInputRaw(requestParameters: CreateUsersWithArrayInputRequest): Promise> { + if (requestParameters.body === null || requestParameters.body === undefined) { + throw new runtime.RequiredError('body','Required parameter requestParameters.body was null or undefined when calling createUsersWithArrayInput.'); + } + + const queryParameters: any = {}; + + const headerParameters: runtime.HTTPHeaders = {}; + + headerParameters['Content-Type'] = 'application/json'; + + const response = await this.request({ + path: `/user/createWithArray`, + method: 'POST', + headers: headerParameters, + query: queryParameters, + body: requestParameters.body.map(UserToJSON), + }); + + return new runtime.VoidApiResponse(response); + } + + /** + * Creates list of users with given input array + */ + async createUsersWithArrayInput(body: Array): Promise { + await this.createUsersWithArrayInputRaw({ body: body }); + } + + /** + * Creates list of users with given input array + */ + async createUsersWithListInputRaw(requestParameters: CreateUsersWithListInputRequest): Promise> { + if (requestParameters.body === null || requestParameters.body === undefined) { + throw new runtime.RequiredError('body','Required parameter requestParameters.body was null or undefined when calling createUsersWithListInput.'); + } + + const queryParameters: any = {}; + + const headerParameters: runtime.HTTPHeaders = {}; + + headerParameters['Content-Type'] = 'application/json'; + + const response = await this.request({ + path: `/user/createWithList`, + method: 'POST', + headers: headerParameters, + query: queryParameters, + body: requestParameters.body.map(UserToJSON), + }); + + return new runtime.VoidApiResponse(response); + } + + /** + * Creates list of users with given input array + */ + async createUsersWithListInput(body: Array): Promise { + await this.createUsersWithListInputRaw({ body: body }); + } + + /** + * This can only be done by the logged in user. + * Delete user + */ + async deleteUserRaw(requestParameters: DeleteUserRequest): Promise> { + if (requestParameters.username === null || requestParameters.username === undefined) { + throw new runtime.RequiredError('username','Required parameter requestParameters.username was null or undefined when calling deleteUser.'); + } + + const queryParameters: any = {}; + + const headerParameters: runtime.HTTPHeaders = {}; + + const response = await this.request({ + path: `/user/{username}`.replace(`{${"username"}}`, encodeURIComponent(String(requestParameters.username))), + method: 'DELETE', + headers: headerParameters, + query: queryParameters, + }); + + return new runtime.VoidApiResponse(response); + } + + /** + * This can only be done by the logged in user. + * Delete user + */ + async deleteUser(username: string): Promise { + await this.deleteUserRaw({ username: username }); + } + + /** + * Get user by user name + */ + async getUserByNameRaw(requestParameters: GetUserByNameRequest): Promise> { + if (requestParameters.username === null || requestParameters.username === undefined) { + throw new runtime.RequiredError('username','Required parameter requestParameters.username was null or undefined when calling getUserByName.'); + } + + const queryParameters: any = {}; + + const headerParameters: runtime.HTTPHeaders = {}; + + const response = await this.request({ + path: `/user/{username}`.replace(`{${"username"}}`, encodeURIComponent(String(requestParameters.username))), + method: 'GET', + headers: headerParameters, + query: queryParameters, + }); + + return new runtime.JSONApiResponse(response, (jsonValue) => UserFromJSON(jsonValue)); + } + + /** + * Get user by user name + */ + async getUserByName(username: string): Promise { + const response = await this.getUserByNameRaw({ username: username }); + return await response.value(); + } + + /** + * Logs user into the system + */ + async loginUserRaw(requestParameters: LoginUserRequest): Promise> { + if (requestParameters.username === null || requestParameters.username === undefined) { + throw new runtime.RequiredError('username','Required parameter requestParameters.username was null or undefined when calling loginUser.'); + } + + if (requestParameters.password === null || requestParameters.password === undefined) { + throw new runtime.RequiredError('password','Required parameter requestParameters.password was null or undefined when calling loginUser.'); + } + + const queryParameters: any = {}; + + if (requestParameters.username !== undefined) { + queryParameters['username'] = requestParameters.username; + } + + if (requestParameters.password !== undefined) { + queryParameters['password'] = requestParameters.password; + } + + const headerParameters: runtime.HTTPHeaders = {}; + + const response = await this.request({ + path: `/user/login`, + method: 'GET', + headers: headerParameters, + query: queryParameters, + }); + + return new runtime.TextApiResponse(response) as any; + } + + /** + * Logs user into the system + */ + async loginUser(username: string, password: string): Promise { + const response = await this.loginUserRaw({ username: username, password: password }); + return await response.value(); + } + + /** + * Logs out current logged in user session + */ + async logoutUserRaw(): Promise> { + const queryParameters: any = {}; + + const headerParameters: runtime.HTTPHeaders = {}; + + const response = await this.request({ + path: `/user/logout`, + method: 'GET', + headers: headerParameters, + query: queryParameters, + }); + + return new runtime.VoidApiResponse(response); + } + + /** + * Logs out current logged in user session + */ + async logoutUser(): Promise { + await this.logoutUserRaw(); + } + + /** + * This can only be done by the logged in user. + * Updated user + */ + async updateUserRaw(requestParameters: UpdateUserRequest): Promise> { + if (requestParameters.username === null || requestParameters.username === undefined) { + throw new runtime.RequiredError('username','Required parameter requestParameters.username was null or undefined when calling updateUser.'); + } + + if (requestParameters.body === null || requestParameters.body === undefined) { + throw new runtime.RequiredError('body','Required parameter requestParameters.body was null or undefined when calling updateUser.'); + } + + const queryParameters: any = {}; + + const headerParameters: runtime.HTTPHeaders = {}; + + headerParameters['Content-Type'] = 'application/json'; + + const response = await this.request({ + path: `/user/{username}`.replace(`{${"username"}}`, encodeURIComponent(String(requestParameters.username))), + method: 'PUT', + headers: headerParameters, + query: queryParameters, + body: UserToJSON(requestParameters.body), + }); + + return new runtime.JSONApiResponse(response, (jsonValue) => DefaultMetaOnlyResponseFromJSON(jsonValue)); + } + + /** + * This can only be done by the logged in user. + * Updated user + */ + async updateUser(username: string, body: User): Promise { + const response = await this.updateUserRaw({ username: username, body: body }); + return await response.value(); + } + +} diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/apis/UserApiSagas.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/apis/UserApiSagas.ts new file mode 100644 index 00000000000..9a2f070e145 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/apis/UserApiSagas.ts @@ -0,0 +1,395 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * 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. + */ + + +import {Api} from './'; +import {List} from 'immutable'; +import {all, fork, put, takeLatest} from "redux-saga/effects"; +import {apiCall, createSagaAction as originalCreateSagaAction, BaseEntitySupportPayloadApiAction, BasePayloadApiAction, NormalizedRecordEntities, normalizedEntities} from "../runtimeSagasAndRecords"; +import {Action} from "redux-ts-simple"; + +import { + DefaultMetaOnlyResponse, + DefaultMetaOnlyResponseRecord, + defaultMetaOnlyResponseRecordUtils, + User, + UserRecord, + userRecordUtils, +} from '../models'; + +const createSagaAction = (type: string) => originalCreateSagaAction(type, {namespace: "api_userApi"}); + +export const userApiSagaMap = new Map Generator>([ + ["createUser", createUserSaga], + ["createUsersWithArrayInput", createUsersWithArrayInputSaga], + ["createUsersWithListInput", createUsersWithListInputSaga], + ["deleteUser", deleteUserSaga], + ["getUserByName", getUserByNameSaga], + ["loginUser", loginUserSaga], + ["logoutUser", logoutUserSaga], + ["updateUser", updateUserSaga], + ] +); + +export function *userApiAllSagas() { + yield all([...userApiSagaMap.values()].map(actionSaga => fork(actionSaga))); +} + +//region createUser + +export interface PayloadCreateUser extends PayloadCreateUserRequest, BasePayloadApiAction { +} + +export interface PayloadCreateUserRequest { + body: UserRecord; +} + +export const createUserRequest = createSagaAction("createUserRequest"); +export const createUserSuccess = createSagaAction("createUserSuccess"); +export const createUserFailure = createSagaAction<{error: any, requestPayload: PayloadCreateUser}>("createUserFailure"); + +export const createUser = createSagaAction("createUser"); + +export function *createUserSaga() { + yield takeLatest(createUser, createUserSagaImp); +} + +export function *createUserSagaImp(_action_: Action) { + const {markErrorsAsHandled, ..._payloadRest_} = _action_.payload; + try { + const { + body, + } = _payloadRest_; + + yield put(createUserRequest(_action_.payload)); + + const response = yield apiCall(Api.userApi, Api.userApi.createUser, + userRecordUtils.toApi(body), + ); + + yield put(createUserSuccess()); + + return undefined; + } catch (error) { + if (markErrorsAsHandled) {error.wasHandled = true; } + yield put(createUserFailure({error, requestPayload: _action_.payload})); + return error; + } +} +//endregion +//region createUsersWithArrayInput + +export interface PayloadCreateUsersWithArrayInput extends PayloadCreateUsersWithArrayInputRequest, BasePayloadApiAction { +} + +export interface PayloadCreateUsersWithArrayInputRequest { + body: List; +} + +export const createUsersWithArrayInputRequest = createSagaAction("createUsersWithArrayInputRequest"); +export const createUsersWithArrayInputSuccess = createSagaAction("createUsersWithArrayInputSuccess"); +export const createUsersWithArrayInputFailure = createSagaAction<{error: any, requestPayload: PayloadCreateUsersWithArrayInput}>("createUsersWithArrayInputFailure"); + +export const createUsersWithArrayInput = createSagaAction("createUsersWithArrayInput"); + +export function *createUsersWithArrayInputSaga() { + yield takeLatest(createUsersWithArrayInput, createUsersWithArrayInputSagaImp); +} + +export function *createUsersWithArrayInputSagaImp(_action_: Action) { + const {markErrorsAsHandled, ..._payloadRest_} = _action_.payload; + try { + const { + body, + } = _payloadRest_; + + yield put(createUsersWithArrayInputRequest(_action_.payload)); + + const response = yield apiCall(Api.userApi, Api.userApi.createUsersWithArrayInput, + userRecordUtils.toApiArray(body), + ); + + yield put(createUsersWithArrayInputSuccess()); + + return undefined; + } catch (error) { + if (markErrorsAsHandled) {error.wasHandled = true; } + yield put(createUsersWithArrayInputFailure({error, requestPayload: _action_.payload})); + return error; + } +} +//endregion +//region createUsersWithListInput + +export interface PayloadCreateUsersWithListInput extends PayloadCreateUsersWithListInputRequest, BasePayloadApiAction { +} + +export interface PayloadCreateUsersWithListInputRequest { + body: List; +} + +export const createUsersWithListInputRequest = createSagaAction("createUsersWithListInputRequest"); +export const createUsersWithListInputSuccess = createSagaAction("createUsersWithListInputSuccess"); +export const createUsersWithListInputFailure = createSagaAction<{error: any, requestPayload: PayloadCreateUsersWithListInput}>("createUsersWithListInputFailure"); + +export const createUsersWithListInput = createSagaAction("createUsersWithListInput"); + +export function *createUsersWithListInputSaga() { + yield takeLatest(createUsersWithListInput, createUsersWithListInputSagaImp); +} + +export function *createUsersWithListInputSagaImp(_action_: Action) { + const {markErrorsAsHandled, ..._payloadRest_} = _action_.payload; + try { + const { + body, + } = _payloadRest_; + + yield put(createUsersWithListInputRequest(_action_.payload)); + + const response = yield apiCall(Api.userApi, Api.userApi.createUsersWithListInput, + userRecordUtils.toApiArray(body), + ); + + yield put(createUsersWithListInputSuccess()); + + return undefined; + } catch (error) { + if (markErrorsAsHandled) {error.wasHandled = true; } + yield put(createUsersWithListInputFailure({error, requestPayload: _action_.payload})); + return error; + } +} +//endregion +//region deleteUser + +export interface PayloadDeleteUser extends PayloadDeleteUserRequest, BasePayloadApiAction { +} + +export interface PayloadDeleteUserRequest { + username: string; +} + +export const deleteUserRequest = createSagaAction("deleteUserRequest"); +export const deleteUserSuccess = createSagaAction("deleteUserSuccess"); +export const deleteUserFailure = createSagaAction<{error: any, requestPayload: PayloadDeleteUser}>("deleteUserFailure"); + +export const deleteUser = createSagaAction("deleteUser"); + +export function *deleteUserSaga() { + yield takeLatest(deleteUser, deleteUserSagaImp); +} + +export function *deleteUserSagaImp(_action_: Action) { + const {markErrorsAsHandled, ..._payloadRest_} = _action_.payload; + try { + const { + username, + } = _payloadRest_; + + yield put(deleteUserRequest(_action_.payload)); + + const response = yield apiCall(Api.userApi, Api.userApi.deleteUser, + username, + ); + + yield put(deleteUserSuccess()); + + return undefined; + } catch (error) { + if (markErrorsAsHandled) {error.wasHandled = true; } + yield put(deleteUserFailure({error, requestPayload: _action_.payload})); + return error; + } +} +//endregion +//region getUserByName + +export interface PayloadGetUserByName extends PayloadGetUserByNameRequest, BaseEntitySupportPayloadApiAction { +} + +export interface PayloadGetUserByNameRequest { + username: string; +} + +export const getUserByNameRequest = createSagaAction("getUserByNameRequest"); +export const getUserByNameSuccess = createSagaAction("getUserByNameSuccess"); +export const getUserByNameSuccess_Entities = createSagaAction("getUserByNameSuccess_Entities"); +export const getUserByNameFailure = createSagaAction<{error: any, requestPayload: PayloadGetUserByName}>("getUserByNameFailure"); + +export const getUserByName = createSagaAction("getUserByName"); + +export function *getUserByNameSaga() { + yield takeLatest(getUserByName, getUserByNameSagaImp); +} + +export function *getUserByNameSagaImp(_action_: Action) { + const {markErrorsAsHandled, ..._payloadRest_} = _action_.payload; + try { + const {toEntities, toInlined = !toEntities, ...requestPayload} = _payloadRest_; + const { + username, + } = _payloadRest_; + + yield put(getUserByNameRequest(requestPayload)); + + const response: Required = yield apiCall(Api.userApi, Api.userApi.getUserByName, + username, + ); + + let successReturnValue: any = undefined; + if (toEntities) { + successReturnValue = userRecordUtils.fromApiArrayAsEntities([response]); + yield put(normalizedEntities(successReturnValue)); + yield put(getUserByNameSuccess_Entities(successReturnValue)); + } + if (toInlined) { + successReturnValue = userRecordUtils.fromApi(response); + yield put(getUserByNameSuccess(successReturnValue)); + } + + return successReturnValue; + } catch (error) { + if (markErrorsAsHandled) {error.wasHandled = true; } + yield put(getUserByNameFailure({error, requestPayload: _action_.payload})); + return error; + } +} +//endregion +//region loginUser + +export interface PayloadLoginUser extends PayloadLoginUserRequest, BasePayloadApiAction { +} + +export interface PayloadLoginUserRequest { + username: string; + password: string; +} + +export const loginUserRequest = createSagaAction("loginUserRequest"); +export const loginUserSuccess = createSagaAction("loginUserSuccess"); +export const loginUserFailure = createSagaAction<{error: any, requestPayload: PayloadLoginUser}>("loginUserFailure"); + +export const loginUser = createSagaAction("loginUser"); + +export function *loginUserSaga() { + yield takeLatest(loginUser, loginUserSagaImp); +} + +export function *loginUserSagaImp(_action_: Action) { + const {markErrorsAsHandled, ..._payloadRest_} = _action_.payload; + try { + const { + username, + password, + } = _payloadRest_; + + yield put(loginUserRequest(_action_.payload)); + + const response: Required = yield apiCall(Api.userApi, Api.userApi.loginUser, + username, + password, + ); + + let successReturnValue: any = undefined; + yield put(loginUserSuccess(response)); + + return response; + } catch (error) { + if (markErrorsAsHandled) {error.wasHandled = true; } + yield put(loginUserFailure({error, requestPayload: _action_.payload})); + return error; + } +} +//endregion +//region logoutUser + +export interface PayloadLogoutUser extends BasePayloadApiAction { +} + + +export const logoutUserRequest = createSagaAction("logoutUserRequest"); +export const logoutUserSuccess = createSagaAction("logoutUserSuccess"); +export const logoutUserFailure = createSagaAction<{error: any, requestPayload: PayloadLogoutUser}>("logoutUserFailure"); + +export const logoutUser = createSagaAction("logoutUser"); + +export function *logoutUserSaga() { + yield takeLatest(logoutUser, logoutUserSagaImp); +} + +export function *logoutUserSagaImp(_action_: Action) { + const {markErrorsAsHandled, ..._payloadRest_} = _action_.payload; + try { + + yield put(logoutUserRequest()); + + const response = yield apiCall(Api.userApi, Api.userApi.logoutUser, + ); + + yield put(logoutUserSuccess()); + + return undefined; + } catch (error) { + if (markErrorsAsHandled) {error.wasHandled = true; } + yield put(logoutUserFailure({error, requestPayload: _action_.payload})); + return error; + } +} +//endregion +//region updateUser + +export interface PayloadUpdateUser extends PayloadUpdateUserRequest, BasePayloadApiAction { +} + +export interface PayloadUpdateUserRequest { + username: string; + body: UserRecord; +} + +export const updateUserRequest = createSagaAction("updateUserRequest"); +export const updateUserSuccess = createSagaAction("updateUserSuccess"); +export const updateUserFailure = createSagaAction<{error: any, requestPayload: PayloadUpdateUser}>("updateUserFailure"); + +export const updateUser = createSagaAction("updateUser"); + +export function *updateUserSaga() { + yield takeLatest(updateUser, updateUserSagaImp); +} + +export function *updateUserSagaImp(_action_: Action) { + const {markErrorsAsHandled, ..._payloadRest_} = _action_.payload; + try { + const { + username, + body, + } = _payloadRest_; + + yield put(updateUserRequest(_action_.payload)); + + const response: Required = yield apiCall(Api.userApi, Api.userApi.updateUser, + username, + userRecordUtils.toApi(body), + ); + + yield put(updateUserSuccess()); + + return undefined; + } catch (error) { + if (markErrorsAsHandled) {error.wasHandled = true; } + yield put(updateUserFailure({error, requestPayload: _action_.payload})); + return error; + } +} +//endregion diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/apis/allSagas.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/apis/allSagas.ts new file mode 100644 index 00000000000..dae5870a93a --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/apis/allSagas.ts @@ -0,0 +1,19 @@ +import {all, fork} from "redux-saga/effects"; + +import { + behaviorApiAllSagas, + petApiAllSagas, + petPartApiAllSagas, + storeApiAllSagas, + userApiAllSagas, +} from "./"; + +export function *allApiSagas() { + yield all([ + fork(behaviorApiAllSagas), + fork(petApiAllSagas), + fork(petPartApiAllSagas), + fork(storeApiAllSagas), + fork(userApiAllSagas), + ]); +} diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/apis/index.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/apis/index.ts new file mode 100644 index 00000000000..4a025f4ed41 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/apis/index.ts @@ -0,0 +1,12 @@ +export * from './SagaApiManager' +export * from './allSagas' +export * from './BehaviorApi'; +export * from './BehaviorApiSagas'; +export * from './PetApi'; +export * from './PetApiSagas'; +export * from './PetPartApi'; +export * from './PetPartApiSagas'; +export * from './StoreApi'; +export * from './StoreApiSagas'; +export * from './UserApi'; +export * from './UserApiSagas'; diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/index.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/index.ts new file mode 100644 index 00000000000..abbe33d5b20 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/index.ts @@ -0,0 +1,7 @@ +export * from './runtime'; +export * from './runtimeSagasAndRecords'; +export * from './ApiEntitiesRecord'; +export * from './ApiEntitiesReducer'; +export * from './ApiEntitiesSelectors'; +export * from './apis'; +export * from './models'; diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/BehaviorType.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/BehaviorType.ts new file mode 100644 index 00000000000..f10324a4775 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/BehaviorType.ts @@ -0,0 +1,37 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * 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. + */ + +/** + * Behavior type of a pet + * @export + * @enum {string} + */ +export enum BehaviorType { + Voluntary = 'Voluntary', + Involuntary = 'Involuntary', + Overt = 'Overt' +} + +export function BehaviorTypeFromJSON(json: any): BehaviorType { + return BehaviorTypeFromJSONTyped(json, false); +} + +export function BehaviorTypeFromJSONTyped(json: any, ignoreDiscriminator: boolean): BehaviorType { + return json as BehaviorType; +} + +export function BehaviorTypeToJSON(value?: BehaviorType | null): any { + return value as any; +} + diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/BehaviorTypeRecord.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/BehaviorTypeRecord.ts new file mode 100644 index 00000000000..65fbcfab763 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/BehaviorTypeRecord.ts @@ -0,0 +1 @@ +// This file is not needed and was generated only because of how codegen is built... Enums do not need to be converted to Records and can be used directly. diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/Category.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/Category.ts new file mode 100644 index 00000000000..faf9aabb9de --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/Category.ts @@ -0,0 +1,65 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * 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. + */ + +import { exists, mapValues } from '../runtime'; +/** + * A category for a pet + * @export + * @interface Category + */ +export interface Category { + /** + * + * @type {number} + * @memberof Category + */ + id?: number; + /** + * + * @type {string} + * @memberof Category + */ + name?: string; +} + +export function CategoryFromJSON(json: any): Category { + return CategoryFromJSONTyped(json, false); +} + +export function CategoryFromJSONTyped(json: any, ignoreDiscriminator: boolean): Category { + if ((json === undefined) || (json === null)) { + return json; + } + return { + + 'id': !exists(json, 'id') ? undefined : json['id'], + 'name': !exists(json, 'name') ? undefined : json['name'], + }; +} + +export function CategoryToJSON(value?: Category | null): any { + if (value === undefined) { + return undefined; + } + if (value === null) { + return null; + } + return { + + 'id': value.id, + 'name': value.name, + }; +} + + 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 new file mode 100644 index 00000000000..f69d536f6ea --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/CategoryRecord.ts @@ -0,0 +1,104 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * 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. + */ + +import {ApiRecordUtils, knownRecordFactories} from "../runtimeSagasAndRecords"; +import {getApiEntitiesState} from "../ApiEntitiesSelectors" +import {List, Record, RecordOf, Map} from 'immutable'; +import {Schema, schema, NormalizedSchema} from "normalizr"; +import {select, call} from "redux-saga/effects"; + +import { + Category, +} from './Category'; + + + +export const CategoryRecordProps = { + recType: "CategoryApiRecord" as "CategoryApiRecord", + id: null as string | null, + name: null as string | null, +}; + +export type CategoryRecordPropsType = typeof CategoryRecordProps; +export const CategoryRecord = Record(CategoryRecordProps, CategoryRecordProps.recType); +export type CategoryRecord = RecordOf; + +knownRecordFactories.set(CategoryRecordProps.recType, CategoryRecord); + +export const CategoryRecordEntityProps = { + ...CategoryRecordProps, + recType: "CategoryApiRecordEntity" as "CategoryApiRecordEntity", +}; + +export type CategoryRecordEntityPropsType = typeof CategoryRecordEntityProps; +export const CategoryRecordEntity = Record(CategoryRecordEntityProps, CategoryRecordEntityProps.recType); +export type CategoryRecordEntity = RecordOf; + +knownRecordFactories.set(CategoryRecordEntityProps.recType, CategoryRecordEntity); + +class CategoryRecordUtils extends ApiRecordUtils { + public normalize(apiObject: Category, asEntity?: boolean): Category { + (apiObject as any).recType = asEntity ? CategoryRecordEntityProps.recType : CategoryRecordProps.recType; + if (apiObject.id) { (apiObject as any).id = apiObject.id.toString(); } + return apiObject; + } + + public getSchema(): Schema { + return new schema.Entity("category", { + }); + } + + public *toInlined(entityId?: string | null) { + if (!entityId) {return undefined; } + const entity = yield select(apiEntityCategorySelector, {id: entityId}); + if (!entity) {return undefined; } + + const { + recType, + ...unchangedProperties + } = entity; + + const entityProperties = { + } + + return CategoryRecord({ + ...unchangedProperties, + ...entityProperties + }); + } + + public *toInlinedArray(entityIds: List | null) { + if (!entityIds) {return null; } + let entities = List(); + for (let entityIndex = 0; entityIndex < entityIds.count(); entityIndex++) { + const entity = yield call(this.toInlined, entityIds.get(entityIndex)); + if (entity) { + entities.push(entity); + } + } + return entities; + } + + public toApi(record: CategoryRecord): Category { + const apiObject = super.toApi(record); + if (record.id) { apiObject.id = parseFloat(record.id); } + return apiObject; + } +} + +export const categoryRecordUtils = new CategoryRecordUtils(); + +export const apiEntitiesCategorySelector = (state: any) => getApiEntitiesState(state).category as Map; +export const apiEntityCategorySelector = (state: any, {id}: {id?: string | null}) => id ? apiEntitiesCategorySelector(state).get(id) : undefined; + diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/DefaultMetaOnlyResponse.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/DefaultMetaOnlyResponse.ts new file mode 100644 index 00000000000..b6ac416539a --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/DefaultMetaOnlyResponse.ts @@ -0,0 +1,64 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * 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. + */ + +import { exists, mapValues } from '../runtime'; +import { + ResponseMeta, + ResponseMetaFromJSON, + ResponseMetaFromJSONTyped, + ResponseMetaToJSON, +} from './'; + +/** + * + * @export + * @interface DefaultMetaOnlyResponse + */ +export interface DefaultMetaOnlyResponse { + /** + * + * @type {ResponseMeta} + * @memberof DefaultMetaOnlyResponse + */ + meta: ResponseMeta; +} + +export function DefaultMetaOnlyResponseFromJSON(json: any): DefaultMetaOnlyResponse { + return DefaultMetaOnlyResponseFromJSONTyped(json, false); +} + +export function DefaultMetaOnlyResponseFromJSONTyped(json: any, ignoreDiscriminator: boolean): DefaultMetaOnlyResponse { + if ((json === undefined) || (json === null)) { + return json; + } + return { + + 'meta': ResponseMetaFromJSON(json['meta']), + }; +} + +export function DefaultMetaOnlyResponseToJSON(value?: DefaultMetaOnlyResponse | null): any { + if (value === undefined) { + return undefined; + } + if (value === null) { + return null; + } + return { + + 'meta': ResponseMetaToJSON(value.meta), + }; +} + + diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/DefaultMetaOnlyResponseRecord.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/DefaultMetaOnlyResponseRecord.ts new file mode 100644 index 00000000000..b59a715e84c --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/DefaultMetaOnlyResponseRecord.ts @@ -0,0 +1,62 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * 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. + */ + +import {ApiRecordUtils, knownRecordFactories} from "../runtimeSagasAndRecords"; +import {getApiEntitiesState} from "../ApiEntitiesSelectors" +import {List, Record, RecordOf, Map} from 'immutable'; +import {Schema, schema, NormalizedSchema} from "normalizr"; +import {select, call} from "redux-saga/effects"; + +import { + DefaultMetaOnlyResponse, +} from './DefaultMetaOnlyResponse'; + +import { + ResponseMeta, +} from './ResponseMeta'; + +import { + ResponseMetaRecord, + responseMetaRecordUtils +} from './ResponseMetaRecord'; + +export const DefaultMetaOnlyResponseRecordProps = { + recType: "DefaultMetaOnlyResponseApiRecord" as "DefaultMetaOnlyResponseApiRecord", + meta: ResponseMetaRecord(), +}; + +export type DefaultMetaOnlyResponseRecordPropsType = typeof DefaultMetaOnlyResponseRecordProps; +export const DefaultMetaOnlyResponseRecord = Record(DefaultMetaOnlyResponseRecordProps, DefaultMetaOnlyResponseRecordProps.recType); +export type DefaultMetaOnlyResponseRecord = RecordOf; + +knownRecordFactories.set(DefaultMetaOnlyResponseRecordProps.recType, DefaultMetaOnlyResponseRecord); + + +class DefaultMetaOnlyResponseRecordUtils extends ApiRecordUtils { + public normalize(apiObject: DefaultMetaOnlyResponse, asEntity?: boolean): DefaultMetaOnlyResponse { + (apiObject as any).recType = DefaultMetaOnlyResponseRecordProps.recType; + responseMetaRecordUtils.normalize(apiObject.meta); + return apiObject; + } + + public toApi(record: DefaultMetaOnlyResponseRecord): DefaultMetaOnlyResponse { + const apiObject = super.toApi(record); + apiObject.meta = responseMetaRecordUtils.toApi(record.meta); + return apiObject; + } +} + +export const defaultMetaOnlyResponseRecordUtils = new DefaultMetaOnlyResponseRecordUtils(); + + diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/DeploymentRequestStatus.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/DeploymentRequestStatus.ts new file mode 100644 index 00000000000..0a24b4b493f --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/DeploymentRequestStatus.ts @@ -0,0 +1,46 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * 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. + */ + +/** + * Status of the deployment request + * @export + * @enum {string} + */ +export enum DeploymentRequestStatus { + New = 'New', + Prepared = 'Prepared', + Printed = 'Printed', + Tested = 'Tested', + Completed = 'Completed', + Cancelled = 'Cancelled', + Promoted = 'Promoted', + Assigned = 'Assigned', + Ready = 'Ready', + Packaged = 'Packaged', + Pairing = 'Pairing', + Paired = 'Paired' +} + +export function DeploymentRequestStatusFromJSON(json: any): DeploymentRequestStatus { + return DeploymentRequestStatusFromJSONTyped(json, false); +} + +export function DeploymentRequestStatusFromJSONTyped(json: any, ignoreDiscriminator: boolean): DeploymentRequestStatus { + return json as DeploymentRequestStatus; +} + +export function DeploymentRequestStatusToJSON(value?: DeploymentRequestStatus | null): any { + return value as any; +} + diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/DeploymentRequestStatusRecord.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/DeploymentRequestStatusRecord.ts new file mode 100644 index 00000000000..65fbcfab763 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/DeploymentRequestStatusRecord.ts @@ -0,0 +1 @@ +// This file is not needed and was generated only because of how codegen is built... Enums do not need to be converted to Records and can be used directly. diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/ErrorCode.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/ErrorCode.ts new file mode 100644 index 00000000000..101539269e4 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/ErrorCode.ts @@ -0,0 +1,52 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * 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. + */ + +/** + * Error code returned when an error occurs + * @export + * @enum {string} + */ +export enum ErrorCode { + VolumeRangeAtLowestValue = 'Volume_Range_At_Lowest_Value', + MusicVolumeBlocksVolumeRangeDecrease = 'Music_Volume_Blocks_Volume_Range_Decrease', + VolumeRangeAtHighestValue = 'Volume_Range_At_Highest_Value', + MaximumVolumeBlocksVolumeRangeIncrease = 'Maximum_Volume_Blocks_Volume_Range_Increase', + MusicVolumeBlocksMaximumVolumeDecrease = 'Music_Volume_Blocks_Maximum_Volume_Decrease', + MaximumVolumeAtLowestValue = 'Maximum_Volume_At_Lowest_Value', + VolumeRangeBlocksMaximumVolumeDecrease = 'Volume_Range_Blocks_Maximum_Volume_Decrease', + MaximumVolumeAtHighestValue = 'Maximum_Volume_At_Highest_Value', + MessageGainBlocksMaximumVolumeIncrease = 'Message_Gain_Blocks_Maximum_Volume_Increase', + MusicVolumeBlocksMaximumVolumeIncrease = 'Music_Volume_Blocks_Maximum_Volume_Increase', + MaximumVolumeBlocksMessageGainDecrease = 'Maximum_Volume_Blocks_Message_Gain_Decrease', + MessageGainAtHighestValue = 'Message_Gain_At_Highest_Value', + MusicVolumeBlocksMessageGain = 'Music_Volume_Blocks_Message_Gain', + MaximumMessageGainLowerThanMinimum = 'Maximum_Message_Gain_Lower_Than_Minimum', + MaximumMessageGainHigherThanMaximum = 'Maximum_Message_Gain_Higher_Than_Maximum', + MaximumMessageGainLowerThanMessageGain = 'Maximum_Message_Gain_Lower_Than_Message_Gain', + MinimumVolumeBlocksMusicVolumeDecrease = 'Minimum_Volume_Blocks_Music_Volume_Decrease', + MaximumVolumeBlocksMusicVolumeIncrease = 'Maximum_Volume_Blocks_Music_Volume_Increase' +} + +export function ErrorCodeFromJSON(json: any): ErrorCode { + return ErrorCodeFromJSONTyped(json, false); +} + +export function ErrorCodeFromJSONTyped(json: any, ignoreDiscriminator: boolean): ErrorCode { + return json as ErrorCode; +} + +export function ErrorCodeToJSON(value?: ErrorCode | null): any { + return value as any; +} + diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/ErrorCodeRecord.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/ErrorCodeRecord.ts new file mode 100644 index 00000000000..65fbcfab763 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/ErrorCodeRecord.ts @@ -0,0 +1 @@ +// This file is not needed and was generated only because of how codegen is built... Enums do not need to be converted to Records and can be used directly. diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/FindPetsByStatusResponse.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/FindPetsByStatusResponse.ts new file mode 100644 index 00000000000..6118e070e10 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/FindPetsByStatusResponse.ts @@ -0,0 +1,76 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * 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. + */ + +import { exists, mapValues } from '../runtime'; +import { + Pet, + PetFromJSON, + PetFromJSONTyped, + PetToJSON, + ResponseMeta, + ResponseMetaFromJSON, + ResponseMetaFromJSONTyped, + ResponseMetaToJSON, +} from './'; + +/** + * + * @export + * @interface FindPetsByStatusResponse + */ +export interface FindPetsByStatusResponse { + /** + * + * @type {ResponseMeta} + * @memberof FindPetsByStatusResponse + */ + meta: ResponseMeta; + /** + * + * @type {Array} + * @memberof FindPetsByStatusResponse + */ + data?: Array; +} + +export function FindPetsByStatusResponseFromJSON(json: any): FindPetsByStatusResponse { + return FindPetsByStatusResponseFromJSONTyped(json, false); +} + +export function FindPetsByStatusResponseFromJSONTyped(json: any, ignoreDiscriminator: boolean): FindPetsByStatusResponse { + if ((json === undefined) || (json === null)) { + return json; + } + return { + + 'meta': ResponseMetaFromJSON(json['meta']), + 'data': !exists(json, 'data') ? undefined : ((json['data'] as Array).map(PetFromJSON)), + }; +} + +export function FindPetsByStatusResponseToJSON(value?: FindPetsByStatusResponse | null): any { + if (value === undefined) { + return undefined; + } + if (value === null) { + return null; + } + return { + + 'meta': ResponseMetaToJSON(value.meta), + 'data': value.data === undefined ? undefined : ((value.data as Array).map(PetToJSON)), + }; +} + + diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/FindPetsByStatusResponseRecord.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/FindPetsByStatusResponseRecord.ts new file mode 100644 index 00000000000..3ac38102f82 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/FindPetsByStatusResponseRecord.ts @@ -0,0 +1,83 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * 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. + */ + +import {ApiRecordUtils, knownRecordFactories, appFromJS, NormalizedRecordEntities} from "../runtimeSagasAndRecords"; +import {getApiEntitiesState} from "../ApiEntitiesSelectors" +import {List, Record, RecordOf, Map} from 'immutable'; +import {Schema, schema, NormalizedSchema} from "normalizr"; +import {select, call} from "redux-saga/effects"; + +import { + FindPetsByStatusResponse, +} from './FindPetsByStatusResponse'; + +import { + Pet, +} from './Pet'; +import { + ResponseMeta, +} from './ResponseMeta'; + +import { + PetRecord, + petRecordUtils +} from './PetRecord'; +import { + ResponseMetaRecord, + responseMetaRecordUtils +} from './ResponseMetaRecord'; + +export const FindPetsByStatusResponseRecordProps = { + recType: "FindPetsByStatusResponseApiRecord" as "FindPetsByStatusResponseApiRecord", + meta: ResponseMetaRecord(), + data: (PetRecord(), null as List | null), +}; + +export type FindPetsByStatusResponseRecordPropsType = typeof FindPetsByStatusResponseRecordProps; +export const FindPetsByStatusResponseRecord = Record(FindPetsByStatusResponseRecordProps, FindPetsByStatusResponseRecordProps.recType); +export type FindPetsByStatusResponseRecord = RecordOf; + +knownRecordFactories.set(FindPetsByStatusResponseRecordProps.recType, FindPetsByStatusResponseRecord); + + +class FindPetsByStatusResponseRecordUtils extends ApiRecordUtils { + public normalize(apiObject: FindPetsByStatusResponse, asEntity?: boolean): FindPetsByStatusResponse { + (apiObject as any).recType = FindPetsByStatusResponseRecordProps.recType; + responseMetaRecordUtils.normalize(apiObject.meta); + if (apiObject.data) { petRecordUtils.normalizeArray(apiObject.data); } + return apiObject; + } + + public toApi(record: FindPetsByStatusResponseRecord): FindPetsByStatusResponse { + const apiObject = super.toApi(record); + apiObject.meta = responseMetaRecordUtils.toApi(record.meta); + if (record.data) { apiObject.data = petRecordUtils.toApiArray(record.data); } + return apiObject; + } + + public fromApiPassthrough(apiObject: FindPetsByStatusResponse): List { + if (!apiObject.data) {return List(); } + const normalizedApiObject = petRecordUtils.normalizeArray(apiObject.data); + return appFromJS(normalizedApiObject); + } + + public fromApiPassthroughAsEntities(apiObject: FindPetsByStatusResponse): NormalizedRecordEntities { + if (!apiObject.data) {return {entities: {}, result: List()}; } + return ApiRecordUtils.toNormalizedRecordEntities(petRecordUtils.normalizeArrayAsEntities(apiObject.data), true); + } +} + +export const findPetsByStatusResponseRecordUtils = new FindPetsByStatusResponseRecordUtils(); + + diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/FindPetsByUserResponse.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/FindPetsByUserResponse.ts new file mode 100644 index 00000000000..9f010d3b32b --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/FindPetsByUserResponse.ts @@ -0,0 +1,76 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * 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. + */ + +import { exists, mapValues } from '../runtime'; +import { + ResponseMeta, + ResponseMetaFromJSON, + ResponseMetaFromJSONTyped, + ResponseMetaToJSON, + User, + UserFromJSON, + UserFromJSONTyped, + UserToJSON, +} from './'; + +/** + * + * @export + * @interface FindPetsByUserResponse + */ +export interface FindPetsByUserResponse { + /** + * + * @type {ResponseMeta} + * @memberof FindPetsByUserResponse + */ + meta: ResponseMeta; + /** + * + * @type {Array} + * @memberof FindPetsByUserResponse + */ + data?: Array; +} + +export function FindPetsByUserResponseFromJSON(json: any): FindPetsByUserResponse { + return FindPetsByUserResponseFromJSONTyped(json, false); +} + +export function FindPetsByUserResponseFromJSONTyped(json: any, ignoreDiscriminator: boolean): FindPetsByUserResponse { + if ((json === undefined) || (json === null)) { + return json; + } + return { + + 'meta': ResponseMetaFromJSON(json['meta']), + 'data': !exists(json, 'data') ? undefined : ((json['data'] as Array).map(UserFromJSON)), + }; +} + +export function FindPetsByUserResponseToJSON(value?: FindPetsByUserResponse | null): any { + if (value === undefined) { + return undefined; + } + if (value === null) { + return null; + } + return { + + 'meta': ResponseMetaToJSON(value.meta), + 'data': value.data === undefined ? undefined : ((value.data as Array).map(UserToJSON)), + }; +} + + diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/FindPetsByUserResponseRecord.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/FindPetsByUserResponseRecord.ts new file mode 100644 index 00000000000..b1cddadbf54 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/FindPetsByUserResponseRecord.ts @@ -0,0 +1,83 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * 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. + */ + +import {ApiRecordUtils, knownRecordFactories, appFromJS, NormalizedRecordEntities} from "../runtimeSagasAndRecords"; +import {getApiEntitiesState} from "../ApiEntitiesSelectors" +import {List, Record, RecordOf, Map} from 'immutable'; +import {Schema, schema, NormalizedSchema} from "normalizr"; +import {select, call} from "redux-saga/effects"; + +import { + FindPetsByUserResponse, +} from './FindPetsByUserResponse'; + +import { + ResponseMeta, +} from './ResponseMeta'; +import { + User, +} from './User'; + +import { + ResponseMetaRecord, + responseMetaRecordUtils +} from './ResponseMetaRecord'; +import { + UserRecord, + userRecordUtils +} from './UserRecord'; + +export const FindPetsByUserResponseRecordProps = { + recType: "FindPetsByUserResponseApiRecord" as "FindPetsByUserResponseApiRecord", + meta: ResponseMetaRecord(), + data: (UserRecord(), null as List | null), +}; + +export type FindPetsByUserResponseRecordPropsType = typeof FindPetsByUserResponseRecordProps; +export const FindPetsByUserResponseRecord = Record(FindPetsByUserResponseRecordProps, FindPetsByUserResponseRecordProps.recType); +export type FindPetsByUserResponseRecord = RecordOf; + +knownRecordFactories.set(FindPetsByUserResponseRecordProps.recType, FindPetsByUserResponseRecord); + + +class FindPetsByUserResponseRecordUtils extends ApiRecordUtils { + public normalize(apiObject: FindPetsByUserResponse, asEntity?: boolean): FindPetsByUserResponse { + (apiObject as any).recType = FindPetsByUserResponseRecordProps.recType; + responseMetaRecordUtils.normalize(apiObject.meta); + if (apiObject.data) { userRecordUtils.normalizeArray(apiObject.data); } + return apiObject; + } + + public toApi(record: FindPetsByUserResponseRecord): FindPetsByUserResponse { + const apiObject = super.toApi(record); + apiObject.meta = responseMetaRecordUtils.toApi(record.meta); + if (record.data) { apiObject.data = userRecordUtils.toApiArray(record.data); } + return apiObject; + } + + public fromApiPassthrough(apiObject: FindPetsByUserResponse): List { + if (!apiObject.data) {return List(); } + const normalizedApiObject = userRecordUtils.normalizeArray(apiObject.data); + return appFromJS(normalizedApiObject); + } + + public fromApiPassthroughAsEntities(apiObject: FindPetsByUserResponse): NormalizedRecordEntities { + if (!apiObject.data) {return {entities: {}, result: List()}; } + return ApiRecordUtils.toNormalizedRecordEntities(userRecordUtils.normalizeArrayAsEntities(apiObject.data), true); + } +} + +export const findPetsByUserResponseRecordUtils = new FindPetsByUserResponseRecordUtils(); + + diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/GetBehaviorPermissionsResponse.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/GetBehaviorPermissionsResponse.ts new file mode 100644 index 00000000000..98f03260391 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/GetBehaviorPermissionsResponse.ts @@ -0,0 +1,72 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * 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. + */ + +import { exists, mapValues } from '../runtime'; +import { + ResponseMeta, + ResponseMetaFromJSON, + ResponseMetaFromJSONTyped, + ResponseMetaToJSON, +} from './'; + +/** + * + * @export + * @interface GetBehaviorPermissionsResponse + */ +export interface GetBehaviorPermissionsResponse { + /** + * + * @type {ResponseMeta} + * @memberof GetBehaviorPermissionsResponse + */ + meta: ResponseMeta; + /** + * + * @type {{ [key: string]: boolean; }} + * @memberof GetBehaviorPermissionsResponse + */ + data?: { [key: string]: boolean; }; +} + +export function GetBehaviorPermissionsResponseFromJSON(json: any): GetBehaviorPermissionsResponse { + return GetBehaviorPermissionsResponseFromJSONTyped(json, false); +} + +export function GetBehaviorPermissionsResponseFromJSONTyped(json: any, ignoreDiscriminator: boolean): GetBehaviorPermissionsResponse { + if ((json === undefined) || (json === null)) { + return json; + } + return { + + 'meta': ResponseMetaFromJSON(json['meta']), + 'data': !exists(json, 'data') ? undefined : json['data'], + }; +} + +export function GetBehaviorPermissionsResponseToJSON(value?: GetBehaviorPermissionsResponse | null): any { + if (value === undefined) { + return undefined; + } + if (value === null) { + return null; + } + return { + + 'meta': ResponseMetaToJSON(value.meta), + 'data': value.data, + }; +} + + diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/GetBehaviorPermissionsResponseRecord.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/GetBehaviorPermissionsResponseRecord.ts new file mode 100644 index 00000000000..eb7f7fdd70f --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/GetBehaviorPermissionsResponseRecord.ts @@ -0,0 +1,72 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * 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. + */ + +import {ApiRecordUtils, knownRecordFactories, appFromJS, NormalizedRecordEntities} from "../runtimeSagasAndRecords"; +import {getApiEntitiesState} from "../ApiEntitiesSelectors" +import {List, Record, RecordOf, Map} from 'immutable'; +import {Schema, schema, NormalizedSchema} from "normalizr"; +import {select, call} from "redux-saga/effects"; + +import { + GetBehaviorPermissionsResponse, +} from './GetBehaviorPermissionsResponse'; + +import { + ResponseMeta, +} from './ResponseMeta'; + +import { + ResponseMetaRecord, + responseMetaRecordUtils +} from './ResponseMetaRecord'; + +export const GetBehaviorPermissionsResponseRecordProps = { + recType: "GetBehaviorPermissionsResponseApiRecord" as "GetBehaviorPermissionsResponseApiRecord", + meta: ResponseMetaRecord(), + data: null as { [key: string]: boolean; } | null, +}; + +export type GetBehaviorPermissionsResponseRecordPropsType = typeof GetBehaviorPermissionsResponseRecordProps; +export const GetBehaviorPermissionsResponseRecord = Record(GetBehaviorPermissionsResponseRecordProps, GetBehaviorPermissionsResponseRecordProps.recType); +export type GetBehaviorPermissionsResponseRecord = RecordOf; + +knownRecordFactories.set(GetBehaviorPermissionsResponseRecordProps.recType, GetBehaviorPermissionsResponseRecord); + + +class GetBehaviorPermissionsResponseRecordUtils extends ApiRecordUtils { + public normalize(apiObject: GetBehaviorPermissionsResponse, asEntity?: boolean): GetBehaviorPermissionsResponse { + (apiObject as any).recType = GetBehaviorPermissionsResponseRecordProps.recType; + responseMetaRecordUtils.normalize(apiObject.meta); + return apiObject; + } + + public toApi(record: GetBehaviorPermissionsResponseRecord): GetBehaviorPermissionsResponse { + const apiObject = super.toApi(record); + apiObject.meta = responseMetaRecordUtils.toApi(record.meta); + return apiObject; + } + + public fromApiPassthrough(apiObject: GetBehaviorPermissionsResponse): { [key: string]: boolean; } { + return apiObject.data!; + } + + public fromApiPassthroughAsEntities(apiObject: GetBehaviorPermissionsResponse): NormalizedRecordEntities { + console.log("entities revival not supported on this response"); + return {entities: {}, result: List()}; + } +} + +export const getBehaviorPermissionsResponseRecordUtils = new GetBehaviorPermissionsResponseRecordUtils(); + + diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/GetBehaviorTypeResponse.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/GetBehaviorTypeResponse.ts new file mode 100644 index 00000000000..da5e918c40f --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/GetBehaviorTypeResponse.ts @@ -0,0 +1,76 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * 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. + */ + +import { exists, mapValues } from '../runtime'; +import { + BehaviorType, + BehaviorTypeFromJSON, + BehaviorTypeFromJSONTyped, + BehaviorTypeToJSON, + ResponseMeta, + ResponseMetaFromJSON, + ResponseMetaFromJSONTyped, + ResponseMetaToJSON, +} from './'; + +/** + * + * @export + * @interface GetBehaviorTypeResponse + */ +export interface GetBehaviorTypeResponse { + /** + * + * @type {ResponseMeta} + * @memberof GetBehaviorTypeResponse + */ + meta: ResponseMeta; + /** + * + * @type {BehaviorType} + * @memberof GetBehaviorTypeResponse + */ + data?: BehaviorType; +} + +export function GetBehaviorTypeResponseFromJSON(json: any): GetBehaviorTypeResponse { + return GetBehaviorTypeResponseFromJSONTyped(json, false); +} + +export function GetBehaviorTypeResponseFromJSONTyped(json: any, ignoreDiscriminator: boolean): GetBehaviorTypeResponse { + if ((json === undefined) || (json === null)) { + return json; + } + return { + + 'meta': ResponseMetaFromJSON(json['meta']), + 'data': !exists(json, 'data') ? undefined : BehaviorTypeFromJSON(json['data']), + }; +} + +export function GetBehaviorTypeResponseToJSON(value?: GetBehaviorTypeResponse | null): any { + if (value === undefined) { + return undefined; + } + if (value === null) { + return null; + } + return { + + 'meta': ResponseMetaToJSON(value.meta), + 'data': BehaviorTypeToJSON(value.data), + }; +} + + diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/GetBehaviorTypeResponseRecord.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/GetBehaviorTypeResponseRecord.ts new file mode 100644 index 00000000000..7113f4a6aa2 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/GetBehaviorTypeResponseRecord.ts @@ -0,0 +1,75 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * 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. + */ + +import {ApiRecordUtils, knownRecordFactories, appFromJS, NormalizedRecordEntities} from "../runtimeSagasAndRecords"; +import {getApiEntitiesState} from "../ApiEntitiesSelectors" +import {List, Record, RecordOf, Map} from 'immutable'; +import {Schema, schema, NormalizedSchema} from "normalizr"; +import {select, call} from "redux-saga/effects"; + +import { + GetBehaviorTypeResponse, +} from './GetBehaviorTypeResponse'; + +import { + BehaviorType, +} from './BehaviorType'; +import { + ResponseMeta, +} from './ResponseMeta'; + +import { + ResponseMetaRecord, + responseMetaRecordUtils +} from './ResponseMetaRecord'; + +export const GetBehaviorTypeResponseRecordProps = { + recType: "GetBehaviorTypeResponseApiRecord" as "GetBehaviorTypeResponseApiRecord", + meta: ResponseMetaRecord(), + data: null as BehaviorType | null, +}; + +export type GetBehaviorTypeResponseRecordPropsType = typeof GetBehaviorTypeResponseRecordProps; +export const GetBehaviorTypeResponseRecord = Record(GetBehaviorTypeResponseRecordProps, GetBehaviorTypeResponseRecordProps.recType); +export type GetBehaviorTypeResponseRecord = RecordOf; + +knownRecordFactories.set(GetBehaviorTypeResponseRecordProps.recType, GetBehaviorTypeResponseRecord); + + +class GetBehaviorTypeResponseRecordUtils extends ApiRecordUtils { + public normalize(apiObject: GetBehaviorTypeResponse, asEntity?: boolean): GetBehaviorTypeResponse { + (apiObject as any).recType = GetBehaviorTypeResponseRecordProps.recType; + responseMetaRecordUtils.normalize(apiObject.meta); + return apiObject; + } + + public toApi(record: GetBehaviorTypeResponseRecord): GetBehaviorTypeResponse { + const apiObject = super.toApi(record); + apiObject.meta = responseMetaRecordUtils.toApi(record.meta); + return apiObject; + } + + public fromApiPassthrough(apiObject: GetBehaviorTypeResponse): BehaviorType { + return apiObject.data!; + } + + public fromApiPassthroughAsEntities(apiObject: GetBehaviorTypeResponse): NormalizedRecordEntities { + console.log("entities revival not supported on this response"); + return {entities: {}, result: List()}; + } +} + +export const getBehaviorTypeResponseRecordUtils = new GetBehaviorTypeResponseRecordUtils(); + + diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/GetMatchingPartsResponse.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/GetMatchingPartsResponse.ts new file mode 100644 index 00000000000..ea8f86a0252 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/GetMatchingPartsResponse.ts @@ -0,0 +1,76 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * 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. + */ + +import { exists, mapValues } from '../runtime'; +import { + MatchingParts, + MatchingPartsFromJSON, + MatchingPartsFromJSONTyped, + MatchingPartsToJSON, + ResponseMeta, + ResponseMetaFromJSON, + ResponseMetaFromJSONTyped, + ResponseMetaToJSON, +} from './'; + +/** + * + * @export + * @interface GetMatchingPartsResponse + */ +export interface GetMatchingPartsResponse { + /** + * + * @type {ResponseMeta} + * @memberof GetMatchingPartsResponse + */ + meta: ResponseMeta; + /** + * + * @type {MatchingParts} + * @memberof GetMatchingPartsResponse + */ + data?: MatchingParts; +} + +export function GetMatchingPartsResponseFromJSON(json: any): GetMatchingPartsResponse { + return GetMatchingPartsResponseFromJSONTyped(json, false); +} + +export function GetMatchingPartsResponseFromJSONTyped(json: any, ignoreDiscriminator: boolean): GetMatchingPartsResponse { + if ((json === undefined) || (json === null)) { + return json; + } + return { + + 'meta': ResponseMetaFromJSON(json['meta']), + 'data': !exists(json, 'data') ? undefined : MatchingPartsFromJSON(json['data']), + }; +} + +export function GetMatchingPartsResponseToJSON(value?: GetMatchingPartsResponse | null): any { + if (value === undefined) { + return undefined; + } + if (value === null) { + return null; + } + return { + + 'meta': ResponseMetaToJSON(value.meta), + 'data': MatchingPartsToJSON(value.data), + }; +} + + diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/GetMatchingPartsResponseRecord.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/GetMatchingPartsResponseRecord.ts new file mode 100644 index 00000000000..6b73951b1df --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/GetMatchingPartsResponseRecord.ts @@ -0,0 +1,83 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * 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. + */ + +import {ApiRecordUtils, knownRecordFactories, appFromJS, NormalizedRecordEntities} from "../runtimeSagasAndRecords"; +import {getApiEntitiesState} from "../ApiEntitiesSelectors" +import {List, Record, RecordOf, Map} from 'immutable'; +import {Schema, schema, NormalizedSchema} from "normalizr"; +import {select, call} from "redux-saga/effects"; + +import { + GetMatchingPartsResponse, +} from './GetMatchingPartsResponse'; + +import { + MatchingParts, +} from './MatchingParts'; +import { + ResponseMeta, +} from './ResponseMeta'; + +import { + MatchingPartsRecord, + matchingPartsRecordUtils +} from './MatchingPartsRecord'; +import { + ResponseMetaRecord, + responseMetaRecordUtils +} from './ResponseMetaRecord'; + +export const GetMatchingPartsResponseRecordProps = { + recType: "GetMatchingPartsResponseApiRecord" as "GetMatchingPartsResponseApiRecord", + meta: ResponseMetaRecord(), + data: (MatchingPartsRecord(), null as MatchingPartsRecord | null), +}; + +export type GetMatchingPartsResponseRecordPropsType = typeof GetMatchingPartsResponseRecordProps; +export const GetMatchingPartsResponseRecord = Record(GetMatchingPartsResponseRecordProps, GetMatchingPartsResponseRecordProps.recType); +export type GetMatchingPartsResponseRecord = RecordOf; + +knownRecordFactories.set(GetMatchingPartsResponseRecordProps.recType, GetMatchingPartsResponseRecord); + + +class GetMatchingPartsResponseRecordUtils extends ApiRecordUtils { + public normalize(apiObject: GetMatchingPartsResponse, asEntity?: boolean): GetMatchingPartsResponse { + (apiObject as any).recType = GetMatchingPartsResponseRecordProps.recType; + responseMetaRecordUtils.normalize(apiObject.meta); + if (apiObject.data) { matchingPartsRecordUtils.normalize(apiObject.data); } + return apiObject; + } + + public toApi(record: GetMatchingPartsResponseRecord): GetMatchingPartsResponse { + const apiObject = super.toApi(record); + apiObject.meta = responseMetaRecordUtils.toApi(record.meta); + if (record.data) { apiObject.data = matchingPartsRecordUtils.toApi(record.data); } + return apiObject; + } + + public fromApiPassthrough(apiObject: GetMatchingPartsResponse): MatchingPartsRecord { + if (!apiObject.data) {return MatchingPartsRecord(); } + const normalizedApiObject = matchingPartsRecordUtils.normalize(apiObject.data); + return appFromJS(normalizedApiObject); + } + + public fromApiPassthroughAsEntities(apiObject: GetMatchingPartsResponse): NormalizedRecordEntities { + console.log("entities revival not supported on this response"); + return {entities: {}, result: List()}; + } +} + +export const getMatchingPartsResponseRecordUtils = new GetMatchingPartsResponseRecordUtils(); + + diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/GetPetPartTypeResponse.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/GetPetPartTypeResponse.ts new file mode 100644 index 00000000000..b0b43d1b96b --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/GetPetPartTypeResponse.ts @@ -0,0 +1,76 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * 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. + */ + +import { exists, mapValues } from '../runtime'; +import { + PetPartType, + PetPartTypeFromJSON, + PetPartTypeFromJSONTyped, + PetPartTypeToJSON, + ResponseMeta, + ResponseMetaFromJSON, + ResponseMetaFromJSONTyped, + ResponseMetaToJSON, +} from './'; + +/** + * + * @export + * @interface GetPetPartTypeResponse + */ +export interface GetPetPartTypeResponse { + /** + * + * @type {ResponseMeta} + * @memberof GetPetPartTypeResponse + */ + meta: ResponseMeta; + /** + * + * @type {PetPartType} + * @memberof GetPetPartTypeResponse + */ + data?: PetPartType; +} + +export function GetPetPartTypeResponseFromJSON(json: any): GetPetPartTypeResponse { + return GetPetPartTypeResponseFromJSONTyped(json, false); +} + +export function GetPetPartTypeResponseFromJSONTyped(json: any, ignoreDiscriminator: boolean): GetPetPartTypeResponse { + if ((json === undefined) || (json === null)) { + return json; + } + return { + + 'meta': ResponseMetaFromJSON(json['meta']), + 'data': !exists(json, 'data') ? undefined : PetPartTypeFromJSON(json['data']), + }; +} + +export function GetPetPartTypeResponseToJSON(value?: GetPetPartTypeResponse | null): any { + if (value === undefined) { + return undefined; + } + if (value === null) { + return null; + } + return { + + 'meta': ResponseMetaToJSON(value.meta), + 'data': PetPartTypeToJSON(value.data), + }; +} + + diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/GetPetPartTypeResponseRecord.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/GetPetPartTypeResponseRecord.ts new file mode 100644 index 00000000000..69caf5d0546 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/GetPetPartTypeResponseRecord.ts @@ -0,0 +1,75 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * 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. + */ + +import {ApiRecordUtils, knownRecordFactories, appFromJS, NormalizedRecordEntities} from "../runtimeSagasAndRecords"; +import {getApiEntitiesState} from "../ApiEntitiesSelectors" +import {List, Record, RecordOf, Map} from 'immutable'; +import {Schema, schema, NormalizedSchema} from "normalizr"; +import {select, call} from "redux-saga/effects"; + +import { + GetPetPartTypeResponse, +} from './GetPetPartTypeResponse'; + +import { + PetPartType, +} from './PetPartType'; +import { + ResponseMeta, +} from './ResponseMeta'; + +import { + ResponseMetaRecord, + responseMetaRecordUtils +} from './ResponseMetaRecord'; + +export const GetPetPartTypeResponseRecordProps = { + recType: "GetPetPartTypeResponseApiRecord" as "GetPetPartTypeResponseApiRecord", + meta: ResponseMetaRecord(), + data: null as PetPartType | null, +}; + +export type GetPetPartTypeResponseRecordPropsType = typeof GetPetPartTypeResponseRecordProps; +export const GetPetPartTypeResponseRecord = Record(GetPetPartTypeResponseRecordProps, GetPetPartTypeResponseRecordProps.recType); +export type GetPetPartTypeResponseRecord = RecordOf; + +knownRecordFactories.set(GetPetPartTypeResponseRecordProps.recType, GetPetPartTypeResponseRecord); + + +class GetPetPartTypeResponseRecordUtils extends ApiRecordUtils { + public normalize(apiObject: GetPetPartTypeResponse, asEntity?: boolean): GetPetPartTypeResponse { + (apiObject as any).recType = GetPetPartTypeResponseRecordProps.recType; + responseMetaRecordUtils.normalize(apiObject.meta); + return apiObject; + } + + public toApi(record: GetPetPartTypeResponseRecord): GetPetPartTypeResponse { + const apiObject = super.toApi(record); + apiObject.meta = responseMetaRecordUtils.toApi(record.meta); + return apiObject; + } + + public fromApiPassthrough(apiObject: GetPetPartTypeResponse): PetPartType { + return apiObject.data!; + } + + public fromApiPassthroughAsEntities(apiObject: GetPetPartTypeResponse): NormalizedRecordEntities { + console.log("entities revival not supported on this response"); + return {entities: {}, result: List()}; + } +} + +export const getPetPartTypeResponseRecordUtils = new GetPetPartTypeResponseRecordUtils(); + + diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/ItemId.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/ItemId.ts new file mode 100644 index 00000000000..c158400740c --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/ItemId.ts @@ -0,0 +1,65 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * 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. + */ + +import { exists, mapValues } from '../runtime'; +/** + * Simplified identifier of an item + * @export + * @interface ItemId + */ +export interface ItemId { + /** + * Unique identifier of the item + * @type {string} + * @memberof ItemId + */ + id: string; + /** + * playlist + * @type {string} + * @memberof ItemId + */ + type: string; +} + +export function ItemIdFromJSON(json: any): ItemId { + return ItemIdFromJSONTyped(json, false); +} + +export function ItemIdFromJSONTyped(json: any, ignoreDiscriminator: boolean): ItemId { + if ((json === undefined) || (json === null)) { + return json; + } + return { + + 'id': json['id'], + 'type': json['type'], + }; +} + +export function ItemIdToJSON(value?: ItemId | null): any { + if (value === undefined) { + return undefined; + } + if (value === null) { + return null; + } + return { + + 'id': value.id, + 'type': value.type, + }; +} + + diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/ItemIdRecord.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/ItemIdRecord.ts new file mode 100644 index 00000000000..6980c92e9b8 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/ItemIdRecord.ts @@ -0,0 +1,54 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * 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. + */ + +import {ApiRecordUtils, knownRecordFactories} from "../runtimeSagasAndRecords"; +import {getApiEntitiesState} from "../ApiEntitiesSelectors" +import {List, Record, RecordOf, Map} from 'immutable'; +import {Schema, schema, NormalizedSchema} from "normalizr"; +import {select, call} from "redux-saga/effects"; + +import { + ItemId, +} from './ItemId'; + + + +export const ItemIdRecordProps = { + recType: "ItemIdApiRecord" as "ItemIdApiRecord", + id: "", + type: "", +}; + +export type ItemIdRecordPropsType = typeof ItemIdRecordProps; +export const ItemIdRecord = Record(ItemIdRecordProps, ItemIdRecordProps.recType); +export type ItemIdRecord = RecordOf; + +knownRecordFactories.set(ItemIdRecordProps.recType, ItemIdRecord); + + +class ItemIdRecordUtils extends ApiRecordUtils { + public normalize(apiObject: ItemId, asEntity?: boolean): ItemId { + (apiObject as any).recType = ItemIdRecordProps.recType; + return apiObject; + } + + public toApi(record: ItemIdRecord): ItemId { + const apiObject = super.toApi(record); + return apiObject; + } +} + +export const itemIdRecordUtils = new ItemIdRecordUtils(); + + diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/MatchingParts.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/MatchingParts.ts new file mode 100644 index 00000000000..790f42e9a53 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/MatchingParts.ts @@ -0,0 +1,72 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * 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. + */ + +import { exists, mapValues } from '../runtime'; +import { + Part, + PartFromJSON, + PartFromJSONTyped, + PartToJSON, +} from './'; + +/** + * Contains all the matching parts + * @export + * @interface MatchingParts + */ +export interface MatchingParts { + /** + * List of all the connected parts + * @type {Array} + * @memberof MatchingParts + */ + connected: Array; + /** + * List of all the related parts + * @type {Array} + * @memberof MatchingParts + */ + related: Array; +} + +export function MatchingPartsFromJSON(json: any): MatchingParts { + return MatchingPartsFromJSONTyped(json, false); +} + +export function MatchingPartsFromJSONTyped(json: any, ignoreDiscriminator: boolean): MatchingParts { + if ((json === undefined) || (json === null)) { + return json; + } + return { + + 'connected': ((json['connected'] as Array).map(PartFromJSON)), + 'related': ((json['related'] as Array).map(PartFromJSON)), + }; +} + +export function MatchingPartsToJSON(value?: MatchingParts | null): any { + if (value === undefined) { + return undefined; + } + if (value === null) { + return null; + } + return { + + 'connected': ((value.connected as Array).map(PartToJSON)), + 'related': ((value.related as Array).map(PartToJSON)), + }; +} + + diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/MatchingPartsRecord.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/MatchingPartsRecord.ts new file mode 100644 index 00000000000..edc7d033ebd --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/MatchingPartsRecord.ts @@ -0,0 +1,65 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * 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. + */ + +import {ApiRecordUtils, knownRecordFactories} from "../runtimeSagasAndRecords"; +import {getApiEntitiesState} from "../ApiEntitiesSelectors" +import {List, Record, RecordOf, Map} from 'immutable'; +import {Schema, schema, NormalizedSchema} from "normalizr"; +import {select, call} from "redux-saga/effects"; + +import { + MatchingParts, +} from './MatchingParts'; + +import { + Part, +} from './Part'; + +import { + PartRecord, + partRecordUtils +} from './PartRecord'; + +export const MatchingPartsRecordProps = { + recType: "MatchingPartsApiRecord" as "MatchingPartsApiRecord", + connected: (PartRecord(), List()), + related: (PartRecord(), List()), +}; + +export type MatchingPartsRecordPropsType = typeof MatchingPartsRecordProps; +export const MatchingPartsRecord = Record(MatchingPartsRecordProps, MatchingPartsRecordProps.recType); +export type MatchingPartsRecord = RecordOf; + +knownRecordFactories.set(MatchingPartsRecordProps.recType, MatchingPartsRecord); + + +class MatchingPartsRecordUtils extends ApiRecordUtils { + public normalize(apiObject: MatchingParts, asEntity?: boolean): MatchingParts { + (apiObject as any).recType = MatchingPartsRecordProps.recType; + partRecordUtils.normalizeArray(apiObject.connected); + partRecordUtils.normalizeArray(apiObject.related); + return apiObject; + } + + public toApi(record: MatchingPartsRecord): MatchingParts { + const apiObject = super.toApi(record); + apiObject.connected = partRecordUtils.toApiArray(record.connected); + apiObject.related = partRecordUtils.toApiArray(record.related); + return apiObject; + } +} + +export const matchingPartsRecordUtils = new MatchingPartsRecordUtils(); + + diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/ModelApiResponse.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/ModelApiResponse.ts new file mode 100644 index 00000000000..63fa57adc03 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/ModelApiResponse.ts @@ -0,0 +1,73 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * 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. + */ + +import { exists, mapValues } from '../runtime'; +/** + * Describes the result of uploading an image resource + * @export + * @interface ModelApiResponse + */ +export interface ModelApiResponse { + /** + * + * @type {number} + * @memberof ModelApiResponse + */ + code?: number; + /** + * + * @type {string} + * @memberof ModelApiResponse + */ + type?: string; + /** + * + * @type {string} + * @memberof ModelApiResponse + */ + message?: string; +} + +export function ModelApiResponseFromJSON(json: any): ModelApiResponse { + return ModelApiResponseFromJSONTyped(json, false); +} + +export function ModelApiResponseFromJSONTyped(json: any, ignoreDiscriminator: boolean): ModelApiResponse { + if ((json === undefined) || (json === null)) { + return json; + } + return { + + 'code': !exists(json, 'code') ? undefined : json['code'], + 'type': !exists(json, 'type') ? undefined : json['type'], + 'message': !exists(json, 'message') ? undefined : json['message'], + }; +} + +export function ModelApiResponseToJSON(value?: ModelApiResponse | null): any { + if (value === undefined) { + return undefined; + } + if (value === null) { + return null; + } + return { + + 'code': value.code, + 'type': value.type, + 'message': value.message, + }; +} + + diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/ModelApiResponseRecord.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/ModelApiResponseRecord.ts new file mode 100644 index 00000000000..6a246575576 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/ModelApiResponseRecord.ts @@ -0,0 +1,55 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * 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. + */ + +import {ApiRecordUtils, knownRecordFactories} from "../runtimeSagasAndRecords"; +import {getApiEntitiesState} from "../ApiEntitiesSelectors" +import {List, Record, RecordOf, Map} from 'immutable'; +import {Schema, schema, NormalizedSchema} from "normalizr"; +import {select, call} from "redux-saga/effects"; + +import { + ModelApiResponse, +} from './ModelApiResponse'; + + + +export const ModelApiResponseRecordProps = { + recType: "ModelApiResponseApiRecord" as "ModelApiResponseApiRecord", + code: null as number | null, + type: null as string | null, + message: null as string | null, +}; + +export type ModelApiResponseRecordPropsType = typeof ModelApiResponseRecordProps; +export const ModelApiResponseRecord = Record(ModelApiResponseRecordProps, ModelApiResponseRecordProps.recType); +export type ModelApiResponseRecord = RecordOf; + +knownRecordFactories.set(ModelApiResponseRecordProps.recType, ModelApiResponseRecord); + + +class ModelApiResponseRecordUtils extends ApiRecordUtils { + public normalize(apiObject: ModelApiResponse, asEntity?: boolean): ModelApiResponse { + (apiObject as any).recType = ModelApiResponseRecordProps.recType; + return apiObject; + } + + public toApi(record: ModelApiResponseRecord): ModelApiResponse { + const apiObject = super.toApi(record); + return apiObject; + } +} + +export const modelApiResponseRecordUtils = new ModelApiResponseRecordUtils(); + + diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/ModelError.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/ModelError.ts new file mode 100644 index 00000000000..be3cda0de1b --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/ModelError.ts @@ -0,0 +1,88 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * 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. + */ + +import { exists, mapValues } from '../runtime'; +import { + ItemId, + ItemIdFromJSON, + ItemIdFromJSONTyped, + ItemIdToJSON, +} from './'; + +/** + * This represent an error normally linked to a specific item from a previous request + * @export + * @interface ModelError + */ +export interface ModelError { + /** + * Usually contains the simple name of the exception + * @type {string} + * @memberof ModelError + */ + type: string; + /** + * + * @type {ItemId} + * @memberof ModelError + */ + itemInfo?: ItemId; + /** + * Simple explanation of the error + * @type {string} + * @memberof ModelError + */ + details?: string; + /** + * Message of the exception that will help developer to debug this problem if needed + * @type {string} + * @memberof ModelError + */ + exception?: string; +} + +export function ModelErrorFromJSON(json: any): ModelError { + return ModelErrorFromJSONTyped(json, false); +} + +export function ModelErrorFromJSONTyped(json: any, ignoreDiscriminator: boolean): ModelError { + if ((json === undefined) || (json === null)) { + return json; + } + return { + + 'type': json['type'], + 'itemInfo': !exists(json, 'itemInfo') ? undefined : ItemIdFromJSON(json['itemInfo']), + 'details': !exists(json, 'details') ? undefined : json['details'], + 'exception': !exists(json, 'exception') ? undefined : json['exception'], + }; +} + +export function ModelErrorToJSON(value?: ModelError | null): any { + if (value === undefined) { + return undefined; + } + if (value === null) { + return null; + } + return { + + 'type': value.type, + 'itemInfo': ItemIdToJSON(value.itemInfo), + 'details': value.details, + 'exception': value.exception, + }; +} + + diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/ModelErrorRecord.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/ModelErrorRecord.ts new file mode 100644 index 00000000000..29f964f5f14 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/ModelErrorRecord.ts @@ -0,0 +1,65 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * 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. + */ + +import {ApiRecordUtils, knownRecordFactories} from "../runtimeSagasAndRecords"; +import {getApiEntitiesState} from "../ApiEntitiesSelectors" +import {List, Record, RecordOf, Map} from 'immutable'; +import {Schema, schema, NormalizedSchema} from "normalizr"; +import {select, call} from "redux-saga/effects"; + +import { + ModelError, +} from './ModelError'; + +import { + ItemId, +} from './ItemId'; + +import { + ItemIdRecord, + itemIdRecordUtils +} from './ItemIdRecord'; + +export const ModelErrorRecordProps = { + recType: "ModelErrorApiRecord" as "ModelErrorApiRecord", + type: 'GenericException', + itemInfo: (ItemIdRecord(), null as ItemIdRecord | null), + details: null as string | null, + exception: null as string | null, +}; + +export type ModelErrorRecordPropsType = typeof ModelErrorRecordProps; +export const ModelErrorRecord = Record(ModelErrorRecordProps, ModelErrorRecordProps.recType); +export type ModelErrorRecord = RecordOf; + +knownRecordFactories.set(ModelErrorRecordProps.recType, ModelErrorRecord); + + +class ModelErrorRecordUtils extends ApiRecordUtils { + public normalize(apiObject: ModelError, asEntity?: boolean): ModelError { + (apiObject as any).recType = ModelErrorRecordProps.recType; + if (apiObject.itemInfo) { itemIdRecordUtils.normalize(apiObject.itemInfo); } + return apiObject; + } + + public toApi(record: ModelErrorRecord): ModelError { + const apiObject = super.toApi(record); + if (record.itemInfo) { apiObject.itemInfo = itemIdRecordUtils.toApi(record.itemInfo); } + return apiObject; + } +} + +export const modelErrorRecordUtils = new ModelErrorRecordUtils(); + + diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/Order.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/Order.ts new file mode 100644 index 00000000000..79b7455a617 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/Order.ts @@ -0,0 +1,107 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * 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. + */ + +import { exists, mapValues } from '../runtime'; +/** + * An order for a pets from the pet store + * @export + * @interface Order + */ +export interface Order { + /** + * + * @type {number} + * @memberof Order + */ + id?: number; + /** + * + * @type {number} + * @memberof Order + */ + petId?: number; + /** + * + * @type {number} + * @memberof Order + */ + quantity?: number; + /** + * + * @type {Date} + * @memberof Order + */ + shipDate?: Date; + /** + * Order Status + * @type {string} + * @memberof Order + */ + status?: OrderStatusEnum; + /** + * + * @type {boolean} + * @memberof Order + */ + complete?: boolean; +} + +/** +* @export +* @enum {string} +*/ +export enum OrderStatusEnum { + Placed = 'placed', + Approved = 'approved', + Delivered = 'delivered' +} + +export function OrderFromJSON(json: any): Order { + return OrderFromJSONTyped(json, false); +} + +export function OrderFromJSONTyped(json: any, ignoreDiscriminator: boolean): Order { + if ((json === undefined) || (json === null)) { + return json; + } + return { + + 'id': !exists(json, 'id') ? undefined : json['id'], + 'petId': !exists(json, 'petId') ? undefined : json['petId'], + 'quantity': !exists(json, 'quantity') ? undefined : json['quantity'], + 'shipDate': !exists(json, 'shipDate') ? undefined : (new Date(json['shipDate'])), + 'status': !exists(json, 'status') ? undefined : json['status'], + 'complete': !exists(json, 'complete') ? undefined : json['complete'], + }; +} + +export function OrderToJSON(value?: Order | null): any { + if (value === undefined) { + return undefined; + } + if (value === null) { + return null; + } + return { + + 'id': value.id, + 'petId': value.petId, + 'quantity': value.quantity, + 'shipDate': value.shipDate === undefined ? undefined : (value.shipDate.toISOString()), + 'status': value.status, + 'complete': value.complete, + }; +} + + 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 new file mode 100644 index 00000000000..621b298df80 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/OrderRecord.ts @@ -0,0 +1,109 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * 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. + */ + +import {ApiRecordUtils, knownRecordFactories} from "../runtimeSagasAndRecords"; +import {getApiEntitiesState} from "../ApiEntitiesSelectors" +import {List, Record, RecordOf, Map} from 'immutable'; +import {Schema, schema, NormalizedSchema} from "normalizr"; +import {select, call} from "redux-saga/effects"; + +import { + Order, + OrderStatusEnum, +} from './Order'; + + + +export const OrderRecordProps = { + recType: "OrderApiRecord" as "OrderApiRecord", + id: null as string | null, + petId: null as number | null, + quantity: null as number | null, + shipDate: null as Date | null, + status: null as OrderStatusEnum | null, + complete: null as boolean | null, +}; + +export type OrderRecordPropsType = typeof OrderRecordProps; +export const OrderRecord = Record(OrderRecordProps, OrderRecordProps.recType); +export type OrderRecord = RecordOf; + +knownRecordFactories.set(OrderRecordProps.recType, OrderRecord); + +export const OrderRecordEntityProps = { + ...OrderRecordProps, + recType: "OrderApiRecordEntity" as "OrderApiRecordEntity", +}; + +export type OrderRecordEntityPropsType = typeof OrderRecordEntityProps; +export const OrderRecordEntity = Record(OrderRecordEntityProps, OrderRecordEntityProps.recType); +export type OrderRecordEntity = RecordOf; + +knownRecordFactories.set(OrderRecordEntityProps.recType, OrderRecordEntity); + +class OrderRecordUtils extends ApiRecordUtils { + public normalize(apiObject: Order, asEntity?: boolean): Order { + (apiObject as any).recType = asEntity ? OrderRecordEntityProps.recType : OrderRecordProps.recType; + if (apiObject.id) { (apiObject as any).id = apiObject.id.toString(); } + return apiObject; + } + + public getSchema(): Schema { + return new schema.Entity("order", { + }); + } + + public *toInlined(entityId?: string | null) { + if (!entityId) {return undefined; } + const entity = yield select(apiEntityOrderSelector, {id: entityId}); + if (!entity) {return undefined; } + + const { + recType, + ...unchangedProperties + } = entity; + + const entityProperties = { + } + + return OrderRecord({ + ...unchangedProperties, + ...entityProperties + }); + } + + public *toInlinedArray(entityIds: List | null) { + if (!entityIds) {return null; } + let entities = List(); + for (let entityIndex = 0; entityIndex < entityIds.count(); entityIndex++) { + const entity = yield call(this.toInlined, entityIds.get(entityIndex)); + if (entity) { + entities.push(entity); + } + } + return entities; + } + + public toApi(record: OrderRecord): Order { + const apiObject = super.toApi(record); + if (record.id) { apiObject.id = parseFloat(record.id); } + return apiObject; + } +} + +export const orderRecordUtils = new OrderRecordUtils(); + +export const apiEntitiesOrderSelector = (state: any) => getApiEntitiesState(state).order as Map; +export const apiEntityOrderSelector = (state: any, {id}: {id?: string | null}) => id ? apiEntitiesOrderSelector(state).get(id) : undefined; + diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/Part.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/Part.ts new file mode 100644 index 00000000000..e5a66755d75 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/Part.ts @@ -0,0 +1,65 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * 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. + */ + +import { exists, mapValues } from '../runtime'; +/** + * Contains all the info about a pet part + * @export + * @interface Part + */ +export interface Part { + /** + * Unique identifier from the database + * @type {number} + * @memberof Part + */ + id: number; + /** + * Name of the part + * @type {string} + * @memberof Part + */ + name: string; +} + +export function PartFromJSON(json: any): Part { + return PartFromJSONTyped(json, false); +} + +export function PartFromJSONTyped(json: any, ignoreDiscriminator: boolean): Part { + if ((json === undefined) || (json === null)) { + return json; + } + return { + + 'id': json['id'], + 'name': json['name'], + }; +} + +export function PartToJSON(value?: Part | null): any { + if (value === undefined) { + return undefined; + } + if (value === null) { + return null; + } + return { + + 'id': value.id, + 'name': value.name, + }; +} + + diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/PartRecord.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/PartRecord.ts new file mode 100644 index 00000000000..0bbd36a831a --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/PartRecord.ts @@ -0,0 +1,56 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * 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. + */ + +import {ApiRecordUtils, knownRecordFactories} from "../runtimeSagasAndRecords"; +import {getApiEntitiesState} from "../ApiEntitiesSelectors" +import {List, Record, RecordOf, Map} from 'immutable'; +import {Schema, schema, NormalizedSchema} from "normalizr"; +import {select, call} from "redux-saga/effects"; + +import { + Part, +} from './Part'; + + + +export const PartRecordProps = { + recType: "PartApiRecord" as "PartApiRecord", + id: "-1", + name: "", +}; + +export type PartRecordPropsType = typeof PartRecordProps; +export const PartRecord = Record(PartRecordProps, PartRecordProps.recType); +export type PartRecord = RecordOf; + +knownRecordFactories.set(PartRecordProps.recType, PartRecord); + + +class PartRecordUtils extends ApiRecordUtils { + public normalize(apiObject: Part, asEntity?: boolean): Part { + (apiObject as any).recType = PartRecordProps.recType; + (apiObject as any).id = apiObject.id.toString(); + return apiObject; + } + + public toApi(record: PartRecord): Part { + const apiObject = super.toApi(record); + apiObject.id = parseFloat(record.id); + return apiObject; + } +} + +export const partRecordUtils = new PartRecordUtils(); + + diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/Pet.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/Pet.ts new file mode 100644 index 00000000000..4a79974b1ef --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/Pet.ts @@ -0,0 +1,238 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * 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. + */ + +import { exists, mapValues } from '../runtime'; +import { + Category, + CategoryFromJSON, + CategoryFromJSONTyped, + CategoryToJSON, + DeploymentRequestStatus, + DeploymentRequestStatusFromJSON, + DeploymentRequestStatusFromJSONTyped, + DeploymentRequestStatusToJSON, + Tag, + TagFromJSON, + TagFromJSONTyped, + TagToJSON, + WarningCode, + WarningCodeFromJSON, + WarningCodeFromJSONTyped, + WarningCodeToJSON, +} from './'; + +/** + * A pet for sale in the pet store + * @export + * @interface Pet + */ +export interface Pet { + /** + * + * @type {number} + * @memberof Pet + */ + id: number; + /** + * + * @type {number} + * @memberof Pet + */ + friendId?: number; + /** + * + * @type {Array} + * @memberof Pet + */ + otherFriendIds: Array; + /** + * + * @type {number} + * @memberof Pet + */ + friendAge: number; + /** + * + * @type {number} + * @memberof Pet + */ + age: number; + /** + * + * @type {boolean} + * @memberof Pet + */ + isHappy: boolean; + /** + * + * @type {boolean} + * @memberof Pet + */ + isTall: boolean; + /** + * + * @type {Category} + * @memberof Pet + */ + category: Category; + /** + * + * @type {Category} + * @memberof Pet + */ + optionalCategory?: Category; + /** + * + * @type {string} + * @memberof Pet + */ + name: string; + /** + * + * @type {Array} + * @memberof Pet + */ + _entries?: Array; + /** + * + * @type {string} + * @memberof Pet + */ + surname?: string; + /** + * + * @type {Array} + * @memberof Pet + */ + photoUrls: Array; + /** + * + * @type {WarningCode} + * @memberof Pet + */ + warningStatus: WarningCode; + /** + * + * @type {DeploymentRequestStatus} + * @memberof Pet + */ + depStatus?: DeploymentRequestStatus; + /** + * + * @type {DeploymentRequestStatus} + * @memberof Pet + */ + alternateStatus: DeploymentRequestStatus; + /** + * + * @type {Array} + * @memberof Pet + */ + otherDepStatuses: Array; + /** + * + * @type {Array} + * @memberof Pet + */ + tags: Array; + /** + * + * @type {Array} + * @memberof Pet + */ + optionalTags?: Array; + /** + * pet status in the store + * @type {string} + * @memberof Pet + */ + status: PetStatusEnum; +} + +/** +* @export +* @enum {string} +*/ +export enum PetStatusEnum { + Available = 'available', + Pending = 'pending', + Sold = 'sold' +} + +export function PetFromJSON(json: any): Pet { + return PetFromJSONTyped(json, false); +} + +export function PetFromJSONTyped(json: any, ignoreDiscriminator: boolean): Pet { + if ((json === undefined) || (json === null)) { + return json; + } + return { + + 'id': json['id'], + 'friendId': !exists(json, 'friendId') ? undefined : json['friendId'], + 'otherFriendIds': json['otherFriendIds'], + 'friendAge': json['friendAge'], + 'age': json['age'], + 'isHappy': json['isHappy'], + 'isTall': json['isTall'], + 'category': CategoryFromJSON(json['category']), + 'optionalCategory': !exists(json, 'optionalCategory') ? undefined : CategoryFromJSON(json['optionalCategory']), + 'name': json['name'], + '_entries': !exists(json, 'entries') ? undefined : ((json['entries'] as Array).map(CategoryFromJSON)), + 'surname': !exists(json, 'surname') ? undefined : json['surname'], + 'photoUrls': json['photoUrls'], + 'warningStatus': WarningCodeFromJSON(json['warningStatus']), + 'depStatus': !exists(json, 'depStatus') ? undefined : DeploymentRequestStatusFromJSON(json['depStatus']), + 'alternateStatus': DeploymentRequestStatusFromJSON(json['alternateStatus']), + 'otherDepStatuses': ((json['otherDepStatuses'] as Array).map(DeploymentRequestStatusFromJSON)), + 'tags': ((json['tags'] as Array).map(TagFromJSON)), + 'optionalTags': !exists(json, 'optionalTags') ? undefined : ((json['optionalTags'] as Array).map(TagFromJSON)), + 'status': json['status'], + }; +} + +export function PetToJSON(value?: Pet | null): any { + if (value === undefined) { + return undefined; + } + if (value === null) { + return null; + } + return { + + 'id': value.id, + 'friendId': value.friendId, + 'otherFriendIds': value.otherFriendIds, + 'friendAge': value.friendAge, + 'age': value.age, + 'isHappy': value.isHappy, + 'isTall': value.isTall, + 'category': CategoryToJSON(value.category), + 'optionalCategory': CategoryToJSON(value.optionalCategory), + 'name': value.name, + 'entries': value._entries === undefined ? undefined : ((value._entries as Array).map(CategoryToJSON)), + 'surname': value.surname, + 'photoUrls': value.photoUrls, + 'warningStatus': WarningCodeToJSON(value.warningStatus), + 'depStatus': DeploymentRequestStatusToJSON(value.depStatus), + 'alternateStatus': DeploymentRequestStatusToJSON(value.alternateStatus), + 'otherDepStatuses': ((value.otherDepStatuses as Array).map(DeploymentRequestStatusToJSON)), + 'tags': ((value.tags as Array).map(TagToJSON)), + 'optionalTags': value.optionalTags === undefined ? undefined : ((value.optionalTags as Array).map(TagToJSON)), + 'status': value.status, + }; +} + + diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/PetPartType.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/PetPartType.ts new file mode 100644 index 00000000000..4b7c05fbd4b --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/PetPartType.ts @@ -0,0 +1,37 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * 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. + */ + +/** + * Type of pet part + * @export + * @enum {string} + */ +export enum PetPartType { + Curved = 'Curved', + Smooth = 'Smooth', + Long = 'Long' +} + +export function PetPartTypeFromJSON(json: any): PetPartType { + return PetPartTypeFromJSONTyped(json, false); +} + +export function PetPartTypeFromJSONTyped(json: any, ignoreDiscriminator: boolean): PetPartType { + return json as PetPartType; +} + +export function PetPartTypeToJSON(value?: PetPartType | null): any { + return value as any; +} + diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/PetPartTypeRecord.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/PetPartTypeRecord.ts new file mode 100644 index 00000000000..65fbcfab763 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/PetPartTypeRecord.ts @@ -0,0 +1 @@ +// This file is not needed and was generated only because of how codegen is built... Enums do not need to be converted to Records and can be used directly. 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 new file mode 100644 index 00000000000..8292c5ee074 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/PetRecord.ts @@ -0,0 +1,177 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * 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. + */ + +import {ApiRecordUtils, knownRecordFactories} from "../runtimeSagasAndRecords"; +import {getApiEntitiesState} from "../ApiEntitiesSelectors" +import {List, Record, RecordOf, Map} from 'immutable'; +import {Schema, schema, NormalizedSchema} from "normalizr"; +import {select, call} from "redux-saga/effects"; + +import { + Pet, + PetStatusEnum, +} from './Pet'; + +import { + Category, +} from './Category'; +import { + DeploymentRequestStatus, +} from './DeploymentRequestStatus'; +import { + Tag, +} from './Tag'; +import { + WarningCode, +} from './WarningCode'; + +import { + CategoryRecord, + categoryRecordUtils +} from './CategoryRecord'; +import { + TagRecord, + tagRecordUtils +} from './TagRecord'; + +export const PetRecordProps = { + recType: "PetApiRecord" as "PetApiRecord", + id: "-1", + friendId: null as string | null, + otherFriendIds: List(), + friendAge: 0, + age: 2, + isHappy: true, + isTall: false, + category: CategoryRecord(), + optionalCategory: (CategoryRecord(), null as CategoryRecord | null), + name: "", + _entries: (CategoryRecord(), null as List | null), + surname: null as string | null, + photoUrls: List(), + warningStatus: WarningCode.ReduceVolumeRangeToAvoidLargeSteps, + depStatus: null as DeploymentRequestStatus | null, + alternateStatus: DeploymentRequestStatus.New, + otherDepStatuses: List(), + tags: (TagRecord(), List()), + optionalTags: (TagRecord(), null as List | null), + status: PetStatusEnum.Pending, +}; + +export type PetRecordPropsType = typeof PetRecordProps; +export const PetRecord = Record(PetRecordProps, PetRecordProps.recType); +export type PetRecord = RecordOf; + +knownRecordFactories.set(PetRecordProps.recType, PetRecord); + +export const PetRecordEntityProps = { + ...PetRecordProps, + recType: "PetApiRecordEntity" as "PetApiRecordEntity", + category: "-1", + optionalCategory: null as string | null, + _entries: null as List | null, + tags: List(), + optionalTags: null as List | null, +}; + +export type PetRecordEntityPropsType = typeof PetRecordEntityProps; +export const PetRecordEntity = Record(PetRecordEntityProps, PetRecordEntityProps.recType); +export type PetRecordEntity = RecordOf; + +knownRecordFactories.set(PetRecordEntityProps.recType, PetRecordEntity); + +class PetRecordUtils extends ApiRecordUtils { + public normalize(apiObject: Pet, asEntity?: boolean): Pet { + (apiObject as any).recType = asEntity ? PetRecordEntityProps.recType : PetRecordProps.recType; + (apiObject as any).id = apiObject.id.toString(); + if (apiObject.friendId) { (apiObject as any).friendId = apiObject.friendId.toString(); } + (apiObject as any).otherFriendIds = apiObject.otherFriendIds.map(item => item.toString()); + categoryRecordUtils.normalize(apiObject.category); + if (apiObject.optionalCategory) { categoryRecordUtils.normalize(apiObject.optionalCategory); } + if (apiObject._entries) { categoryRecordUtils.normalizeArray(apiObject._entries); } + tagRecordUtils.normalizeArray(apiObject.tags); + if (apiObject.optionalTags) { tagRecordUtils.normalizeArray(apiObject.optionalTags); } + return apiObject; + } + + public getSchema(): Schema { + return new schema.Entity("pet", { + category: categoryRecordUtils.getSchema(), + optionalCategory: categoryRecordUtils.getSchema(), + _entries: [categoryRecordUtils.getSchema()], + tags: [tagRecordUtils.getSchema()], + optionalTags: [tagRecordUtils.getSchema()], + }); + } + + public *toInlined(entityId?: string | null) { + if (!entityId) {return undefined; } + const entity = yield select(apiEntityPetSelector, {id: entityId}); + if (!entity) {return undefined; } + + const { + recType, + category: category_original, + optionalCategory: optionalCategory_original, + _entries: _entries_original, + tags: tags_original, + optionalTags: optionalTags_original, + ...unchangedProperties + } = entity; + + const entityProperties = { + category: yield call(categoryRecordUtils.toInlined, entity.category), + optionalCategory: entity.optionalCategory ? yield call(categoryRecordUtils.toInlined, entity.optionalCategory) : null, + _entries: entity._entries ? yield call(categoryRecordUtils.toInlinedArray, entity._entries) : null, + tags: yield call(tagRecordUtils.toInlinedArray, entity.tags), + optionalTags: entity.optionalTags ? yield call(tagRecordUtils.toInlinedArray, entity.optionalTags) : null, + } + + return PetRecord({ + ...unchangedProperties, + ...entityProperties + }); + } + + public *toInlinedArray(entityIds: List | null) { + if (!entityIds) {return null; } + let entities = List(); + for (let entityIndex = 0; entityIndex < entityIds.count(); entityIndex++) { + const entity = yield call(this.toInlined, entityIds.get(entityIndex)); + if (entity) { + entities.push(entity); + } + } + return entities; + } + + public toApi(record: PetRecord): Pet { + const apiObject = super.toApi(record); + apiObject.id = parseFloat(record.id); + if (record.friendId) { apiObject.friendId = parseFloat(record.friendId); } + apiObject.otherFriendIds = record.otherFriendIds.map(item => parseFloat(item)).toArray(); + apiObject.category = categoryRecordUtils.toApi(record.category); + if (record.optionalCategory) { apiObject.optionalCategory = categoryRecordUtils.toApi(record.optionalCategory); } + if (record._entries) { apiObject._entries = categoryRecordUtils.toApiArray(record._entries); } + apiObject.tags = tagRecordUtils.toApiArray(record.tags); + if (record.optionalTags) { apiObject.optionalTags = tagRecordUtils.toApiArray(record.optionalTags); } + return apiObject; + } +} + +export const petRecordUtils = new PetRecordUtils(); + +export const apiEntitiesPetSelector = (state: any) => getApiEntitiesState(state).pet as Map; +export const apiEntityPetSelector = (state: any, {id}: {id?: string | null}) => id ? apiEntitiesPetSelector(state).get(id) : undefined; + diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/ResponseMeta.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/ResponseMeta.ts new file mode 100644 index 00000000000..5b63ca5e8c5 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/ResponseMeta.ts @@ -0,0 +1,134 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * 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. + */ + +import { exists, mapValues } from '../runtime'; +import { + ErrorCode, + ErrorCodeFromJSON, + ErrorCodeFromJSONTyped, + ErrorCodeToJSON, +} from './'; + +/** + * Mandatory part of each response given by our API + * @export + * @interface ResponseMeta + */ +export interface ResponseMeta { + /** + * Code returned by the function + * @type {string} + * @memberof ResponseMeta + */ + code: ResponseMetaCodeEnum; + /** + * Explanation of what went wrong + * @type {string} + * @memberof ResponseMeta + */ + detail?: string; + /** + * Message of the exception that will help developer to debug this problem if needed + * @type {string} + * @memberof ResponseMeta + */ + exception?: string; + /** + * Type of error + * @type {string} + * @memberof ResponseMeta + */ + type?: string; + /** + * + * @type {ErrorCode} + * @memberof ResponseMeta + */ + errorCode?: ErrorCode; + /** + * An array of all the specific error encountered during the request + * @type {Array} + * @memberof ResponseMeta + */ + errors?: Array; +} + +/** +* @export +* @enum {string} +*/ +export enum ResponseMetaCodeEnum { + Ok = 'Ok', + GenericException = 'Generic_Exception', + FieldErrorException = 'Field_Error_Exception', + ImageValidationException = 'Image_Validation_Exception', + InvalidContainerCreationWithNoDefaultAssetException = 'Invalid_Container_Creation_With_No_Default_Asset_Exception', + InvalidOverrideModeException = 'Invalid_Override_Mode_Exception', + InvalidTagException = 'Invalid_Tag_Exception', + ItemUseException = 'Item_Use_Exception', + MissingPlatformForSoftwareException = 'Missing_Platform_For_Software_Exception', + MissingSoftwareForPlatformException = 'Missing_Software_For_Platform_Exception', + PlatformNotSupportedException = 'Platform_Not_Supported_Exception', + RefreshDataException = 'Refresh_Data_Exception', + RoleAssignmentException = 'Role_Assignment_Exception', + TaskAlreadyRunningException = 'Task_Already_Running_Exception', + LoggedOutException = 'Logged_Out_Exception', + AuthorizationException = 'Authorization_Exception', + UnauthorizedActionForCurrentUserException = 'Unauthorized_Action_For_Current_User_Exception', + UserAlreadyExistsButIsNotAuthenticatedException = 'User_Already_Exists_But_Is_Not_Authenticated_Exception', + UserAlreadyHasActiveOrClosedGalaxieApiProductException = 'User_Already_Has_Active_Or_Closed_Galaxie_Api_Product_Exception', + UserAlreadyHasMultipleGalaxieApiProductsException = 'User_Already_Has_Multiple_Galaxie_Api_Products_Exception', + RecurlyApiException = 'Recurly_Api_Exception', + RecurlyTransactionErrorException = 'Recurly_Transaction_Error_Exception', + GalaxieApiException = 'Galaxie_Api_Exception' +} + +export function ResponseMetaFromJSON(json: any): ResponseMeta { + return ResponseMetaFromJSONTyped(json, false); +} + +export function ResponseMetaFromJSONTyped(json: any, ignoreDiscriminator: boolean): ResponseMeta { + if ((json === undefined) || (json === null)) { + return json; + } + return { + + 'code': json['code'], + 'detail': !exists(json, 'detail') ? undefined : json['detail'], + 'exception': !exists(json, 'exception') ? undefined : json['exception'], + 'type': !exists(json, 'type') ? undefined : json['type'], + 'errorCode': !exists(json, 'errorCode') ? undefined : ErrorCodeFromJSON(json['errorCode']), + 'errors': !exists(json, 'errors') ? undefined : json['errors'], + }; +} + +export function ResponseMetaToJSON(value?: ResponseMeta | null): any { + if (value === undefined) { + return undefined; + } + if (value === null) { + return null; + } + return { + + 'code': value.code, + 'detail': value.detail, + 'exception': value.exception, + 'type': value.type, + 'errorCode': ErrorCodeToJSON(value.errorCode), + 'errors': value.errors, + }; +} + + diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/ResponseMetaRecord.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/ResponseMetaRecord.ts new file mode 100644 index 00000000000..79a092e4988 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/ResponseMetaRecord.ts @@ -0,0 +1,62 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * 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. + */ + +import {ApiRecordUtils, knownRecordFactories} from "../runtimeSagasAndRecords"; +import {getApiEntitiesState} from "../ApiEntitiesSelectors" +import {List, Record, RecordOf, Map} from 'immutable'; +import {Schema, schema, NormalizedSchema} from "normalizr"; +import {select, call} from "redux-saga/effects"; + +import { + ResponseMeta, + ResponseMetaCodeEnum, +} from './ResponseMeta'; + +import { + ErrorCode, +} from './ErrorCode'; + + +export const ResponseMetaRecordProps = { + recType: "ResponseMetaApiRecord" as "ResponseMetaApiRecord", + code: ResponseMetaCodeEnum.Ok, + detail: null as string | null, + exception: null as string | null, + type: null as string | null, + errorCode: null as ErrorCode | null, + errors: null as Array | null, +}; + +export type ResponseMetaRecordPropsType = typeof ResponseMetaRecordProps; +export const ResponseMetaRecord = Record(ResponseMetaRecordProps, ResponseMetaRecordProps.recType); +export type ResponseMetaRecord = RecordOf; + +knownRecordFactories.set(ResponseMetaRecordProps.recType, ResponseMetaRecord); + + +class ResponseMetaRecordUtils extends ApiRecordUtils { + public normalize(apiObject: ResponseMeta, asEntity?: boolean): ResponseMeta { + (apiObject as any).recType = ResponseMetaRecordProps.recType; + return apiObject; + } + + public toApi(record: ResponseMetaRecord): ResponseMeta { + const apiObject = super.toApi(record); + return apiObject; + } +} + +export const responseMetaRecordUtils = new ResponseMetaRecordUtils(); + + diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/Tag.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/Tag.ts new file mode 100644 index 00000000000..8ea5895e79b --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/Tag.ts @@ -0,0 +1,65 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * 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. + */ + +import { exists, mapValues } from '../runtime'; +/** + * A tag for a pet + * @export + * @interface Tag + */ +export interface Tag { + /** + * + * @type {number} + * @memberof Tag + */ + id?: number; + /** + * + * @type {string} + * @memberof Tag + */ + name?: string; +} + +export function TagFromJSON(json: any): Tag { + return TagFromJSONTyped(json, false); +} + +export function TagFromJSONTyped(json: any, ignoreDiscriminator: boolean): Tag { + if ((json === undefined) || (json === null)) { + return json; + } + return { + + 'id': !exists(json, 'id') ? undefined : json['id'], + 'name': !exists(json, 'name') ? undefined : json['name'], + }; +} + +export function TagToJSON(value?: Tag | null): any { + if (value === undefined) { + return undefined; + } + if (value === null) { + return null; + } + return { + + 'id': value.id, + 'name': value.name, + }; +} + + 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 new file mode 100644 index 00000000000..dd3b631ac85 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/TagRecord.ts @@ -0,0 +1,104 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * 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. + */ + +import {ApiRecordUtils, knownRecordFactories} from "../runtimeSagasAndRecords"; +import {getApiEntitiesState} from "../ApiEntitiesSelectors" +import {List, Record, RecordOf, Map} from 'immutable'; +import {Schema, schema, NormalizedSchema} from "normalizr"; +import {select, call} from "redux-saga/effects"; + +import { + Tag, +} from './Tag'; + + + +export const TagRecordProps = { + recType: "TagApiRecord" as "TagApiRecord", + id: null as string | null, + name: null as string | null, +}; + +export type TagRecordPropsType = typeof TagRecordProps; +export const TagRecord = Record(TagRecordProps, TagRecordProps.recType); +export type TagRecord = RecordOf; + +knownRecordFactories.set(TagRecordProps.recType, TagRecord); + +export const TagRecordEntityProps = { + ...TagRecordProps, + recType: "TagApiRecordEntity" as "TagApiRecordEntity", +}; + +export type TagRecordEntityPropsType = typeof TagRecordEntityProps; +export const TagRecordEntity = Record(TagRecordEntityProps, TagRecordEntityProps.recType); +export type TagRecordEntity = RecordOf; + +knownRecordFactories.set(TagRecordEntityProps.recType, TagRecordEntity); + +class TagRecordUtils extends ApiRecordUtils { + public normalize(apiObject: Tag, asEntity?: boolean): Tag { + (apiObject as any).recType = asEntity ? TagRecordEntityProps.recType : TagRecordProps.recType; + if (apiObject.id) { (apiObject as any).id = apiObject.id.toString(); } + return apiObject; + } + + public getSchema(): Schema { + return new schema.Entity("tag", { + }); + } + + public *toInlined(entityId?: string | null) { + if (!entityId) {return undefined; } + const entity = yield select(apiEntityTagSelector, {id: entityId}); + if (!entity) {return undefined; } + + const { + recType, + ...unchangedProperties + } = entity; + + const entityProperties = { + } + + return TagRecord({ + ...unchangedProperties, + ...entityProperties + }); + } + + public *toInlinedArray(entityIds: List | null) { + if (!entityIds) {return null; } + let entities = List(); + for (let entityIndex = 0; entityIndex < entityIds.count(); entityIndex++) { + const entity = yield call(this.toInlined, entityIds.get(entityIndex)); + if (entity) { + entities.push(entity); + } + } + return entities; + } + + public toApi(record: TagRecord): Tag { + const apiObject = super.toApi(record); + if (record.id) { apiObject.id = parseFloat(record.id); } + return apiObject; + } +} + +export const tagRecordUtils = new TagRecordUtils(); + +export const apiEntitiesTagSelector = (state: any) => getApiEntitiesState(state).tag as Map; +export const apiEntityTagSelector = (state: any, {id}: {id?: string | null}) => id ? apiEntitiesTagSelector(state).get(id) : undefined; + diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/User.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/User.ts new file mode 100644 index 00000000000..6219c91e3e4 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/User.ts @@ -0,0 +1,129 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * 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. + */ + +import { exists, mapValues } from '../runtime'; +/** + * A User who is purchasing from the pet store + * @export + * @interface User + */ +export interface User { + /** + * + * @type {number} + * @memberof User + */ + id: number; + /** + * + * @type {string} + * @memberof User + */ + username?: string; + /** + * + * @type {string} + * @memberof User + */ + firstName?: string; + /** + * + * @type {string} + * @memberof User + */ + lastName?: string; + /** + * + * @type {string} + * @memberof User + */ + email?: string; + /** + * + * @type {string} + * @memberof User + */ + password?: string; + /** + * + * @type {string} + * @memberof User + */ + phone?: string; + /** + * User Status + * @type {number} + * @memberof User + */ + userStatus?: number; + /** + * + * @type {User} + * @memberof User + */ + subUser?: User; + /** + * + * @type {User} + * @memberof User + */ + subUser2: User; +} + +export function UserFromJSON(json: any): User { + return UserFromJSONTyped(json, false); +} + +export function UserFromJSONTyped(json: any, ignoreDiscriminator: boolean): User { + if ((json === undefined) || (json === null)) { + return json; + } + return { + + 'id': json['id'], + 'username': !exists(json, 'username') ? undefined : json['username'], + 'firstName': !exists(json, 'firstName') ? undefined : json['firstName'], + 'lastName': !exists(json, 'lastName') ? undefined : json['lastName'], + 'email': !exists(json, 'email') ? undefined : json['email'], + 'password': !exists(json, 'password') ? undefined : json['password'], + 'phone': !exists(json, 'phone') ? undefined : json['phone'], + 'userStatus': !exists(json, 'userStatus') ? undefined : json['userStatus'], + 'subUser': !exists(json, 'subUser') ? undefined : UserFromJSON(json['subUser']), + 'subUser2': UserFromJSON(json['subUser2']), + }; +} + +export function UserToJSON(value?: User | null): any { + if (value === undefined) { + return undefined; + } + if (value === null) { + return null; + } + return { + + 'id': value.id, + 'username': value.username, + 'firstName': value.firstName, + 'lastName': value.lastName, + 'email': value.email, + 'password': value.password, + 'phone': value.phone, + 'userStatus': value.userStatus, + 'subUser': UserToJSON(value.subUser), + 'subUser2': UserToJSON(value.subUser2), + }; +} + + 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 new file mode 100644 index 00000000000..292519c32b2 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/UserRecord.ts @@ -0,0 +1,112 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * 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. + */ + +import {ApiRecordUtils, knownRecordFactories} from "../runtimeSagasAndRecords"; +import {getApiEntitiesState} from "../ApiEntitiesSelectors" +import {List, Record, RecordOf, Map} from 'immutable'; +import {Schema, schema, NormalizedSchema} from "normalizr"; +import {select, call} from "redux-saga/effects"; + +import { + User, +} from './User'; + + + +export const UserRecordProps = { + recType: "UserApiRecord" as "UserApiRecord", + id: "-1", + username: null as string | null, + firstName: null as string | null, + lastName: null as string | null, + email: null as string | null, + password: null as string | null, + phone: null as string | null, + userStatus: null as number | null, + subUser: null as User | null, + subUser2: {} as any as User, +}; + +export type UserRecordPropsType = typeof UserRecordProps; +export const UserRecord = Record(UserRecordProps, UserRecordProps.recType); +export type UserRecord = RecordOf; + +knownRecordFactories.set(UserRecordProps.recType, UserRecord); + +export const UserRecordEntityProps = { + ...UserRecordProps, + recType: "UserApiRecordEntity" as "UserApiRecordEntity", +}; + +export type UserRecordEntityPropsType = typeof UserRecordEntityProps; +export const UserRecordEntity = Record(UserRecordEntityProps, UserRecordEntityProps.recType); +export type UserRecordEntity = RecordOf; + +knownRecordFactories.set(UserRecordEntityProps.recType, UserRecordEntity); + +class UserRecordUtils extends ApiRecordUtils { + public normalize(apiObject: User, asEntity?: boolean): User { + (apiObject as any).recType = asEntity ? UserRecordEntityProps.recType : UserRecordProps.recType; + (apiObject as any).id = apiObject.id.toString(); + return apiObject; + } + + public getSchema(): Schema { + return new schema.Entity("user", { + }); + } + + public *toInlined(entityId?: string | null) { + if (!entityId) {return undefined; } + const entity = yield select(apiEntityUserSelector, {id: entityId}); + if (!entity) {return undefined; } + + const { + recType, + ...unchangedProperties + } = entity; + + const entityProperties = { + } + + return UserRecord({ + ...unchangedProperties, + ...entityProperties + }); + } + + public *toInlinedArray(entityIds: List | null) { + if (!entityIds) {return null; } + let entities = List(); + for (let entityIndex = 0; entityIndex < entityIds.count(); entityIndex++) { + const entity = yield call(this.toInlined, entityIds.get(entityIndex)); + if (entity) { + entities.push(entity); + } + } + return entities; + } + + public toApi(record: UserRecord): User { + const apiObject = super.toApi(record); + apiObject.id = parseFloat(record.id); + return apiObject; + } +} + +export const userRecordUtils = new UserRecordUtils(); + +export const apiEntitiesUserSelector = (state: any) => getApiEntitiesState(state).user as Map; +export const apiEntityUserSelector = (state: any, {id}: {id?: string | null}) => id ? apiEntitiesUserSelector(state).get(id) : undefined; + diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/WarningCode.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/WarningCode.ts new file mode 100644 index 00000000000..f0b6dfe654a --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/WarningCode.ts @@ -0,0 +1,37 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * 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. + */ + +/** + * Warning code returned when a potential problem is detected + * @export + * @enum {string} + */ +export enum WarningCode { + ReduceVolumeRangeToAvoidLargeSteps = 'Reduce_Volume_Range_To_Avoid_Large_Steps', + RaiseAmplifierVolume = 'Raise_Amplifier_Volume', + NoVolumeRangeSpecified = 'No_Volume_Range_Specified' +} + +export function WarningCodeFromJSON(json: any): WarningCode { + return WarningCodeFromJSONTyped(json, false); +} + +export function WarningCodeFromJSONTyped(json: any, ignoreDiscriminator: boolean): WarningCode { + return json as WarningCode; +} + +export function WarningCodeToJSON(value?: WarningCode | null): any { + return value as any; +} + diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/WarningCodeRecord.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/WarningCodeRecord.ts new file mode 100644 index 00000000000..65fbcfab763 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/WarningCodeRecord.ts @@ -0,0 +1 @@ +// This file is not needed and was generated only because of how codegen is built... Enums do not need to be converted to Records and can be used directly. diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/index.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/index.ts new file mode 100644 index 00000000000..6881bb9feda --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/index.ts @@ -0,0 +1,41 @@ +export * from './BehaviorType'; +export * from './Category'; +export * from './CategoryRecord'; +export * from './DefaultMetaOnlyResponse'; +export * from './DefaultMetaOnlyResponseRecord'; +export * from './DeploymentRequestStatus'; +export * from './ErrorCode'; +export * from './FindPetsByStatusResponse'; +export * from './FindPetsByStatusResponseRecord'; +export * from './FindPetsByUserResponse'; +export * from './FindPetsByUserResponseRecord'; +export * from './GetBehaviorPermissionsResponse'; +export * from './GetBehaviorPermissionsResponseRecord'; +export * from './GetBehaviorTypeResponse'; +export * from './GetBehaviorTypeResponseRecord'; +export * from './GetMatchingPartsResponse'; +export * from './GetMatchingPartsResponseRecord'; +export * from './GetPetPartTypeResponse'; +export * from './GetPetPartTypeResponseRecord'; +export * from './ItemId'; +export * from './ItemIdRecord'; +export * from './MatchingParts'; +export * from './MatchingPartsRecord'; +export * from './ModelApiResponse'; +export * from './ModelApiResponseRecord'; +export * from './ModelError'; +export * from './ModelErrorRecord'; +export * from './Order'; +export * from './OrderRecord'; +export * from './Part'; +export * from './PartRecord'; +export * from './Pet'; +export * from './PetRecord'; +export * from './PetPartType'; +export * from './ResponseMeta'; +export * from './ResponseMetaRecord'; +export * from './Tag'; +export * from './TagRecord'; +export * from './User'; +export * from './UserRecord'; +export * from './WarningCode'; 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 new file mode 100644 index 00000000000..40ac35e9d19 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/runtime.ts @@ -0,0 +1,319 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * 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. + */ + + +export const BASE_PATH = "http://petstore.swagger.io/v2".replace(/\/+$/, ""); + +const isBlob = (value: any) => typeof Blob !== 'undefined' && value instanceof Blob; + +/** + * This is the base class for all generated API classes. + */ +export class BaseAPI { + + private middleware: Middleware[]; + + constructor(protected configuration = new Configuration()) { + this.middleware = configuration.middleware; + } + + withMiddleware(this: T, ...middlewares: Middleware[]) { + const next = this.clone(); + next.middleware = next.middleware.concat(...middlewares); + return next; + } + + withPreMiddleware(this: T, ...preMiddlewares: Array) { + const middlewares = preMiddlewares.map((pre) => ({ pre })); + return this.withMiddleware(...middlewares); + } + + withPostMiddleware(this: T, ...postMiddlewares: Array) { + const middlewares = postMiddlewares.map((post) => ({ post })); + return this.withMiddleware(...middlewares); + } + + protected async request(context: RequestOpts): Promise { + const { url, init } = this.createFetchParams(context); + const response = await this.fetchApi(url, init); + if (response.status >= 200 && response.status < 300) { + return response; + } + throw response; + } + + private createFetchParams(context: RequestOpts) { + let url = this.configuration.basePath + context.path; + if (context.query !== undefined && Object.keys(context.query).length !== 0) { + // only add the querystring to the URL if there are query parameters. + // this is done to avoid urls ending with a "?" character which buggy webservers + // do not handle correctly sometimes. + url += '?' + this.configuration.queryParamsStringify(context.query); + } + const body = ((typeof FormData !== "undefined" && context.body instanceof FormData) || context.body instanceof URLSearchParams || isBlob(context.body)) + ? context.body + : JSON.stringify(context.body); + + const headers = Object.assign({}, this.configuration.headers, context.headers); + const init = { + method: context.method, + headers: headers, + body, + credentials: this.configuration.credentials + }; + return { url, init }; + } + + private fetchApi = async (url: string, init: RequestInit) => { + let fetchParams = { url, init }; + for (const middleware of this.middleware) { + if (middleware.pre) { + fetchParams = await middleware.pre({ + fetch: this.fetchApi, + ...fetchParams, + }) || fetchParams; + } + } + let response = await this.configuration.fetchApi(fetchParams.url, fetchParams.init); + for (const middleware of this.middleware) { + if (middleware.post) { + response = await middleware.post({ + fetch: this.fetchApi, + url: fetchParams.url, + init: fetchParams.init, + response: response.clone(), + }) || response; + } + } + return response; + } + + /** + * Create a shallow clone of `this` by constructing a new instance + * and then shallow cloning data members. + */ + private clone(this: T): T { + const constructor = this.constructor as any; + const next = new constructor(this.configuration); + next.middleware = this.middleware.slice(); + return next; + } +}; + +export class RequiredError extends Error { + name: "RequiredError" = "RequiredError"; + constructor(public field: string, msg?: string) { + super(msg); + } +} + +export const COLLECTION_FORMATS = { + csv: ",", + ssv: " ", + tsv: "\t", + pipes: "|", +}; + +export type FetchAPI = WindowOrWorkerGlobalScope['fetch']; + +export interface ConfigurationParameters { + basePath?: string; // override base path + fetchApi?: FetchAPI; // override for fetch implementation + middleware?: Middleware[]; // middleware to apply before/after fetch requests + queryParamsStringify?: (params: HTTPQuery) => string; // stringify function for query strings + username?: string; // parameter for basic security + password?: string; // parameter for basic security + apiKey?: string | ((name: string) => string); // parameter for apiKey security + accessToken?: string | Promise | ((name?: string, scopes?: string[]) => string | Promise); // parameter for oauth2 security + headers?: HTTPHeaders; //header params we want to use on every request + credentials?: RequestCredentials; //value for the credentials param we want to use on each request +} + +export class Configuration { + constructor(private configuration: ConfigurationParameters = {}) {} + + get basePath(): string { + return this.configuration.basePath != null ? this.configuration.basePath : BASE_PATH; + } + + get fetchApi(): FetchAPI { + return this.configuration.fetchApi || window.fetch.bind(window); + } + + get middleware(): Middleware[] { + return this.configuration.middleware || []; + } + + get queryParamsStringify(): (params: HTTPQuery) => string { + return this.configuration.queryParamsStringify || querystring; + } + + get username(): string | undefined { + return this.configuration.username; + } + + get password(): string | undefined { + return this.configuration.password; + } + + get apiKey(): ((name: string) => string) | undefined { + const apiKey = this.configuration.apiKey; + if (apiKey) { + return typeof apiKey === 'function' ? apiKey : () => apiKey; + } + return undefined; + } + + get accessToken(): ((name?: string, scopes?: string[]) => string | Promise) | undefined { + const accessToken = this.configuration.accessToken; + if (accessToken) { + return typeof accessToken === 'function' ? accessToken : async () => accessToken; + } + return undefined; + } + + get headers(): HTTPHeaders | undefined { + return this.configuration.headers; + } + + get credentials(): RequestCredentials | undefined { + return this.configuration.credentials; + } +} + +export type Json = any; +export type HTTPMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'OPTIONS' | 'HEAD'; +export type HTTPHeaders = { [key: string]: string }; +export type HTTPQuery = { [key: string]: string | number | null | boolean | Array | HTTPQuery }; +export type HTTPBody = Json | FormData | URLSearchParams; +export type ModelPropertyNaming = 'camelCase' | 'snake_case' | 'PascalCase' | 'original'; + +export interface FetchParams { + url: string; + init: RequestInit; +} + +export interface RequestOpts { + path: string; + method: HTTPMethod; + headers: HTTPHeaders; + query?: HTTPQuery; + body?: HTTPBody; +} + +export function exists(json: any, key: string) { + const value = json[key]; + return value !== null && value !== undefined; +} + +export function querystring(params: HTTPQuery, prefix: string = ''): string { + return Object.keys(params) + .map((key) => { + const fullKey = prefix + (prefix.length ? `[${key}]` : key); + const value = params[key]; + if (value instanceof Array) { + const multiValue = value.map(singleValue => encodeURIComponent(String(singleValue))) + .join(`&${encodeURIComponent(fullKey)}=`); + return `${encodeURIComponent(fullKey)}=${multiValue}`; + } + if (value instanceof Date) { + return `${encodeURIComponent(fullKey)}=${encodeURIComponent(value.toISOString())}`; + } + if (value instanceof Object) { + return querystring(value as HTTPQuery, fullKey); + } + return `${encodeURIComponent(fullKey)}=${encodeURIComponent(String(value))}`; + }) + .filter(part => part.length > 0) + .join('&'); +} + +export function mapValues(data: any, fn: (item: any) => any) { + return Object.keys(data).reduce( + (acc, key) => ({ ...acc, [key]: fn(data[key]) }), + {} + ); +} + +export function canConsumeForm(consumes: Consume[]): boolean { + for (const consume of consumes) { + if ('multipart/form-data' === consume.contentType) { + return true; + } + } + return false; +} + +export interface Consume { + contentType: string +} + +export interface RequestContext { + fetch: FetchAPI; + url: string; + init: RequestInit; +} + +export interface ResponseContext { + fetch: FetchAPI; + url: string; + init: RequestInit; + response: Response; +} + +export interface Middleware { + pre?(context: RequestContext): Promise; + post?(context: ResponseContext): Promise; +} + +export interface ApiResponse { + raw: Response; + value(): Promise; +} + +export interface ResponseTransformer { + (json: any): T; +} + +export class JSONApiResponse { + constructor(public raw: Response, private transformer: ResponseTransformer = (jsonValue: any) => jsonValue) {} + + async value(): Promise { + return this.transformer(await this.raw.json()); + } +} + +export class VoidApiResponse { + constructor(public raw: Response) {} + + async value(): Promise { + return undefined; + } +} + +export class BlobApiResponse { + constructor(public raw: Response) {} + + async value(): Promise { + return await this.raw.blob(); + }; +} + +export class TextApiResponse { + constructor(public raw: Response) {} + + async value(): Promise { + return await this.raw.text(); + }; +} diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/runtimeSagasAndRecords.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/runtimeSagasAndRecords.ts new file mode 100644 index 00000000000..e182521fac3 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/runtimeSagasAndRecords.ts @@ -0,0 +1,120 @@ +/* tslint:disable */ +/* eslint-disable */ + +import {fromJS as originalFromJS, isIndexed, List, Map as ImmMap, RecordOf} from 'immutable'; +import {normalize, NormalizedSchema, schema, Schema} from "normalizr"; +import {ActionDefinition, createAction} from "redux-ts-simple"; + +export const knownRecordFactories = new Map(); +export const knownIndexedSetByKey: (string | number)[] = []; + +export function appFromJS(any: any): any { + return originalFromJS(any, (key, value) => { + if (isIndexed(value)) { + return knownIndexedSetByKey.indexOf(key) !== -1 ? value.toSet() : value.toList(); + } // we're reviving an array -> it's a List + const MatchingType = knownRecordFactories.get(value.get('recType')) as { new(input?: any): any }; // check if we know a Record with this type + if (MatchingType) { + return new MatchingType(value); + } + return value.toMap(); // no matching Record type found -> it's a plain old Map + }); +} + +export type NormalizedRecordEntity = NormalizedSchema<{ [key: string]: Map> }, string>; +export type NormalizedRecordEntities = NormalizedSchema<{ [key: string]: Map> }, List>; + +export abstract class ApiRecordUtils> { + public abstract normalize(apiObject: TAPI, asEntity?: boolean): any; + + public getSchema(): Schema { + console.log("Entity mode not supported on this record."); + return new schema.Entity("entityNotSupported"); + } + + public normalizeArray(apiObjectArray: TAPI[], asEntity?: boolean): TAPI[] { + apiObjectArray.forEach(apiObject => this.normalize(apiObject, asEntity)); + return apiObjectArray; + } + + public normalizeAsEntities(apiObject: TAPI): NormalizedSchema { + const normalized = this.normalize(apiObject, true); + return normalize(normalized, this.getSchema()); + } + + public normalizeArrayAsEntities(apiObject: TAPI[]): NormalizedSchema { + const normalized = this.normalizeArray(apiObject, true); + return normalize(normalized, new schema.Array(this.getSchema())); + } + + public fromApi(apiObject: TAPI): TREC { + return appFromJS(this.normalize(apiObject)); + } + + public fromApiArray(apiObjectArray: TAPI[]): List { + this.normalizeArray(apiObjectArray); + return appFromJS(apiObjectArray); + } + + public fromApiAsEntities(apiObject: TAPI): NormalizedRecordEntity { + return ApiRecordUtils.toNormalizedRecordEntities(this.normalizeAsEntities(apiObject), false); + } + + public fromApiArrayAsEntities(apiObject: TAPI[]): NormalizedRecordEntities { + return ApiRecordUtils.toNormalizedRecordEntities(this.normalizeArrayAsEntities(apiObject), true); + } + + public toApi(record: TREC): TAPI { + const apiObject = record.toJS(); + delete apiObject.recType; + return apiObject; + } + + public toApiArray(records: List): TAPI[] { + return records.map(record => this.toApi(record)).toArray(); + } + + public static toNormalizedRecordEntities(normalizedAsEntities: any, forArray: boolean) { + const entities = normalizedAsEntities.entities; + for (const entityKey of Object.keys(entities)) { + entities[entityKey] = appFromJS(entities[entityKey]); + } + normalizedAsEntities.result = appFromJS(normalizedAsEntities.result || (forArray ? "" : [])); + return normalizedAsEntities; + } +} + +export const allApiActionFailures: SagaActionDefinition[] = []; + +export interface BaseEntitySupportPayloadApiAction { + toInlined?: boolean; + toEntities?: boolean; + markErrorsAsHandled?: boolean; +} + +export interface BasePayloadApiAction { + markErrorsAsHandled?: boolean; +} + +export interface SagaActionDefinition extends ActionDefinition { + toString: () => string; +} + +export function createSagaAction(type: string, options?: { doNotAutoRegisterFailure?: boolean, namespace?: string }): SagaActionDefinition { + const {doNotAutoRegisterFailure, namespace} = options || {} as any; + let actionDefinition = createAction(namespace ? `${namespace}-${type}` : type); + (actionDefinition as any).toString = () => actionDefinition.type; + if (type.endsWith("Failure") && !doNotAutoRegisterFailure) { + allApiActionFailures.push(actionDefinition); + } + return actionDefinition; +} + +export let apiCall: any>(context: Ctx, fn: Fn, ...args: Parameters) => Generator; + +export function setApiCall(apiCallFc: any>(context: Ctx, fn: Fn, ...args: Parameters) => Generator) { + console.log("init apiCall"); + apiCall = apiCallFc; +} + +export const normalizedEntities = createSagaAction("normalizedEntities"); \ No newline at end of file diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/tsconfig.json b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/tsconfig.json new file mode 100644 index 00000000000..5047f4d59a3 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "declaration": true, + "target": "es6", + "strict": true, + "module": "commonjs", + "moduleResolution": "node", + "outDir": "dist", + "typeRoots": [ + "node_modules/@types" + ] + }, + "exclude": [ + "dist", + "node_modules" + ] +} diff --git a/samples/client/petstore/typescript-fetch/builds/typescript-three-plus/.openapi-generator/VERSION b/samples/client/petstore/typescript-fetch/builds/typescript-three-plus/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/client/petstore/typescript-fetch/builds/typescript-three-plus/.openapi-generator/VERSION +++ b/samples/client/petstore/typescript-fetch/builds/typescript-three-plus/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/client/petstore/typescript-fetch/builds/typescript-three-plus/package.json b/samples/client/petstore/typescript-fetch/builds/typescript-three-plus/package.json index 96268c493a5..232f78295b2 100644 --- a/samples/client/petstore/typescript-fetch/builds/typescript-three-plus/package.json +++ b/samples/client/petstore/typescript-fetch/builds/typescript-three-plus/package.json @@ -10,7 +10,7 @@ "prepare": "npm run build" }, "devDependencies": { - "typescript": "^3.6" + "typescript": "^3.9.5" }, "publishConfig": { "registry": "https://skimdb.npmjs.com/registry" diff --git a/samples/client/petstore/typescript-fetch/builds/typescript-three-plus/src/apis/PetApi.ts b/samples/client/petstore/typescript-fetch/builds/typescript-three-plus/src/apis/PetApi.ts index a219f15f7e2..3bf150e489b 100644 --- a/samples/client/petstore/typescript-fetch/builds/typescript-three-plus/src/apis/PetApi.ts +++ b/samples/client/petstore/typescript-fetch/builds/typescript-three-plus/src/apis/PetApi.ts @@ -81,11 +81,7 @@ export class PetApi extends runtime.BaseAPI { if (this.configuration && this.configuration.accessToken) { // oauth required - if (typeof this.configuration.accessToken === 'function') { - headerParameters["Authorization"] = this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); - } else { - headerParameters["Authorization"] = this.configuration.accessToken; - } + headerParameters["Authorization"] = await this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); } const response = await this.request({ @@ -124,11 +120,7 @@ export class PetApi extends runtime.BaseAPI { if (this.configuration && this.configuration.accessToken) { // oauth required - if (typeof this.configuration.accessToken === 'function') { - headerParameters["Authorization"] = this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); - } else { - headerParameters["Authorization"] = this.configuration.accessToken; - } + headerParameters["Authorization"] = await this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); } const response = await this.request({ @@ -167,11 +159,7 @@ export class PetApi extends runtime.BaseAPI { if (this.configuration && this.configuration.accessToken) { // oauth required - if (typeof this.configuration.accessToken === 'function') { - headerParameters["Authorization"] = this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); - } else { - headerParameters["Authorization"] = this.configuration.accessToken; - } + headerParameters["Authorization"] = await this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); } const response = await this.request({ @@ -212,11 +200,7 @@ export class PetApi extends runtime.BaseAPI { if (this.configuration && this.configuration.accessToken) { // oauth required - if (typeof this.configuration.accessToken === 'function') { - headerParameters["Authorization"] = this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); - } else { - headerParameters["Authorization"] = this.configuration.accessToken; - } + headerParameters["Authorization"] = await this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); } const response = await this.request({ @@ -290,11 +274,7 @@ export class PetApi extends runtime.BaseAPI { if (this.configuration && this.configuration.accessToken) { // oauth required - if (typeof this.configuration.accessToken === 'function') { - headerParameters["Authorization"] = this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); - } else { - headerParameters["Authorization"] = this.configuration.accessToken; - } + headerParameters["Authorization"] = await this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); } const response = await this.request({ @@ -329,11 +309,7 @@ export class PetApi extends runtime.BaseAPI { if (this.configuration && this.configuration.accessToken) { // oauth required - if (typeof this.configuration.accessToken === 'function') { - headerParameters["Authorization"] = this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); - } else { - headerParameters["Authorization"] = this.configuration.accessToken; - } + headerParameters["Authorization"] = await this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); } const consumes: runtime.Consume[] = [ @@ -390,11 +366,7 @@ export class PetApi extends runtime.BaseAPI { if (this.configuration && this.configuration.accessToken) { // oauth required - if (typeof this.configuration.accessToken === 'function') { - headerParameters["Authorization"] = this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); - } else { - headerParameters["Authorization"] = this.configuration.accessToken; - } + headerParameters["Authorization"] = await this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); } const consumes: runtime.Consume[] = [ diff --git a/samples/client/petstore/typescript-fetch/builds/typescript-three-plus/src/runtime.ts b/samples/client/petstore/typescript-fetch/builds/typescript-three-plus/src/runtime.ts index da5d9059bad..40ac35e9d19 100644 --- a/samples/client/petstore/typescript-fetch/builds/typescript-three-plus/src/runtime.ts +++ b/samples/client/petstore/typescript-fetch/builds/typescript-three-plus/src/runtime.ts @@ -90,8 +90,8 @@ export class BaseAPI { if (middleware.post) { response = await middleware.post({ fetch: this.fetchApi, - url, - init, + url: fetchParams.url, + init: fetchParams.init, response: response.clone(), }) || response; } @@ -135,7 +135,7 @@ export interface ConfigurationParameters { username?: string; // parameter for basic security password?: string; // parameter for basic security apiKey?: string | ((name: string) => string); // parameter for apiKey security - accessToken?: string | ((name?: string, scopes?: string[]) => string); // parameter for oauth2 security + accessToken?: string | Promise | ((name?: string, scopes?: string[]) => string | Promise); // parameter for oauth2 security headers?: HTTPHeaders; //header params we want to use on every request credentials?: RequestCredentials; //value for the credentials param we want to use on each request } @@ -175,10 +175,10 @@ export class Configuration { return undefined; } - get accessToken(): ((name: string, scopes?: string[]) => string) | undefined { + get accessToken(): ((name?: string, scopes?: string[]) => string | Promise) | undefined { const accessToken = this.configuration.accessToken; if (accessToken) { - return typeof accessToken === 'function' ? accessToken : () => accessToken; + return typeof accessToken === 'function' ? accessToken : async () => accessToken; } return undefined; } 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 5f68295fc19..e8415097f3a 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,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x 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 d7f8f8a62fe..f8224fdb55f 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 @@ -218,11 +218,7 @@ export class PetApi extends runtime.BaseAPI implements PetApiInterface { if (this.configuration && this.configuration.accessToken) { // oauth required - if (typeof this.configuration.accessToken === 'function') { - headerParameters["Authorization"] = this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); - } else { - headerParameters["Authorization"] = this.configuration.accessToken; - } + headerParameters["Authorization"] = await this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); } const response = await this.request({ @@ -261,11 +257,7 @@ export class PetApi extends runtime.BaseAPI implements PetApiInterface { if (this.configuration && this.configuration.accessToken) { // oauth required - if (typeof this.configuration.accessToken === 'function') { - headerParameters["Authorization"] = this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); - } else { - headerParameters["Authorization"] = this.configuration.accessToken; - } + headerParameters["Authorization"] = await this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); } const response = await this.request({ @@ -304,11 +296,7 @@ export class PetApi extends runtime.BaseAPI implements PetApiInterface { if (this.configuration && this.configuration.accessToken) { // oauth required - if (typeof this.configuration.accessToken === 'function') { - headerParameters["Authorization"] = this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); - } else { - headerParameters["Authorization"] = this.configuration.accessToken; - } + headerParameters["Authorization"] = await this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); } const response = await this.request({ @@ -349,11 +337,7 @@ export class PetApi extends runtime.BaseAPI implements PetApiInterface { if (this.configuration && this.configuration.accessToken) { // oauth required - if (typeof this.configuration.accessToken === 'function') { - headerParameters["Authorization"] = this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); - } else { - headerParameters["Authorization"] = this.configuration.accessToken; - } + headerParameters["Authorization"] = await this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); } const response = await this.request({ @@ -427,11 +411,7 @@ export class PetApi extends runtime.BaseAPI implements PetApiInterface { if (this.configuration && this.configuration.accessToken) { // oauth required - if (typeof this.configuration.accessToken === 'function') { - headerParameters["Authorization"] = this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); - } else { - headerParameters["Authorization"] = this.configuration.accessToken; - } + headerParameters["Authorization"] = await this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); } const response = await this.request({ @@ -466,11 +446,7 @@ export class PetApi extends runtime.BaseAPI implements PetApiInterface { if (this.configuration && this.configuration.accessToken) { // oauth required - if (typeof this.configuration.accessToken === 'function') { - headerParameters["Authorization"] = this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); - } else { - headerParameters["Authorization"] = this.configuration.accessToken; - } + headerParameters["Authorization"] = await this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); } const consumes: runtime.Consume[] = [ @@ -527,11 +503,7 @@ export class PetApi extends runtime.BaseAPI implements PetApiInterface { if (this.configuration && this.configuration.accessToken) { // oauth required - if (typeof this.configuration.accessToken === 'function') { - headerParameters["Authorization"] = this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); - } else { - headerParameters["Authorization"] = this.configuration.accessToken; - } + headerParameters["Authorization"] = await this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); } const consumes: runtime.Consume[] = [ 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 f7a51f623ff..8ae5f65348c 100644 --- a/samples/client/petstore/typescript-fetch/builds/with-interfaces/runtime.ts +++ b/samples/client/petstore/typescript-fetch/builds/with-interfaces/runtime.ts @@ -90,8 +90,8 @@ export class BaseAPI { if (middleware.post) { response = await middleware.post({ fetch: this.fetchApi, - url, - init, + url: fetchParams.url, + init: fetchParams.init, response: response.clone(), }) || response; } @@ -135,7 +135,7 @@ export interface ConfigurationParameters { username?: string; // parameter for basic security password?: string; // parameter for basic security apiKey?: string | ((name: string) => string); // parameter for apiKey security - accessToken?: string | ((name?: string, scopes?: string[]) => string); // parameter for oauth2 security + accessToken?: string | Promise | ((name?: string, scopes?: string[]) => string | Promise); // parameter for oauth2 security headers?: HTTPHeaders; //header params we want to use on every request credentials?: RequestCredentials; //value for the credentials param we want to use on each request } @@ -175,10 +175,10 @@ export class Configuration { return undefined; } - get accessToken(): ((name: string, scopes?: string[]) => string) | undefined { + get accessToken(): ((name?: string, scopes?: string[]) => string | Promise) | undefined { const accessToken = this.configuration.accessToken; if (accessToken) { - return typeof accessToken === 'function' ? accessToken : () => accessToken; + return typeof accessToken === 'function' ? accessToken : async () => accessToken; } return undefined; } 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 5f68295fc19..e8415097f3a 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,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x 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 a219f15f7e2..3bf150e489b 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 @@ -81,11 +81,7 @@ export class PetApi extends runtime.BaseAPI { if (this.configuration && this.configuration.accessToken) { // oauth required - if (typeof this.configuration.accessToken === 'function') { - headerParameters["Authorization"] = this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); - } else { - headerParameters["Authorization"] = this.configuration.accessToken; - } + headerParameters["Authorization"] = await this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); } const response = await this.request({ @@ -124,11 +120,7 @@ export class PetApi extends runtime.BaseAPI { if (this.configuration && this.configuration.accessToken) { // oauth required - if (typeof this.configuration.accessToken === 'function') { - headerParameters["Authorization"] = this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); - } else { - headerParameters["Authorization"] = this.configuration.accessToken; - } + headerParameters["Authorization"] = await this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); } const response = await this.request({ @@ -167,11 +159,7 @@ export class PetApi extends runtime.BaseAPI { if (this.configuration && this.configuration.accessToken) { // oauth required - if (typeof this.configuration.accessToken === 'function') { - headerParameters["Authorization"] = this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); - } else { - headerParameters["Authorization"] = this.configuration.accessToken; - } + headerParameters["Authorization"] = await this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); } const response = await this.request({ @@ -212,11 +200,7 @@ export class PetApi extends runtime.BaseAPI { if (this.configuration && this.configuration.accessToken) { // oauth required - if (typeof this.configuration.accessToken === 'function') { - headerParameters["Authorization"] = this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); - } else { - headerParameters["Authorization"] = this.configuration.accessToken; - } + headerParameters["Authorization"] = await this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); } const response = await this.request({ @@ -290,11 +274,7 @@ export class PetApi extends runtime.BaseAPI { if (this.configuration && this.configuration.accessToken) { // oauth required - if (typeof this.configuration.accessToken === 'function') { - headerParameters["Authorization"] = this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); - } else { - headerParameters["Authorization"] = this.configuration.accessToken; - } + headerParameters["Authorization"] = await this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); } const response = await this.request({ @@ -329,11 +309,7 @@ export class PetApi extends runtime.BaseAPI { if (this.configuration && this.configuration.accessToken) { // oauth required - if (typeof this.configuration.accessToken === 'function') { - headerParameters["Authorization"] = this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); - } else { - headerParameters["Authorization"] = this.configuration.accessToken; - } + headerParameters["Authorization"] = await this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); } const consumes: runtime.Consume[] = [ @@ -390,11 +366,7 @@ export class PetApi extends runtime.BaseAPI { if (this.configuration && this.configuration.accessToken) { // oauth required - if (typeof this.configuration.accessToken === 'function') { - headerParameters["Authorization"] = this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); - } else { - headerParameters["Authorization"] = this.configuration.accessToken; - } + headerParameters["Authorization"] = await this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); } const consumes: runtime.Consume[] = [ 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 f7a51f623ff..8ae5f65348c 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 @@ -90,8 +90,8 @@ export class BaseAPI { if (middleware.post) { response = await middleware.post({ fetch: this.fetchApi, - url, - init, + url: fetchParams.url, + init: fetchParams.init, response: response.clone(), }) || response; } @@ -135,7 +135,7 @@ export interface ConfigurationParameters { username?: string; // parameter for basic security password?: string; // parameter for basic security apiKey?: string | ((name: string) => string); // parameter for apiKey security - accessToken?: string | ((name?: string, scopes?: string[]) => string); // parameter for oauth2 security + accessToken?: string | Promise | ((name?: string, scopes?: string[]) => string | Promise); // parameter for oauth2 security headers?: HTTPHeaders; //header params we want to use on every request credentials?: RequestCredentials; //value for the credentials param we want to use on each request } @@ -175,10 +175,10 @@ export class Configuration { return undefined; } - get accessToken(): ((name: string, scopes?: string[]) => string) | undefined { + get accessToken(): ((name?: string, scopes?: string[]) => string | Promise) | undefined { const accessToken = this.configuration.accessToken; if (accessToken) { - return typeof accessToken === 'function' ? accessToken : () => accessToken; + return typeof accessToken === 'function' ? accessToken : async () => accessToken; } return undefined; } 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 5f68295fc19..e8415097f3a 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,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x 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 dd0a9026b01..063d760e6ca 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 @@ -77,11 +77,7 @@ export class PetApi extends runtime.BaseAPI { if (this.configuration && this.configuration.accessToken) { // oauth required - if (typeof this.configuration.accessToken === 'function') { - headerParameters["Authorization"] = this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); - } else { - headerParameters["Authorization"] = this.configuration.accessToken; - } + headerParameters["Authorization"] = await this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); } const response = await this.request({ @@ -120,11 +116,7 @@ export class PetApi extends runtime.BaseAPI { if (this.configuration && this.configuration.accessToken) { // oauth required - if (typeof this.configuration.accessToken === 'function') { - headerParameters["Authorization"] = this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); - } else { - headerParameters["Authorization"] = this.configuration.accessToken; - } + headerParameters["Authorization"] = await this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); } const response = await this.request({ @@ -163,11 +155,7 @@ export class PetApi extends runtime.BaseAPI { if (this.configuration && this.configuration.accessToken) { // oauth required - if (typeof this.configuration.accessToken === 'function') { - headerParameters["Authorization"] = this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); - } else { - headerParameters["Authorization"] = this.configuration.accessToken; - } + headerParameters["Authorization"] = await this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); } const response = await this.request({ @@ -208,11 +196,7 @@ export class PetApi extends runtime.BaseAPI { if (this.configuration && this.configuration.accessToken) { // oauth required - if (typeof this.configuration.accessToken === 'function') { - headerParameters["Authorization"] = this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); - } else { - headerParameters["Authorization"] = this.configuration.accessToken; - } + headerParameters["Authorization"] = await this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); } const response = await this.request({ @@ -286,11 +270,7 @@ export class PetApi extends runtime.BaseAPI { if (this.configuration && this.configuration.accessToken) { // oauth required - if (typeof this.configuration.accessToken === 'function') { - headerParameters["Authorization"] = this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); - } else { - headerParameters["Authorization"] = this.configuration.accessToken; - } + headerParameters["Authorization"] = await this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); } const response = await this.request({ @@ -325,11 +305,7 @@ export class PetApi extends runtime.BaseAPI { if (this.configuration && this.configuration.accessToken) { // oauth required - if (typeof this.configuration.accessToken === 'function') { - headerParameters["Authorization"] = this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); - } else { - headerParameters["Authorization"] = this.configuration.accessToken; - } + headerParameters["Authorization"] = await this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); } const consumes: runtime.Consume[] = [ @@ -386,11 +362,7 @@ export class PetApi extends runtime.BaseAPI { if (this.configuration && this.configuration.accessToken) { // oauth required - if (typeof this.configuration.accessToken === 'function') { - headerParameters["Authorization"] = this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); - } else { - headerParameters["Authorization"] = this.configuration.accessToken; - } + headerParameters["Authorization"] = await this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); } const consumes: runtime.Consume[] = [ diff --git a/samples/client/petstore/typescript-fetch/builds/without-runtime-checks/src/models/Category.ts b/samples/client/petstore/typescript-fetch/builds/without-runtime-checks/src/models/Category.ts new file mode 100644 index 00000000000..faf9aabb9de --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/without-runtime-checks/src/models/Category.ts @@ -0,0 +1,65 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * 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. + */ + +import { exists, mapValues } from '../runtime'; +/** + * A category for a pet + * @export + * @interface Category + */ +export interface Category { + /** + * + * @type {number} + * @memberof Category + */ + id?: number; + /** + * + * @type {string} + * @memberof Category + */ + name?: string; +} + +export function CategoryFromJSON(json: any): Category { + return CategoryFromJSONTyped(json, false); +} + +export function CategoryFromJSONTyped(json: any, ignoreDiscriminator: boolean): Category { + if ((json === undefined) || (json === null)) { + return json; + } + return { + + 'id': !exists(json, 'id') ? undefined : json['id'], + 'name': !exists(json, 'name') ? undefined : json['name'], + }; +} + +export function CategoryToJSON(value?: Category | null): any { + if (value === undefined) { + return undefined; + } + if (value === null) { + return null; + } + return { + + 'id': value.id, + 'name': value.name, + }; +} + + diff --git a/samples/client/petstore/typescript-fetch/builds/without-runtime-checks/src/models/ModelApiResponse.ts b/samples/client/petstore/typescript-fetch/builds/without-runtime-checks/src/models/ModelApiResponse.ts new file mode 100644 index 00000000000..63fa57adc03 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/without-runtime-checks/src/models/ModelApiResponse.ts @@ -0,0 +1,73 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * 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. + */ + +import { exists, mapValues } from '../runtime'; +/** + * Describes the result of uploading an image resource + * @export + * @interface ModelApiResponse + */ +export interface ModelApiResponse { + /** + * + * @type {number} + * @memberof ModelApiResponse + */ + code?: number; + /** + * + * @type {string} + * @memberof ModelApiResponse + */ + type?: string; + /** + * + * @type {string} + * @memberof ModelApiResponse + */ + message?: string; +} + +export function ModelApiResponseFromJSON(json: any): ModelApiResponse { + return ModelApiResponseFromJSONTyped(json, false); +} + +export function ModelApiResponseFromJSONTyped(json: any, ignoreDiscriminator: boolean): ModelApiResponse { + if ((json === undefined) || (json === null)) { + return json; + } + return { + + 'code': !exists(json, 'code') ? undefined : json['code'], + 'type': !exists(json, 'type') ? undefined : json['type'], + 'message': !exists(json, 'message') ? undefined : json['message'], + }; +} + +export function ModelApiResponseToJSON(value?: ModelApiResponse | null): any { + if (value === undefined) { + return undefined; + } + if (value === null) { + return null; + } + return { + + 'code': value.code, + 'type': value.type, + 'message': value.message, + }; +} + + diff --git a/samples/client/petstore/typescript-fetch/builds/without-runtime-checks/src/models/Order.ts b/samples/client/petstore/typescript-fetch/builds/without-runtime-checks/src/models/Order.ts new file mode 100644 index 00000000000..104c3157f61 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/without-runtime-checks/src/models/Order.ts @@ -0,0 +1,107 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * 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. + */ + +import { exists, mapValues } from '../runtime'; +/** + * An order for a pets from the pet store + * @export + * @interface Order + */ +export interface Order { + /** + * + * @type {number} + * @memberof Order + */ + id?: number; + /** + * + * @type {number} + * @memberof Order + */ + petId?: number; + /** + * + * @type {number} + * @memberof Order + */ + quantity?: number; + /** + * + * @type {Date} + * @memberof Order + */ + shipDate?: Date; + /** + * Order Status + * @type {string} + * @memberof Order + */ + status?: OrderStatusEnum; + /** + * + * @type {boolean} + * @memberof Order + */ + complete?: boolean; +} + +export function OrderFromJSON(json: any): Order { + return OrderFromJSONTyped(json, false); +} + +export function OrderFromJSONTyped(json: any, ignoreDiscriminator: boolean): Order { + if ((json === undefined) || (json === null)) { + return json; + } + return { + + 'id': !exists(json, 'id') ? undefined : json['id'], + 'petId': !exists(json, 'petId') ? undefined : json['petId'], + 'quantity': !exists(json, 'quantity') ? undefined : json['quantity'], + 'shipDate': !exists(json, 'shipDate') ? undefined : (new Date(json['shipDate'])), + 'status': !exists(json, 'status') ? undefined : json['status'], + 'complete': !exists(json, 'complete') ? undefined : json['complete'], + }; +} + +export function OrderToJSON(value?: Order | null): any { + if (value === undefined) { + return undefined; + } + if (value === null) { + return null; + } + return { + + 'id': value.id, + 'petId': value.petId, + 'quantity': value.quantity, + 'shipDate': value.shipDate === undefined ? undefined : (value.shipDate.toISOString()), + 'status': value.status, + 'complete': value.complete, + }; +} + +/** +* @export +* @enum {string} +*/ +export enum OrderStatusEnum { + Placed = 'placed', + Approved = 'approved', + Delivered = 'delivered' +} + + diff --git a/samples/client/petstore/typescript-fetch/builds/without-runtime-checks/src/models/Pet.ts b/samples/client/petstore/typescript-fetch/builds/without-runtime-checks/src/models/Pet.ts new file mode 100644 index 00000000000..7e084c084a9 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/without-runtime-checks/src/models/Pet.ts @@ -0,0 +1,118 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * 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. + */ + +import { exists, mapValues } from '../runtime'; +import { + Category, + CategoryFromJSON, + CategoryFromJSONTyped, + CategoryToJSON, + Tag, + TagFromJSON, + TagFromJSONTyped, + TagToJSON, +} from './'; + +/** + * A pet for sale in the pet store + * @export + * @interface Pet + */ +export interface Pet { + /** + * + * @type {number} + * @memberof Pet + */ + id?: number; + /** + * + * @type {Category} + * @memberof Pet + */ + category?: Category; + /** + * + * @type {string} + * @memberof Pet + */ + name: string; + /** + * + * @type {Array} + * @memberof Pet + */ + photoUrls: Array; + /** + * + * @type {Array} + * @memberof Pet + */ + tags?: Array; + /** + * pet status in the store + * @type {string} + * @memberof Pet + */ + status?: PetStatusEnum; +} + +export function PetFromJSON(json: any): Pet { + return PetFromJSONTyped(json, false); +} + +export function PetFromJSONTyped(json: any, ignoreDiscriminator: boolean): Pet { + if ((json === undefined) || (json === null)) { + return json; + } + return { + + 'id': !exists(json, 'id') ? undefined : json['id'], + 'category': !exists(json, 'category') ? undefined : CategoryFromJSON(json['category']), + 'name': json['name'], + 'photoUrls': json['photoUrls'], + 'tags': !exists(json, 'tags') ? undefined : ((json['tags'] as Array).map(TagFromJSON)), + 'status': !exists(json, 'status') ? undefined : json['status'], + }; +} + +export function PetToJSON(value?: Pet | null): any { + if (value === undefined) { + return undefined; + } + if (value === null) { + return null; + } + return { + + 'id': value.id, + 'category': CategoryToJSON(value.category), + 'name': value.name, + 'photoUrls': value.photoUrls, + 'tags': value.tags === undefined ? undefined : ((value.tags as Array).map(TagToJSON)), + 'status': value.status, + }; +} + +/** +* @export +* @enum {string} +*/ +export enum PetStatusEnum { + Available = 'available', + Pending = 'pending', + Sold = 'sold' +} + + diff --git a/samples/client/petstore/typescript-fetch/builds/without-runtime-checks/src/models/Tag.ts b/samples/client/petstore/typescript-fetch/builds/without-runtime-checks/src/models/Tag.ts new file mode 100644 index 00000000000..8ea5895e79b --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/without-runtime-checks/src/models/Tag.ts @@ -0,0 +1,65 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * 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. + */ + +import { exists, mapValues } from '../runtime'; +/** + * A tag for a pet + * @export + * @interface Tag + */ +export interface Tag { + /** + * + * @type {number} + * @memberof Tag + */ + id?: number; + /** + * + * @type {string} + * @memberof Tag + */ + name?: string; +} + +export function TagFromJSON(json: any): Tag { + return TagFromJSONTyped(json, false); +} + +export function TagFromJSONTyped(json: any, ignoreDiscriminator: boolean): Tag { + if ((json === undefined) || (json === null)) { + return json; + } + return { + + 'id': !exists(json, 'id') ? undefined : json['id'], + 'name': !exists(json, 'name') ? undefined : json['name'], + }; +} + +export function TagToJSON(value?: Tag | null): any { + if (value === undefined) { + return undefined; + } + if (value === null) { + return null; + } + return { + + 'id': value.id, + 'name': value.name, + }; +} + + diff --git a/samples/client/petstore/typescript-fetch/builds/without-runtime-checks/src/models/User.ts b/samples/client/petstore/typescript-fetch/builds/without-runtime-checks/src/models/User.ts new file mode 100644 index 00000000000..841b50d0fa2 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/without-runtime-checks/src/models/User.ts @@ -0,0 +1,113 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * 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. + */ + +import { exists, mapValues } from '../runtime'; +/** + * A User who is purchasing from the pet store + * @export + * @interface User + */ +export interface User { + /** + * + * @type {number} + * @memberof User + */ + id?: number; + /** + * + * @type {string} + * @memberof User + */ + username?: string; + /** + * + * @type {string} + * @memberof User + */ + firstName?: string; + /** + * + * @type {string} + * @memberof User + */ + lastName?: string; + /** + * + * @type {string} + * @memberof User + */ + email?: string; + /** + * + * @type {string} + * @memberof User + */ + password?: string; + /** + * + * @type {string} + * @memberof User + */ + phone?: string; + /** + * User Status + * @type {number} + * @memberof User + */ + userStatus?: number; +} + +export function UserFromJSON(json: any): User { + return UserFromJSONTyped(json, false); +} + +export function UserFromJSONTyped(json: any, ignoreDiscriminator: boolean): User { + if ((json === undefined) || (json === null)) { + return json; + } + return { + + 'id': !exists(json, 'id') ? undefined : json['id'], + 'username': !exists(json, 'username') ? undefined : json['username'], + 'firstName': !exists(json, 'firstName') ? undefined : json['firstName'], + 'lastName': !exists(json, 'lastName') ? undefined : json['lastName'], + 'email': !exists(json, 'email') ? undefined : json['email'], + 'password': !exists(json, 'password') ? undefined : json['password'], + 'phone': !exists(json, 'phone') ? undefined : json['phone'], + 'userStatus': !exists(json, 'userStatus') ? undefined : json['userStatus'], + }; +} + +export function UserToJSON(value?: User | null): any { + if (value === undefined) { + return undefined; + } + if (value === null) { + return null; + } + return { + + 'id': value.id, + 'username': value.username, + 'firstName': value.firstName, + 'lastName': value.lastName, + 'email': value.email, + 'password': value.password, + 'phone': value.phone, + 'userStatus': value.userStatus, + }; +} + + diff --git a/samples/client/petstore/typescript-fetch/builds/without-runtime-checks/src/models/index.ts b/samples/client/petstore/typescript-fetch/builds/without-runtime-checks/src/models/index.ts index 92ab264fa9c..099f52268b7 100644 --- a/samples/client/petstore/typescript-fetch/builds/without-runtime-checks/src/models/index.ts +++ b/samples/client/petstore/typescript-fetch/builds/without-runtime-checks/src/models/index.ts @@ -1,4 +1,3 @@ - /** * A category for a pet * @export @@ -18,7 +17,6 @@ export interface Category { */ name?: string; } - /** * Describes the result of uploading an image resource * @export @@ -44,7 +42,6 @@ export interface ModelApiResponse { */ message?: string; } - /** * An order for a pets from the pet store * @export @@ -98,7 +95,6 @@ export enum OrderStatusEnum { Approved = 'approved', Delivered = 'delivered' } - /** * A pet for sale in the pet store * @export @@ -152,7 +148,6 @@ export enum PetStatusEnum { Pending = 'pending', Sold = 'sold' } - /** * A tag for a pet * @export @@ -172,7 +167,6 @@ export interface Tag { */ name?: string; } - /** * A User who is purchasing from the pet store * @export 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 f7a51f623ff..8ae5f65348c 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 @@ -90,8 +90,8 @@ export class BaseAPI { if (middleware.post) { response = await middleware.post({ fetch: this.fetchApi, - url, - init, + url: fetchParams.url, + init: fetchParams.init, response: response.clone(), }) || response; } @@ -135,7 +135,7 @@ export interface ConfigurationParameters { username?: string; // parameter for basic security password?: string; // parameter for basic security apiKey?: string | ((name: string) => string); // parameter for apiKey security - accessToken?: string | ((name?: string, scopes?: string[]) => string); // parameter for oauth2 security + accessToken?: string | Promise | ((name?: string, scopes?: string[]) => string | Promise); // parameter for oauth2 security headers?: HTTPHeaders; //header params we want to use on every request credentials?: RequestCredentials; //value for the credentials param we want to use on each request } @@ -175,10 +175,10 @@ export class Configuration { return undefined; } - get accessToken(): ((name: string, scopes?: string[]) => string) | undefined { + get accessToken(): ((name?: string, scopes?: string[]) => string | Promise) | undefined { const accessToken = this.configuration.accessToken; if (accessToken) { - return typeof accessToken === 'function' ? accessToken : () => accessToken; + return typeof accessToken === 'function' ? accessToken : async () => accessToken; } return undefined; } diff --git a/samples/client/petstore/typescript-inversify/.openapi-generator/VERSION b/samples/client/petstore/typescript-inversify/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/client/petstore/typescript-inversify/.openapi-generator/VERSION +++ b/samples/client/petstore/typescript-inversify/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/client/petstore/typescript-jquery/default/.openapi-generator/VERSION b/samples/client/petstore/typescript-jquery/default/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/client/petstore/typescript-jquery/default/.openapi-generator/VERSION +++ b/samples/client/petstore/typescript-jquery/default/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/client/petstore/typescript-jquery/npm/.openapi-generator/VERSION b/samples/client/petstore/typescript-jquery/npm/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/client/petstore/typescript-jquery/npm/.openapi-generator/VERSION +++ b/samples/client/petstore/typescript-jquery/npm/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x 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 5f68295fc19..e8415097f3a 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,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/client/petstore/typescript-node/default/.openapi-generator/VERSION b/samples/client/petstore/typescript-node/default/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/client/petstore/typescript-node/default/.openapi-generator/VERSION +++ b/samples/client/petstore/typescript-node/default/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/client/petstore/typescript-node/npm/.openapi-generator/VERSION b/samples/client/petstore/typescript-node/npm/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/client/petstore/typescript-node/npm/.openapi-generator/VERSION +++ b/samples/client/petstore/typescript-node/npm/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/client/petstore/typescript-node/npm/package.json b/samples/client/petstore/typescript-node/npm/package.json index 0ff014f766a..2bab750c5ba 100644 --- a/samples/client/petstore/typescript-node/npm/package.json +++ b/samples/client/petstore/typescript-node/npm/package.json @@ -15,7 +15,7 @@ "dependencies": { "bluebird": "^3.5.0", "request": "^2.81.0", - "@types/bluebird": "*", + "@types/bluebird": "3.5.33", "@types/request": "*", "rewire": "^3.0.2" }, 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 5f68295fc19..e8415097f3a 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,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x 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 5f68295fc19..e8415097f3a 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,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x 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 5f68295fc19..e8415097f3a 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,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x 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 5f68295fc19..e8415097f3a 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,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x 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 5f68295fc19..e8415097f3a 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,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/config/petstore/protobuf-schema/.openapi-generator/VERSION b/samples/config/petstore/protobuf-schema/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/config/petstore/protobuf-schema/.openapi-generator/VERSION +++ b/samples/config/petstore/protobuf-schema/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/meta-codegen/lib/pom.xml b/samples/meta-codegen/lib/pom.xml index 5d82299e91b..c13096b0a83 100644 --- a/samples/meta-codegen/lib/pom.xml +++ b/samples/meta-codegen/lib/pom.xml @@ -121,7 +121,11 @@ UTF-8 +<<<<<<< HEAD 6.0.0-SNAPSHOT +======= + 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x 1.0.0 4.8.1 diff --git a/samples/meta-codegen/usage/.openapi-generator/VERSION b/samples/meta-codegen/usage/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/meta-codegen/usage/.openapi-generator/VERSION +++ b/samples/meta-codegen/usage/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/openapi3/client/elm/.openapi-generator/VERSION b/samples/openapi3/client/elm/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/openapi3/client/elm/.openapi-generator/VERSION +++ b/samples/openapi3/client/elm/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x 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 5f68295fc19..e8415097f3a 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,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x 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 ad7707a3b82..1d0dad0e27b 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 @@ -18,6 +18,7 @@ import ( "errors" "fmt" "io" + "io/ioutil" "log" "mime/multipart" "net/http" @@ -359,6 +360,15 @@ func (c *APIClient) decode(v interface{}, b []byte, contentType string) (err err *s = string(b) return nil } + if f, ok := v.(**os.File); ok { + *f, err = ioutil.TempFile("", "HttpClientFile") + if err != nil { + return + } + _, err = (*f).Write(b) + _, err = (*f).Seek(0, io.SeekStart) + return + } if xmlCheck.MatchString(contentType) { if err = xml.Unmarshal(b, v); err != nil { return err 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 5f68295fc19..e8415097f3a 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,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x 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 index 5f68295fc19..e8415097f3a 100644 --- 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 @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/python/x_auth_id_alias/api/usage_api.py b/samples/openapi3/client/extensions/x-auth-id-alias/python/x_auth_id_alias/api/usage_api.py index e05577ea119..865341d7c66 100644 --- a/samples/openapi3/client/extensions/x-auth-id-alias/python/x_auth_id_alias/api/usage_api.py +++ b/samples/openapi3/client/extensions/x-auth-id-alias/python/x_auth_id_alias/api/usage_api.py @@ -55,8 +55,8 @@ class UsageApi(object): _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. - _request_timeout (float/tuple): timeout setting for this request. If one - number provided, it will be total request timeout. It can also + _request_timeout (int/float/tuple): timeout setting for this request. If + one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking @@ -163,8 +163,8 @@ class UsageApi(object): _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. - _request_timeout (float/tuple): timeout setting for this request. If one - number provided, it will be total request timeout. It can also + _request_timeout (int/float/tuple): timeout setting for this request. If + one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking @@ -271,8 +271,8 @@ class UsageApi(object): _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. - _request_timeout (float/tuple): timeout setting for this request. If one - number provided, it will be total request timeout. It can also + _request_timeout (int/float/tuple): timeout setting for this request. If + one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking @@ -378,8 +378,8 @@ class UsageApi(object): _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. - _request_timeout (float/tuple): timeout setting for this request. If one - number provided, it will be total request timeout. It can also + _request_timeout (int/float/tuple): timeout setting for this request. If + one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/python/x_auth_id_alias/api_client.py b/samples/openapi3/client/extensions/x-auth-id-alias/python/x_auth_id_alias/api_client.py index 9230d950d48..7e4fa034a6a 100644 --- a/samples/openapi3/client/extensions/x-auth-id-alias/python/x_auth_id_alias/api_client.py +++ b/samples/openapi3/client/extensions/x-auth-id-alias/python/x_auth_id_alias/api_client.py @@ -129,7 +129,7 @@ class ApiClient(object): _return_http_data_only: typing.Optional[bool] = None, collection_formats: typing.Optional[typing.Dict[str, str]] = None, _preload_content: bool = True, - _request_timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + _request_timeout: typing.Optional[typing.Union[int, float, typing.Tuple]] = None, _host: typing.Optional[str] = None, _check_type: typing.Optional[bool] = None ): @@ -347,7 +347,7 @@ class ApiClient(object): _return_http_data_only: typing.Optional[bool] = None, collection_formats: typing.Optional[typing.Dict[str, str]] = None, _preload_content: bool = True, - _request_timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + _request_timeout: typing.Optional[typing.Union[int, float, typing.Tuple]] = None, _host: typing.Optional[str] = None, _check_type: typing.Optional[bool] = None ): @@ -674,7 +674,7 @@ class Endpoint(object): 'async_req': (bool,), '_host_index': (none_type, int), '_preload_content': (bool,), - '_request_timeout': (none_type, int, (int,), [int]), + '_request_timeout': (none_type, float, (float,), [float], int, (int,), [int]), '_return_http_data_only': (bool,), '_check_input_type': (bool,), '_check_return_type': (bool,) diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/python/x_auth_id_alias/model_utils.py b/samples/openapi3/client/extensions/x-auth-id-alias/python/x_auth_id_alias/model_utils.py index 7993d12971b..13277887d39 100644 --- a/samples/openapi3/client/extensions/x-auth-id-alias/python/x_auth_id_alias/model_utils.py +++ b/samples/openapi3/client/extensions/x-auth-id-alias/python/x_auth_id_alias/model_utils.py @@ -47,7 +47,7 @@ def convert_js_args_to_python_args(fn): class cached_property(object): # this caches the result of the function call for fn with no inputs - # use this as a decorator on fuction methods that you want converted + # use this as a decorator on function methods that you want converted # into cached properties result_key = '_results' @@ -1632,12 +1632,20 @@ def model_to_dict(model_instance, serialize=True): model_instances = [model_instance] if model_instance._composed_schemas: model_instances.extend(model_instance._composed_instances) + seen_json_attribute_names = set() + used_fallback_python_attribute_names = set() + py_to_json_map = {} for model_instance in model_instances: for attr, value in model_instance._data_store.items(): if serialize: # we use get here because additional property key names do not # exist in attribute_map - attr = model_instance.attribute_map.get(attr, attr) + try: + attr = model_instance.attribute_map[attr] + py_to_json_map.update(model_instance.attribute_map) + seen_json_attribute_names.add(attr) + except KeyError: + used_fallback_python_attribute_names.add(attr) if isinstance(value, list): if not value: # empty list or None @@ -1665,6 +1673,16 @@ def model_to_dict(model_instance, serialize=True): result[attr] = model_to_dict(value, serialize=serialize) else: result[attr] = value + if serialize: + for python_key in used_fallback_python_attribute_names: + json_key = py_to_json_map.get(python_key) + if json_key is None: + continue + if python_key == json_key: + continue + json_key_assigned_no_need_for_python_key = json_key in seen_json_attribute_names + if json_key_assigned_no_need_for_python_key: + del result[python_key] return result diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/python/x_auth_id_alias/rest.py b/samples/openapi3/client/extensions/x-auth-id-alias/python/x_auth_id_alias/rest.py index a0a26a797db..a7c5fd3304a 100644 --- a/samples/openapi3/client/extensions/x-auth-id-alias/python/x_auth_id_alias/rest.py +++ b/samples/openapi3/client/extensions/x-auth-id-alias/python/x_auth_id_alias/rest.py @@ -137,15 +137,15 @@ class RESTClientObject(object): timeout = urllib3.Timeout( connect=_request_timeout[0], read=_request_timeout[1]) - if 'Content-Type' not in headers: - headers['Content-Type'] = 'application/json' - try: # For `POST`, `PUT`, `PATCH`, `OPTIONS`, `DELETE` if method in ['POST', 'PUT', 'PATCH', 'OPTIONS', 'DELETE']: + # Only set a default Content-Type for POST, PUT, PATCH and OPTIONS requests + if (method != 'DELETE') and ('Content-Type' not in headers): + headers['Content-Type'] = 'application/json' if query_params: url += '?' + urlencode(query_params) - if re.search('json', headers['Content-Type'], re.IGNORECASE): + if ('Content-Type' not in headers) or (re.search('json', headers['Content-Type'], re.IGNORECASE)): request_body = None if body is not None: request_body = json.dumps(body) 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 5f68295fc19..e8415097f3a 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,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x 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 6d6964932aa..6b0cd8c3f24 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,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =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 4dc01f94637..faa5b134f3f 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,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =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 18182705e43..2e38f9a7aa3 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,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =end 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 90a45186eea..2d72fa80345 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,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =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 bb9d76c3d63..ddb0210f483 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,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =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 66381103e77..a8ca97a68c7 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,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =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 558b77058c7..7ff16c42a04 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,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =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 c011e31b222..34ae878d3d1 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,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =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 1f191e8eb0e..46f1c4b68fb 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,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =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 007ed603179..376e985a334 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,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =end diff --git a/samples/openapi3/client/features/dynamic-servers/python/.openapi-generator/VERSION b/samples/openapi3/client/features/dynamic-servers/python/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/openapi3/client/features/dynamic-servers/python/.openapi-generator/VERSION +++ b/samples/openapi3/client/features/dynamic-servers/python/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/openapi3/client/features/dynamic-servers/python/dynamic_servers/api/usage_api.py b/samples/openapi3/client/features/dynamic-servers/python/dynamic_servers/api/usage_api.py index 5da74def3fb..c60c19b881b 100644 --- a/samples/openapi3/client/features/dynamic-servers/python/dynamic_servers/api/usage_api.py +++ b/samples/openapi3/client/features/dynamic-servers/python/dynamic_servers/api/usage_api.py @@ -55,8 +55,8 @@ class UsageApi(object): _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. - _request_timeout (float/tuple): timeout setting for this request. If one - number provided, it will be total request timeout. It can also + _request_timeout (int/float/tuple): timeout setting for this request. If + one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking @@ -209,8 +209,8 @@ class UsageApi(object): _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. - _request_timeout (float/tuple): timeout setting for this request. If one - number provided, it will be total request timeout. It can also + _request_timeout (int/float/tuple): timeout setting for this request. If + one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking diff --git a/samples/openapi3/client/features/dynamic-servers/python/dynamic_servers/api_client.py b/samples/openapi3/client/features/dynamic-servers/python/dynamic_servers/api_client.py index 0b76cbb12b1..81247d2f6e5 100644 --- a/samples/openapi3/client/features/dynamic-servers/python/dynamic_servers/api_client.py +++ b/samples/openapi3/client/features/dynamic-servers/python/dynamic_servers/api_client.py @@ -129,7 +129,7 @@ class ApiClient(object): _return_http_data_only: typing.Optional[bool] = None, collection_formats: typing.Optional[typing.Dict[str, str]] = None, _preload_content: bool = True, - _request_timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + _request_timeout: typing.Optional[typing.Union[int, float, typing.Tuple]] = None, _host: typing.Optional[str] = None, _check_type: typing.Optional[bool] = None ): @@ -347,7 +347,7 @@ class ApiClient(object): _return_http_data_only: typing.Optional[bool] = None, collection_formats: typing.Optional[typing.Dict[str, str]] = None, _preload_content: bool = True, - _request_timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + _request_timeout: typing.Optional[typing.Union[int, float, typing.Tuple]] = None, _host: typing.Optional[str] = None, _check_type: typing.Optional[bool] = None ): @@ -674,7 +674,7 @@ class Endpoint(object): 'async_req': (bool,), '_host_index': (none_type, int), '_preload_content': (bool,), - '_request_timeout': (none_type, int, (int,), [int]), + '_request_timeout': (none_type, float, (float,), [float], int, (int,), [int]), '_return_http_data_only': (bool,), '_check_input_type': (bool,), '_check_return_type': (bool,) diff --git a/samples/openapi3/client/features/dynamic-servers/python/dynamic_servers/model_utils.py b/samples/openapi3/client/features/dynamic-servers/python/dynamic_servers/model_utils.py index 2fcf6b2de1e..fa10b2d24f9 100644 --- a/samples/openapi3/client/features/dynamic-servers/python/dynamic_servers/model_utils.py +++ b/samples/openapi3/client/features/dynamic-servers/python/dynamic_servers/model_utils.py @@ -47,7 +47,7 @@ def convert_js_args_to_python_args(fn): class cached_property(object): # this caches the result of the function call for fn with no inputs - # use this as a decorator on fuction methods that you want converted + # use this as a decorator on function methods that you want converted # into cached properties result_key = '_results' @@ -1632,12 +1632,20 @@ def model_to_dict(model_instance, serialize=True): model_instances = [model_instance] if model_instance._composed_schemas: model_instances.extend(model_instance._composed_instances) + seen_json_attribute_names = set() + used_fallback_python_attribute_names = set() + py_to_json_map = {} for model_instance in model_instances: for attr, value in model_instance._data_store.items(): if serialize: # we use get here because additional property key names do not # exist in attribute_map - attr = model_instance.attribute_map.get(attr, attr) + try: + attr = model_instance.attribute_map[attr] + py_to_json_map.update(model_instance.attribute_map) + seen_json_attribute_names.add(attr) + except KeyError: + used_fallback_python_attribute_names.add(attr) if isinstance(value, list): if not value: # empty list or None @@ -1665,6 +1673,16 @@ def model_to_dict(model_instance, serialize=True): result[attr] = model_to_dict(value, serialize=serialize) else: result[attr] = value + if serialize: + for python_key in used_fallback_python_attribute_names: + json_key = py_to_json_map.get(python_key) + if json_key is None: + continue + if python_key == json_key: + continue + json_key_assigned_no_need_for_python_key = json_key in seen_json_attribute_names + if json_key_assigned_no_need_for_python_key: + del result[python_key] return result diff --git a/samples/openapi3/client/features/dynamic-servers/python/dynamic_servers/rest.py b/samples/openapi3/client/features/dynamic-servers/python/dynamic_servers/rest.py index 979c58eb200..191d850b87d 100644 --- a/samples/openapi3/client/features/dynamic-servers/python/dynamic_servers/rest.py +++ b/samples/openapi3/client/features/dynamic-servers/python/dynamic_servers/rest.py @@ -137,15 +137,15 @@ class RESTClientObject(object): timeout = urllib3.Timeout( connect=_request_timeout[0], read=_request_timeout[1]) - if 'Content-Type' not in headers: - headers['Content-Type'] = 'application/json' - try: # For `POST`, `PUT`, `PATCH`, `OPTIONS`, `DELETE` if method in ['POST', 'PUT', 'PATCH', 'OPTIONS', 'DELETE']: + # Only set a default Content-Type for POST, PUT, PATCH and OPTIONS requests + if (method != 'DELETE') and ('Content-Type' not in headers): + headers['Content-Type'] = 'application/json' if query_params: url += '?' + urlencode(query_params) - if re.search('json', headers['Content-Type'], re.IGNORECASE): + if ('Content-Type' not in headers) or (re.search('json', headers['Content-Type'], re.IGNORECASE)): request_body = None if body is not None: request_body = json.dumps(body) 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 5f68295fc19..e8415097f3a 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,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x 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 dfe7d45dedc..5f9398cd7d0 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,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =end 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 ac81bc65875..3f3de89c19f 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,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =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 44ad371b1df..aca35586cf5 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,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =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 d61333491f5..fcd2eca8f2b 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,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =end 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 42728038602..6051e3abf41 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,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =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 f157fa0714a..3c20866303c 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,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =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 0498388e6c2..8338974e211 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,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =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 f370745a6a5..e07d9e42019 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,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =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 0cf4da3cbc2..873083eddda 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,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =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 2c425b59e55..8d5d7e541b2 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,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =end 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 5f68295fc19..e8415097f3a 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,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x 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 65857baeb0c..db7c52d5e38 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,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =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 af0e5cba9a7..2026f933021 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,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =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 18b8ee414ea..80aba24f320 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,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =end 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 da466010b4e..0c743fb9bb8 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,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =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 c71bc79af69..802ccad1482 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,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =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 c72355b506c..98fa01b0566 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,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =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 cf7fc57d9bb..88b9d58c0fa 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,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =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 df2dd7ae50a..57e7a26260f 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,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =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 8a19b1bfcda..f7eb2a72666 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,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =end 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 1d6dbf9b5ac..dd5ab897699 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,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =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 9e5aa7b6f4a..63ad6199056 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,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =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 f4974f981a3..8744501e48e 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,11 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech +<<<<<<< HEAD OpenAPI Generator version: 6.0.0-SNAPSHOT +======= +OpenAPI Generator version: 5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x =end diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/.gitignore b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/.gitignore index 8092a49d515..6d2ac22c0b4 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/.gitignore +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/.gitignore @@ -30,8 +30,12 @@ pubspec.lock # Don’t commit files and directories created by other development environments. # For example, if your development environment creates any of the following files, # consider putting them in a global ignore file: -*.iml // IntelliJ -*.ipr // IntelliJ -*.iws // IntelliJ -.idea/ // IntelliJ -.DS_Store // Mac + +# IntelliJ +*.iml +*.ipr +*.iws +.idea/ + +# Mac +.DS_Store diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/.openapi-generator/VERSION b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/.openapi-generator/VERSION +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/README.md b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/README.md index f49dd295950..0e312d4370d 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/README.md +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/README.md @@ -46,8 +46,8 @@ Please follow the [installation procedure](#installation--usage) and then run th import 'package:openapi/openapi.dart'; -final api = AnotherFakeApi(); -final modelClient = ModelClient(); // ModelClient | client model +final api = Openapi().getAnotherFakeApi(); +final ModelClient modelClient = ; // ModelClient | client model try { final response = await api.call123testSpecialTags(modelClient); @@ -64,46 +64,47 @@ All URIs are relative to *http://petstore.swagger.io:80/v2* Class | Method | HTTP request | Description ------------ | ------------- | ------------- | ------------- -*AnotherFakeApi* | [**call123testSpecialTags**](doc/AnotherFakeApi.md#call123testspecialtags) | **patch** /another-fake/dummy | To test special tags -*DefaultApi* | [**fooGet**](doc/DefaultApi.md#fooget) | **get** /foo | -*FakeApi* | [**fakeHealthGet**](doc/FakeApi.md#fakehealthget) | **get** /fake/health | Health check endpoint -*FakeApi* | [**fakeHttpSignatureTest**](doc/FakeApi.md#fakehttpsignaturetest) | **get** /fake/http-signature-test | test http signature authentication -*FakeApi* | [**fakeOuterBooleanSerialize**](doc/FakeApi.md#fakeouterbooleanserialize) | **post** /fake/outer/boolean | -*FakeApi* | [**fakeOuterCompositeSerialize**](doc/FakeApi.md#fakeoutercompositeserialize) | **post** /fake/outer/composite | -*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* | [**testBodyWithFileSchema**](doc/FakeApi.md#testbodywithfileschema) | **put** /fake/body-with-file-schema | -*FakeApi* | [**testBodyWithQueryParams**](doc/FakeApi.md#testbodywithqueryparams) | **put** /fake/body-with-query-params | -*FakeApi* | [**testClientModel**](doc/FakeApi.md#testclientmodel) | **patch** /fake | To test \"client\" model -*FakeApi* | [**testEndpointParameters**](doc/FakeApi.md#testendpointparameters) | **post** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 -*FakeApi* | [**testEnumParameters**](doc/FakeApi.md#testenumparameters) | **get** /fake | To test enum parameters -*FakeApi* | [**testGroupParameters**](doc/FakeApi.md#testgroupparameters) | **delete** /fake | Fake endpoint to test group parameters (optional) -*FakeApi* | [**testInlineAdditionalProperties**](doc/FakeApi.md#testinlineadditionalproperties) | **post** /fake/inline-additionalProperties | test inline additionalProperties -*FakeApi* | [**testJsonFormData**](doc/FakeApi.md#testjsonformdata) | **get** /fake/jsonFormData | test json serialization of form data -*FakeApi* | [**testQueryParameterCollectionFormat**](doc/FakeApi.md#testqueryparametercollectionformat) | **put** /fake/test-query-paramters | -*FakeClassnameTags123Api* | [**testClassname**](doc/FakeClassnameTags123Api.md#testclassname) | **patch** /fake_classname_test | To test class name in snake case -*PetApi* | [**addPet**](doc/PetApi.md#addpet) | **post** /pet | Add a new pet to the store -*PetApi* | [**deletePet**](doc/PetApi.md#deletepet) | **delete** /pet/{petId} | Deletes a pet -*PetApi* | [**findPetsByStatus**](doc/PetApi.md#findpetsbystatus) | **get** /pet/findByStatus | Finds Pets by status -*PetApi* | [**findPetsByTags**](doc/PetApi.md#findpetsbytags) | **get** /pet/findByTags | Finds Pets by tags -*PetApi* | [**getPetById**](doc/PetApi.md#getpetbyid) | **get** /pet/{petId} | Find pet by ID -*PetApi* | [**updatePet**](doc/PetApi.md#updatepet) | **put** /pet | Update an existing pet -*PetApi* | [**updatePetWithForm**](doc/PetApi.md#updatepetwithform) | **post** /pet/{petId} | Updates a pet in the store with form data -*PetApi* | [**uploadFile**](doc/PetApi.md#uploadfile) | **post** /pet/{petId}/uploadImage | uploads an image -*PetApi* | [**uploadFileWithRequiredFile**](doc/PetApi.md#uploadfilewithrequiredfile) | **post** /fake/{petId}/uploadImageWithRequiredFile | uploads an image (required) -*StoreApi* | [**deleteOrder**](doc/StoreApi.md#deleteorder) | **delete** /store/order/{order_id} | Delete purchase order by ID -*StoreApi* | [**getInventory**](doc/StoreApi.md#getinventory) | **get** /store/inventory | Returns pet inventories by status -*StoreApi* | [**getOrderById**](doc/StoreApi.md#getorderbyid) | **get** /store/order/{order_id} | Find purchase order by ID -*StoreApi* | [**placeOrder**](doc/StoreApi.md#placeorder) | **post** /store/order | Place an order for a pet -*UserApi* | [**createUser**](doc/UserApi.md#createuser) | **post** /user | Create user -*UserApi* | [**createUsersWithArrayInput**](doc/UserApi.md#createuserswitharrayinput) | **post** /user/createWithArray | Creates list of users with given input array -*UserApi* | [**createUsersWithListInput**](doc/UserApi.md#createuserswithlistinput) | **post** /user/createWithList | Creates list of users with given input array -*UserApi* | [**deleteUser**](doc/UserApi.md#deleteuser) | **delete** /user/{username} | Delete user -*UserApi* | [**getUserByName**](doc/UserApi.md#getuserbyname) | **get** /user/{username} | Get user by user name -*UserApi* | [**loginUser**](doc/UserApi.md#loginuser) | **get** /user/login | Logs user into the system -*UserApi* | [**logoutUser**](doc/UserApi.md#logoutuser) | **get** /user/logout | Logs out current logged in user session -*UserApi* | [**updateUser**](doc/UserApi.md#updateuser) | **put** /user/{username} | Updated user +[*AnotherFakeApi*](doc/AnotherFakeApi.md) | [**call123testSpecialTags**](doc/AnotherFakeApi.md#call123testspecialtags) | **PATCH** /another-fake/dummy | To test special tags +[*DefaultApi*](doc/DefaultApi.md) | [**fooGet**](doc/DefaultApi.md#fooget) | **GET** /foo | +[*FakeApi*](doc/FakeApi.md) | [**fakeHealthGet**](doc/FakeApi.md#fakehealthget) | **GET** /fake/health | Health check endpoint +[*FakeApi*](doc/FakeApi.md) | [**fakeHttpSignatureTest**](doc/FakeApi.md#fakehttpsignaturetest) | **GET** /fake/http-signature-test | test http signature authentication +[*FakeApi*](doc/FakeApi.md) | [**fakeOuterBooleanSerialize**](doc/FakeApi.md#fakeouterbooleanserialize) | **POST** /fake/outer/boolean | +[*FakeApi*](doc/FakeApi.md) | [**fakeOuterCompositeSerialize**](doc/FakeApi.md#fakeoutercompositeserialize) | **POST** /fake/outer/composite | +[*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) | [**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 | +[*FakeApi*](doc/FakeApi.md) | [**testClientModel**](doc/FakeApi.md#testclientmodel) | **PATCH** /fake | To test \"client\" model +[*FakeApi*](doc/FakeApi.md) | [**testEndpointParameters**](doc/FakeApi.md#testendpointparameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 +[*FakeApi*](doc/FakeApi.md) | [**testEnumParameters**](doc/FakeApi.md#testenumparameters) | **GET** /fake | To test enum parameters +[*FakeApi*](doc/FakeApi.md) | [**testGroupParameters**](doc/FakeApi.md#testgroupparameters) | **DELETE** /fake | Fake endpoint to test group parameters (optional) +[*FakeApi*](doc/FakeApi.md) | [**testInlineAdditionalProperties**](doc/FakeApi.md#testinlineadditionalproperties) | **POST** /fake/inline-additionalProperties | test inline additionalProperties +[*FakeApi*](doc/FakeApi.md) | [**testJsonFormData**](doc/FakeApi.md#testjsonformdata) | **GET** /fake/jsonFormData | test json serialization of form data +[*FakeApi*](doc/FakeApi.md) | [**testQueryParameterCollectionFormat**](doc/FakeApi.md#testqueryparametercollectionformat) | **PUT** /fake/test-query-paramters | +[*FakeClassnameTags123Api*](doc/FakeClassnameTags123Api.md) | [**testClassname**](doc/FakeClassnameTags123Api.md#testclassname) | **PATCH** /fake_classname_test | To test class name in snake case +[*PetApi*](doc/PetApi.md) | [**addPet**](doc/PetApi.md#addpet) | **POST** /pet | Add a new pet to the store +[*PetApi*](doc/PetApi.md) | [**deletePet**](doc/PetApi.md#deletepet) | **DELETE** /pet/{petId} | Deletes a pet +[*PetApi*](doc/PetApi.md) | [**findPetsByStatus**](doc/PetApi.md#findpetsbystatus) | **GET** /pet/findByStatus | Finds Pets by status +[*PetApi*](doc/PetApi.md) | [**findPetsByTags**](doc/PetApi.md#findpetsbytags) | **GET** /pet/findByTags | Finds Pets by tags +[*PetApi*](doc/PetApi.md) | [**getPetById**](doc/PetApi.md#getpetbyid) | **GET** /pet/{petId} | Find pet by ID +[*PetApi*](doc/PetApi.md) | [**updatePet**](doc/PetApi.md#updatepet) | **PUT** /pet | Update an existing pet +[*PetApi*](doc/PetApi.md) | [**updatePetWithForm**](doc/PetApi.md#updatepetwithform) | **POST** /pet/{petId} | Updates a pet in the store with form data +[*PetApi*](doc/PetApi.md) | [**uploadFile**](doc/PetApi.md#uploadfile) | **POST** /pet/{petId}/uploadImage | uploads an image +[*PetApi*](doc/PetApi.md) | [**uploadFileWithRequiredFile**](doc/PetApi.md#uploadfilewithrequiredfile) | **POST** /fake/{petId}/uploadImageWithRequiredFile | uploads an image (required) +[*StoreApi*](doc/StoreApi.md) | [**deleteOrder**](doc/StoreApi.md#deleteorder) | **DELETE** /store/order/{order_id} | Delete purchase order by ID +[*StoreApi*](doc/StoreApi.md) | [**getInventory**](doc/StoreApi.md#getinventory) | **GET** /store/inventory | Returns pet inventories by status +[*StoreApi*](doc/StoreApi.md) | [**getOrderById**](doc/StoreApi.md#getorderbyid) | **GET** /store/order/{order_id} | Find purchase order by ID +[*StoreApi*](doc/StoreApi.md) | [**placeOrder**](doc/StoreApi.md#placeorder) | **POST** /store/order | Place an order for a pet +[*UserApi*](doc/UserApi.md) | [**createUser**](doc/UserApi.md#createuser) | **POST** /user | Create user +[*UserApi*](doc/UserApi.md) | [**createUsersWithArrayInput**](doc/UserApi.md#createuserswitharrayinput) | **POST** /user/createWithArray | Creates list of users with given input array +[*UserApi*](doc/UserApi.md) | [**createUsersWithListInput**](doc/UserApi.md#createuserswithlistinput) | **POST** /user/createWithList | Creates list of users with given input array +[*UserApi*](doc/UserApi.md) | [**deleteUser**](doc/UserApi.md#deleteuser) | **DELETE** /user/{username} | Delete user +[*UserApi*](doc/UserApi.md) | [**getUserByName**](doc/UserApi.md#getuserbyname) | **GET** /user/{username} | Get user by user name +[*UserApi*](doc/UserApi.md) | [**loginUser**](doc/UserApi.md#loginuser) | **GET** /user/login | Logs user into the system +[*UserApi*](doc/UserApi.md) | [**logoutUser**](doc/UserApi.md#logoutuser) | **GET** /user/logout | Logs out current logged in user session +[*UserApi*](doc/UserApi.md) | [**updateUser**](doc/UserApi.md#updateuser) | **PUT** /user/{username} | Updated user ## Documentation For Models diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/doc/AdditionalPropertiesClass.md b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/doc/AdditionalPropertiesClass.md index 5443d024fd2..f9f7857894d 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/doc/AdditionalPropertiesClass.md +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/doc/AdditionalPropertiesClass.md @@ -8,8 +8,8 @@ import 'package:openapi/api.dart'; ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**mapProperty** | **BuiltMap** | | [optional] -**mapOfMapProperty** | [**BuiltMap>**](BuiltMap.md) | | [optional] +**mapProperty** | **BuiltMap<String, String>** | | [optional] +**mapOfMapProperty** | [**BuiltMap<String, BuiltMap<String, String>>**](BuiltMap.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/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/doc/AnotherFakeApi.md b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/doc/AnotherFakeApi.md index d55663297c1..9416627d74d 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/doc/AnotherFakeApi.md +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/doc/AnotherFakeApi.md @@ -9,7 +9,7 @@ All URIs are relative to *http://petstore.swagger.io:80/v2* Method | HTTP request | Description ------------- | ------------- | ------------- -[**call123testSpecialTags**](AnotherFakeApi.md#call123testspecialtags) | **patch** /another-fake/dummy | To test special tags +[**call123testSpecialTags**](AnotherFakeApi.md#call123testspecialtags) | **PATCH** /another-fake/dummy | To test special tags # **call123testSpecialTags** @@ -23,13 +23,13 @@ To test special tags and operation ID starting with number ```dart import 'package:openapi/api.dart'; -var api_instance = new AnotherFakeApi(); -var modelClient = new ModelClient(); // ModelClient | client model +final api = Openapi().getAnotherFakeApi(); +final ModelClient modelClient = ; // ModelClient | client model try { - var result = api_instance.call123testSpecialTags(modelClient); - print(result); -} catch (e) { + final response = api.call123testSpecialTags(modelClient); + print(response); +} catch on DioError (e) { print('Exception when calling AnotherFakeApi->call123testSpecialTags: $e\n'); } ``` diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/doc/ArrayOfArrayOfNumberOnly.md b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/doc/ArrayOfArrayOfNumberOnly.md index 0a9d69c7e3c..d1a272ab602 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/doc/ArrayOfArrayOfNumberOnly.md +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/doc/ArrayOfArrayOfNumberOnly.md @@ -8,7 +8,7 @@ import 'package:openapi/api.dart'; ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**arrayArrayNumber** | [**BuiltList>**](BuiltList.md) | | [optional] +**arrayArrayNumber** | [**BuiltList<BuiltList<num>>**](BuiltList.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/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/doc/ArrayOfNumberOnly.md b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/doc/ArrayOfNumberOnly.md index 6ffe36730c2..94b60f272fd 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/doc/ArrayOfNumberOnly.md +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/doc/ArrayOfNumberOnly.md @@ -8,7 +8,7 @@ import 'package:openapi/api.dart'; ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**arrayNumber** | **BuiltList** | | [optional] +**arrayNumber** | **BuiltList<num>** | | [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-next/petstore_client_lib_fake/doc/ArrayTest.md b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/doc/ArrayTest.md index fc38f8ae52d..0813d4fa93c 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/doc/ArrayTest.md +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/doc/ArrayTest.md @@ -8,9 +8,9 @@ import 'package:openapi/api.dart'; ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**arrayOfString** | **BuiltList** | | [optional] -**arrayArrayOfInteger** | [**BuiltList>**](BuiltList.md) | | [optional] -**arrayArrayOfModel** | [**BuiltList>**](BuiltList.md) | | [optional] +**arrayOfString** | **BuiltList<String>** | | [optional] +**arrayArrayOfInteger** | [**BuiltList<BuiltList<int>>**](BuiltList.md) | | [optional] +**arrayArrayOfModel** | [**BuiltList<BuiltList<ReadOnlyFirst>>**](BuiltList.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/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/doc/DefaultApi.md b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/doc/DefaultApi.md index be916c3037d..5b5a2cdead6 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/doc/DefaultApi.md +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/doc/DefaultApi.md @@ -9,7 +9,7 @@ All URIs are relative to *http://petstore.swagger.io:80/v2* Method | HTTP request | Description ------------- | ------------- | ------------- -[**fooGet**](DefaultApi.md#fooget) | **get** /foo | +[**fooGet**](DefaultApi.md#fooget) | **GET** /foo | # **fooGet** @@ -21,12 +21,12 @@ Method | HTTP request | Description ```dart import 'package:openapi/api.dart'; -var api_instance = new DefaultApi(); +final api = Openapi().getDefaultApi(); try { - var result = api_instance.fooGet(); - print(result); -} catch (e) { + final response = api.fooGet(); + print(response); +} catch on DioError (e) { print('Exception when calling DefaultApi->fooGet: $e\n'); } ``` diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/doc/EnumArrays.md b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/doc/EnumArrays.md index 9cc4d727b2a..06170bb8f51 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/doc/EnumArrays.md +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/doc/EnumArrays.md @@ -9,7 +9,7 @@ import 'package:openapi/api.dart'; Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **justSymbol** | **String** | | [optional] -**arrayEnum** | **BuiltList** | | [optional] +**arrayEnum** | **BuiltList<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/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/doc/FakeApi.md b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/doc/FakeApi.md index c01cc40f97d..b8e90ea6074 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/doc/FakeApi.md +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/doc/FakeApi.md @@ -9,22 +9,23 @@ All URIs are relative to *http://petstore.swagger.io:80/v2* Method | HTTP request | Description ------------- | ------------- | ------------- -[**fakeHealthGet**](FakeApi.md#fakehealthget) | **get** /fake/health | Health check endpoint -[**fakeHttpSignatureTest**](FakeApi.md#fakehttpsignaturetest) | **get** /fake/http-signature-test | test http signature authentication -[**fakeOuterBooleanSerialize**](FakeApi.md#fakeouterbooleanserialize) | **post** /fake/outer/boolean | -[**fakeOuterCompositeSerialize**](FakeApi.md#fakeoutercompositeserialize) | **post** /fake/outer/composite | -[**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 | -[**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 -[**testEndpointParameters**](FakeApi.md#testendpointparameters) | **post** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 -[**testEnumParameters**](FakeApi.md#testenumparameters) | **get** /fake | To test enum parameters -[**testGroupParameters**](FakeApi.md#testgroupparameters) | **delete** /fake | Fake endpoint to test group parameters (optional) -[**testInlineAdditionalProperties**](FakeApi.md#testinlineadditionalproperties) | **post** /fake/inline-additionalProperties | test inline additionalProperties -[**testJsonFormData**](FakeApi.md#testjsonformdata) | **get** /fake/jsonFormData | test json serialization of form data -[**testQueryParameterCollectionFormat**](FakeApi.md#testqueryparametercollectionformat) | **put** /fake/test-query-paramters | +[**fakeHealthGet**](FakeApi.md#fakehealthget) | **GET** /fake/health | Health check endpoint +[**fakeHttpSignatureTest**](FakeApi.md#fakehttpsignaturetest) | **GET** /fake/http-signature-test | test http signature authentication +[**fakeOuterBooleanSerialize**](FakeApi.md#fakeouterbooleanserialize) | **POST** /fake/outer/boolean | +[**fakeOuterCompositeSerialize**](FakeApi.md#fakeoutercompositeserialize) | **POST** /fake/outer/composite | +[**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 | +[**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 | +[**testClientModel**](FakeApi.md#testclientmodel) | **PATCH** /fake | To test \"client\" model +[**testEndpointParameters**](FakeApi.md#testendpointparameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 +[**testEnumParameters**](FakeApi.md#testenumparameters) | **GET** /fake | To test enum parameters +[**testGroupParameters**](FakeApi.md#testgroupparameters) | **DELETE** /fake | Fake endpoint to test group parameters (optional) +[**testInlineAdditionalProperties**](FakeApi.md#testinlineadditionalproperties) | **POST** /fake/inline-additionalProperties | test inline additionalProperties +[**testJsonFormData**](FakeApi.md#testjsonformdata) | **GET** /fake/jsonFormData | test json serialization of form data +[**testQueryParameterCollectionFormat**](FakeApi.md#testqueryparametercollectionformat) | **PUT** /fake/test-query-paramters | # **fakeHealthGet** @@ -36,12 +37,12 @@ Health check endpoint ```dart import 'package:openapi/api.dart'; -var api_instance = new FakeApi(); +final api = Openapi().getFakeApi(); try { - var result = api_instance.fakeHealthGet(); - print(result); -} catch (e) { + final response = api.fakeHealthGet(); + print(response); +} catch on DioError (e) { print('Exception when calling FakeApi->fakeHealthGet: $e\n'); } ``` @@ -76,14 +77,14 @@ import 'package:openapi/api.dart'; //defaultApiClient.getAuthentication('http_signature_test').username = 'YOUR_USERNAME' //defaultApiClient.getAuthentication('http_signature_test').password = 'YOUR_PASSWORD'; -var api_instance = new FakeApi(); -var pet = new Pet(); // Pet | Pet object that needs to be added to the store -var query1 = query1_example; // String | query parameter -var header1 = header1_example; // String | header parameter +final api = Openapi().getFakeApi(); +final Pet pet = ; // Pet | Pet object that needs to be added to the store +final String query1 = query1_example; // String | query parameter +final String header1 = header1_example; // String | header parameter try { - api_instance.fakeHttpSignatureTest(pet, query1, header1); -} catch (e) { + api.fakeHttpSignatureTest(pet, query1, header1); +} catch on DioError (e) { print('Exception when calling FakeApi->fakeHttpSignatureTest: $e\n'); } ``` @@ -122,13 +123,13 @@ Test serialization of outer boolean types ```dart import 'package:openapi/api.dart'; -var api_instance = new FakeApi(); -var body = new bool(); // bool | Input boolean as post body +final api = Openapi().getFakeApi(); +final bool body = true; // bool | Input boolean as post body try { - var result = api_instance.fakeOuterBooleanSerialize(body); - print(result); -} catch (e) { + final response = api.fakeOuterBooleanSerialize(body); + print(response); +} catch on DioError (e) { print('Exception when calling FakeApi->fakeOuterBooleanSerialize: $e\n'); } ``` @@ -165,13 +166,13 @@ Test serialization of object with outer number type ```dart import 'package:openapi/api.dart'; -var api_instance = new FakeApi(); -var outerComposite = new OuterComposite(); // OuterComposite | Input composite as post body +final api = Openapi().getFakeApi(); +final OuterComposite outerComposite = ; // OuterComposite | Input composite as post body try { - var result = api_instance.fakeOuterCompositeSerialize(outerComposite); - print(result); -} catch (e) { + final response = api.fakeOuterCompositeSerialize(outerComposite); + print(response); +} catch on DioError (e) { print('Exception when calling FakeApi->fakeOuterCompositeSerialize: $e\n'); } ``` @@ -208,13 +209,13 @@ Test serialization of outer number types ```dart import 'package:openapi/api.dart'; -var api_instance = new FakeApi(); -var body = new num(); // num | Input number as post body +final api = Openapi().getFakeApi(); +final num body = 8.14; // num | Input number as post body try { - var result = api_instance.fakeOuterNumberSerialize(body); - print(result); -} catch (e) { + final response = api.fakeOuterNumberSerialize(body); + print(response); +} catch on DioError (e) { print('Exception when calling FakeApi->fakeOuterNumberSerialize: $e\n'); } ``` @@ -251,13 +252,13 @@ Test serialization of outer string types ```dart import 'package:openapi/api.dart'; -var api_instance = new FakeApi(); -var body = new String(); // String | Input string as post body +final api = Openapi().getFakeApi(); +final String body = body_example; // String | Input string as post body try { - var result = api_instance.fakeOuterStringSerialize(body); - print(result); -} catch (e) { + final response = api.fakeOuterStringSerialize(body); + print(response); +} catch on DioError (e) { print('Exception when calling FakeApi->fakeOuterStringSerialize: $e\n'); } ``` @@ -294,13 +295,13 @@ Test serialization of enum (int) properties with examples ```dart import 'package:openapi/api.dart'; -var api_instance = new FakeApi(); -var outerObjectWithEnumProperty = new OuterObjectWithEnumProperty(); // OuterObjectWithEnumProperty | Input enum (int) as post body +final api = Openapi().getFakeApi(); +final OuterObjectWithEnumProperty outerObjectWithEnumProperty = ; // OuterObjectWithEnumProperty | Input enum (int) as post body try { - var result = api_instance.fakePropertyEnumIntegerSerialize(outerObjectWithEnumProperty); - print(result); -} catch (e) { + final response = api.fakePropertyEnumIntegerSerialize(outerObjectWithEnumProperty); + print(response); +} catch on DioError (e) { print('Exception when calling FakeApi->fakePropertyEnumIntegerSerialize: $e\n'); } ``` @@ -326,23 +327,65 @@ 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) -# **testBodyWithFileSchema** -> testBodyWithFileSchema(fileSchemaTestClass) +# **testBodyWithBinary** +> testBodyWithBinary(body) -For this test, the body for this request much reference a schema named `File`. +For this test, the body has to be a binary file. ### Example ```dart import 'package:openapi/api.dart'; -var api_instance = new FakeApi(); -var fileSchemaTestClass = new FileSchemaTestClass(); // FileSchemaTestClass | +final api = Openapi().getFakeApi(); +final MultipartFile body = BINARY_DATA_HERE; // MultipartFile | image to upload try { - api_instance.testBodyWithFileSchema(fileSchemaTestClass); -} catch (e) { + api.testBodyWithBinary(body); +} catch on DioError (e) { + print('Exception when calling FakeApi->testBodyWithBinary: $e\n'); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | **MultipartFile**| image to upload | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: image/png + - **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(fileSchemaTestClass) + + + +For this test, the body for this request must reference a schema named `File`. + +### Example +```dart +import 'package:openapi/api.dart'; + +final api = Openapi().getFakeApi(); +final FileSchemaTestClass fileSchemaTestClass = ; // FileSchemaTestClass | + +try { + api.testBodyWithFileSchema(fileSchemaTestClass); +} catch on DioError (e) { print('Exception when calling FakeApi->testBodyWithFileSchema: $e\n'); } ``` @@ -377,13 +420,13 @@ No authorization required ```dart import 'package:openapi/api.dart'; -var api_instance = new FakeApi(); -var query = query_example; // String | -var user = new User(); // User | +final api = Openapi().getFakeApi(); +final String query = query_example; // String | +final User user = ; // User | try { - api_instance.testBodyWithQueryParams(query, user); -} catch (e) { + api.testBodyWithQueryParams(query, user); +} catch on DioError (e) { print('Exception when calling FakeApi->testBodyWithQueryParams: $e\n'); } ``` @@ -421,13 +464,13 @@ To test \"client\" model ```dart import 'package:openapi/api.dart'; -var api_instance = new FakeApi(); -var modelClient = new ModelClient(); // ModelClient | client model +final api = Openapi().getFakeApi(); +final ModelClient modelClient = ; // ModelClient | client model try { - var result = api_instance.testClientModel(modelClient); - print(result); -} catch (e) { + final response = api.testClientModel(modelClient); + print(response); +} catch on DioError (e) { print('Exception when calling FakeApi->testClientModel: $e\n'); } ``` @@ -467,25 +510,25 @@ import 'package:openapi/api.dart'; //defaultApiClient.getAuthentication('http_basic_test').username = 'YOUR_USERNAME' //defaultApiClient.getAuthentication('http_basic_test').password = 'YOUR_PASSWORD'; -var api_instance = new FakeApi(); -var number = 8.14; // num | None -var double_ = 1.2; // double | None -var patternWithoutDelimiter = patternWithoutDelimiter_example; // String | None -var byte = BYTE_ARRAY_DATA_HERE; // String | None -var integer = 56; // int | None -var int32 = 56; // int | None -var int64 = 789; // int | None -var float = 3.4; // double | None -var string = string_example; // String | None -var binary = BINARY_DATA_HERE; // Uint8List | None -var date = 2013-10-20; // Date | None -var dateTime = 2013-10-20T19:20:30+01:00; // DateTime | None -var password = password_example; // String | None -var callback = callback_example; // String | None +final api = Openapi().getFakeApi(); +final num number = 8.14; // num | None +final double double_ = 1.2; // double | None +final String patternWithoutDelimiter = patternWithoutDelimiter_example; // String | None +final String byte = BYTE_ARRAY_DATA_HERE; // String | None +final int integer = 56; // int | None +final int int32 = 56; // int | None +final int int64 = 789; // int | None +final double float = 3.4; // double | None +final String string = string_example; // String | None +final Uint8List binary = BINARY_DATA_HERE; // Uint8List | None +final Date date = 2013-10-20; // Date | None +final DateTime dateTime = 2013-10-20T19:20:30+01:00; // DateTime | None +final String password = password_example; // String | None +final String callback = callback_example; // String | None try { - api_instance.testEndpointParameters(number, double_, patternWithoutDelimiter, byte, integer, int32, int64, float, string, binary, date, dateTime, password, callback); -} catch (e) { + api.testEndpointParameters(number, double_, patternWithoutDelimiter, byte, integer, int32, int64, float, string, binary, date, dateTime, password, callback); +} catch on DioError (e) { print('Exception when calling FakeApi->testEndpointParameters: $e\n'); } ``` @@ -535,19 +578,19 @@ To test enum parameters ```dart import 'package:openapi/api.dart'; -var api_instance = new FakeApi(); -var enumHeaderStringArray = []; // BuiltList | Header parameter enum test (string array) -var enumHeaderString = enumHeaderString_example; // String | Header parameter enum test (string) -var enumQueryStringArray = []; // BuiltList | Query parameter enum test (string array) -var enumQueryString = enumQueryString_example; // String | Query parameter enum test (string) -var enumQueryInteger = 56; // int | Query parameter enum test (double) -var enumQueryDouble = 1.2; // double | Query parameter enum test (double) -var enumFormStringArray = [enumFormStringArray_example]; // BuiltList | Form parameter enum test (string array) -var enumFormString = enumFormString_example; // String | Form parameter enum test (string) +final api = Openapi().getFakeApi(); +final BuiltList enumHeaderStringArray = ; // BuiltList | Header parameter enum test (string array) +final String enumHeaderString = enumHeaderString_example; // String | Header parameter enum test (string) +final BuiltList enumQueryStringArray = ; // BuiltList | Query parameter enum test (string array) +final String enumQueryString = enumQueryString_example; // String | Query parameter enum test (string) +final int enumQueryInteger = 56; // int | Query parameter enum test (double) +final double enumQueryDouble = 1.2; // double | Query parameter enum test (double) +final BuiltList enumFormStringArray = enumFormStringArray_example; // BuiltList | Form parameter enum test (string array) +final String enumFormString = enumFormString_example; // String | Form parameter enum test (string) try { - api_instance.testEnumParameters(enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble, enumFormStringArray, enumFormString); -} catch (e) { + api.testEnumParameters(enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble, enumFormStringArray, enumFormString); +} catch on DioError (e) { print('Exception when calling FakeApi->testEnumParameters: $e\n'); } ``` @@ -556,13 +599,13 @@ try { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **enumHeaderStringArray** | [**BuiltList**](String.md)| Header parameter enum test (string array) | [optional] + **enumHeaderStringArray** | [**BuiltList<String>**](String.md)| Header parameter enum test (string array) | [optional] **enumHeaderString** | **String**| Header parameter enum test (string) | [optional] [default to '-efg'] - **enumQueryStringArray** | [**BuiltList**](String.md)| Query parameter enum test (string array) | [optional] + **enumQueryStringArray** | [**BuiltList<String>**](String.md)| Query parameter enum test (string array) | [optional] **enumQueryString** | **String**| Query parameter enum test (string) | [optional] [default to '-efg'] **enumQueryInteger** | **int**| Query parameter enum test (double) | [optional] **enumQueryDouble** | **double**| Query parameter enum test (double) | [optional] - **enumFormStringArray** | [**BuiltList**](String.md)| Form parameter enum test (string array) | [optional] [default to '$'] + **enumFormStringArray** | [**BuiltList<String>**](String.md)| Form parameter enum test (string array) | [optional] [default to '$'] **enumFormString** | **String**| Form parameter enum test (string) | [optional] [default to '-efg'] ### Return type @@ -594,17 +637,17 @@ import 'package:openapi/api.dart'; //defaultApiClient.getAuthentication('bearer_test').username = 'YOUR_USERNAME' //defaultApiClient.getAuthentication('bearer_test').password = 'YOUR_PASSWORD'; -var api_instance = new FakeApi(); -var requiredStringGroup = 56; // int | Required String in group parameters -var requiredBooleanGroup = true; // bool | Required Boolean in group parameters -var requiredInt64Group = 789; // int | Required Integer in group parameters -var stringGroup = 56; // int | String in group parameters -var booleanGroup = true; // bool | Boolean in group parameters -var int64Group = 789; // int | Integer in group parameters +final api = Openapi().getFakeApi(); +final int requiredStringGroup = 56; // int | Required String in group parameters +final bool requiredBooleanGroup = true; // bool | Required Boolean in group parameters +final int requiredInt64Group = 789; // int | Required Integer in group parameters +final int stringGroup = 56; // int | String in group parameters +final bool booleanGroup = true; // bool | Boolean in group parameters +final int int64Group = 789; // int | Integer in group parameters try { - api_instance.testGroupParameters(requiredStringGroup, requiredBooleanGroup, requiredInt64Group, stringGroup, booleanGroup, int64Group); -} catch (e) { + api.testGroupParameters(requiredStringGroup, requiredBooleanGroup, requiredInt64Group, stringGroup, booleanGroup, int64Group); +} catch on DioError (e) { print('Exception when calling FakeApi->testGroupParameters: $e\n'); } ``` @@ -644,12 +687,12 @@ test inline additionalProperties ```dart import 'package:openapi/api.dart'; -var api_instance = new FakeApi(); -var requestBody = new BuiltMap(); // BuiltMap | request body +final api = Openapi().getFakeApi(); +final BuiltMap requestBody = ; // BuiltMap | request body try { - api_instance.testInlineAdditionalProperties(requestBody); -} catch (e) { + api.testInlineAdditionalProperties(requestBody); +} catch on DioError (e) { print('Exception when calling FakeApi->testInlineAdditionalProperties: $e\n'); } ``` @@ -658,7 +701,7 @@ try { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **requestBody** | [**BuiltMap**](String.md)| request body | + **requestBody** | [**BuiltMap<String, String>**](String.md)| request body | ### Return type @@ -684,13 +727,13 @@ test json serialization of form data ```dart import 'package:openapi/api.dart'; -var api_instance = new FakeApi(); -var param = param_example; // String | field1 -var param2 = param2_example; // String | field2 +final api = Openapi().getFakeApi(); +final String param = param_example; // String | field1 +final String param2 = param2_example; // String | field2 try { - api_instance.testJsonFormData(param, param2); -} catch (e) { + api.testJsonFormData(param, param2); +} catch on DioError (e) { print('Exception when calling FakeApi->testJsonFormData: $e\n'); } ``` @@ -728,16 +771,16 @@ To test the collection format in query parameters ```dart import 'package:openapi/api.dart'; -var api_instance = new FakeApi(); -var pipe = []; // BuiltList | -var ioutil = []; // BuiltList | -var http = []; // BuiltList | -var url = []; // BuiltList | -var context = []; // BuiltList | +final api = Openapi().getFakeApi(); +final BuiltList pipe = ; // BuiltList | +final BuiltList ioutil = ; // BuiltList | +final BuiltList http = ; // BuiltList | +final BuiltList url = ; // BuiltList | +final BuiltList context = ; // BuiltList | try { - api_instance.testQueryParameterCollectionFormat(pipe, ioutil, http, url, context); -} catch (e) { + api.testQueryParameterCollectionFormat(pipe, ioutil, http, url, context); +} catch on DioError (e) { print('Exception when calling FakeApi->testQueryParameterCollectionFormat: $e\n'); } ``` @@ -746,11 +789,11 @@ try { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **pipe** | [**BuiltList**](String.md)| | - **ioutil** | [**BuiltList**](String.md)| | - **http** | [**BuiltList**](String.md)| | - **url** | [**BuiltList**](String.md)| | - **context** | [**BuiltList**](String.md)| | + **pipe** | [**BuiltList<String>**](String.md)| | + **ioutil** | [**BuiltList<String>**](String.md)| | + **http** | [**BuiltList<String>**](String.md)| | + **url** | [**BuiltList<String>**](String.md)| | + **context** | [**BuiltList<String>**](String.md)| | ### Return type diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/doc/FakeClassnameTags123Api.md b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/doc/FakeClassnameTags123Api.md index 9745ca8e3ff..cabd6fe0a99 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/doc/FakeClassnameTags123Api.md +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/doc/FakeClassnameTags123Api.md @@ -9,7 +9,7 @@ All URIs are relative to *http://petstore.swagger.io:80/v2* Method | HTTP request | Description ------------- | ------------- | ------------- -[**testClassname**](FakeClassnameTags123Api.md#testclassname) | **patch** /fake_classname_test | To test class name in snake case +[**testClassname**](FakeClassnameTags123Api.md#testclassname) | **PATCH** /fake_classname_test | To test class name in snake case # **testClassname** @@ -27,13 +27,13 @@ import 'package:openapi/api.dart'; // uncomment below to setup prefix (e.g. Bearer) for API key, if needed //defaultApiClient.getAuthentication('api_key_query').apiKeyPrefix = 'Bearer'; -var api_instance = new FakeClassnameTags123Api(); -var modelClient = new ModelClient(); // ModelClient | client model +final api = Openapi().getFakeClassnameTags123Api(); +final ModelClient modelClient = ; // ModelClient | client model try { - var result = api_instance.testClassname(modelClient); - print(result); -} catch (e) { + final response = api.testClassname(modelClient); + print(response); +} catch on DioError (e) { print('Exception when calling FakeClassnameTags123Api->testClassname: $e\n'); } ``` diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/doc/FileSchemaTestClass.md b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/doc/FileSchemaTestClass.md index 9b7eebcb2bf..105fece87f1 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/doc/FileSchemaTestClass.md +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/doc/FileSchemaTestClass.md @@ -9,7 +9,7 @@ import 'package:openapi/api.dart'; Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **file** | [**ModelFile**](ModelFile.md) | | [optional] -**files** | [**BuiltList**](ModelFile.md) | | [optional] +**files** | [**BuiltList<ModelFile>**](ModelFile.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/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/doc/MapTest.md b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/doc/MapTest.md index 2da739ba8b8..4ad87df6423 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/doc/MapTest.md +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/doc/MapTest.md @@ -8,10 +8,10 @@ import 'package:openapi/api.dart'; ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**mapMapOfString** | [**BuiltMap>**](BuiltMap.md) | | [optional] -**mapOfEnumString** | **BuiltMap** | | [optional] -**directMap** | **BuiltMap** | | [optional] -**indirectMap** | **BuiltMap** | | [optional] +**mapMapOfString** | [**BuiltMap<String, BuiltMap<String, String>>**](BuiltMap.md) | | [optional] +**mapOfEnumString** | **BuiltMap<String, String>** | | [optional] +**directMap** | **BuiltMap<String, bool>** | | [optional] +**indirectMap** | **BuiltMap<String, bool>** | | [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-next/petstore_client_lib_fake/doc/MixedPropertiesAndAdditionalPropertiesClass.md b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/doc/MixedPropertiesAndAdditionalPropertiesClass.md index f50d9768751..b1a4c4ccc40 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/doc/MixedPropertiesAndAdditionalPropertiesClass.md +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/doc/MixedPropertiesAndAdditionalPropertiesClass.md @@ -10,7 +10,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **uuid** | **String** | | [optional] **dateTime** | [**DateTime**](DateTime.md) | | [optional] -**map** | [**BuiltMap**](Animal.md) | | [optional] +**map** | [**BuiltMap<String, Animal>**](Animal.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/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/doc/NullableClass.md b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/doc/NullableClass.md index 0241e3eb15e..4ce8d5e1757 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/doc/NullableClass.md +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/doc/NullableClass.md @@ -14,12 +14,12 @@ Name | Type | Description | Notes **stringProp** | **String** | | [optional] **dateProp** | [**Date**](Date.md) | | [optional] **datetimeProp** | [**DateTime**](DateTime.md) | | [optional] -**arrayNullableProp** | [**BuiltList**](JsonObject.md) | | [optional] -**arrayAndItemsNullableProp** | [**BuiltList**](JsonObject.md) | | [optional] -**arrayItemsNullable** | [**BuiltList**](JsonObject.md) | | [optional] -**objectNullableProp** | [**BuiltMap**](JsonObject.md) | | [optional] -**objectAndItemsNullableProp** | [**BuiltMap**](JsonObject.md) | | [optional] -**objectItemsNullable** | [**BuiltMap**](JsonObject.md) | | [optional] +**arrayNullableProp** | [**BuiltList<JsonObject>**](JsonObject.md) | | [optional] +**arrayAndItemsNullableProp** | [**BuiltList<JsonObject>**](JsonObject.md) | | [optional] +**arrayItemsNullable** | [**BuiltList<JsonObject>**](JsonObject.md) | | [optional] +**objectNullableProp** | [**BuiltMap<String, JsonObject>**](JsonObject.md) | | [optional] +**objectAndItemsNullableProp** | [**BuiltMap<String, JsonObject>**](JsonObject.md) | | [optional] +**objectItemsNullable** | [**BuiltMap<String, JsonObject>**](JsonObject.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/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/doc/Pet.md b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/doc/Pet.md index 3640640df19..08e0aeedd78 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/doc/Pet.md +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/doc/Pet.md @@ -11,8 +11,8 @@ Name | Type | Description | Notes **id** | **int** | | [optional] **category** | [**Category**](Category.md) | | [optional] **name** | **String** | | -**photoUrls** | **BuiltSet** | | -**tags** | [**BuiltList**](Tag.md) | | [optional] +**photoUrls** | **BuiltSet<String>** | | +**tags** | [**BuiltList<Tag>**](Tag.md) | | [optional] **status** | **String** | pet status in the store | [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-next/petstore_client_lib_fake/doc/PetApi.md b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/doc/PetApi.md index d5a07d5046e..70f5342d771 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/doc/PetApi.md +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/doc/PetApi.md @@ -9,15 +9,15 @@ All URIs are relative to *http://petstore.swagger.io:80/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 -[**uploadFileWithRequiredFile**](PetApi.md#uploadfilewithrequiredfile) | **post** /fake/{petId}/uploadImageWithRequiredFile | uploads an image (required) +[**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 +[**uploadFileWithRequiredFile**](PetApi.md#uploadfilewithrequiredfile) | **POST** /fake/{petId}/uploadImageWithRequiredFile | uploads an image (required) # **addPet** @@ -31,12 +31,12 @@ import 'package:openapi/api.dart'; // TODO Configure OAuth2 access token for authorization: petstore_auth //defaultApiClient.getAuthentication('petstore_auth').accessToken = 'YOUR_ACCESS_TOKEN'; -var api_instance = new PetApi(); -var pet = new Pet(); // Pet | Pet object that needs to be added to the store +final api = Openapi().getPetApi(); +final Pet pet = ; // Pet | Pet object that needs to be added to the store try { - api_instance.addPet(pet); -} catch (e) { + api.addPet(pet); +} catch on DioError (e) { print('Exception when calling PetApi->addPet: $e\n'); } ``` @@ -73,13 +73,13 @@ import 'package:openapi/api.dart'; // TODO Configure OAuth2 access token for authorization: petstore_auth //defaultApiClient.getAuthentication('petstore_auth').accessToken = 'YOUR_ACCESS_TOKEN'; -var api_instance = new PetApi(); -var petId = 789; // int | Pet id to delete -var apiKey = apiKey_example; // String | +final api = Openapi().getPetApi(); +final int petId = 789; // int | Pet id to delete +final String apiKey = apiKey_example; // String | try { - api_instance.deletePet(petId, apiKey); -} catch (e) { + api.deletePet(petId, apiKey); +} catch on DioError (e) { print('Exception when calling PetApi->deletePet: $e\n'); } ``` @@ -119,13 +119,13 @@ import 'package:openapi/api.dart'; // TODO Configure OAuth2 access token for authorization: petstore_auth //defaultApiClient.getAuthentication('petstore_auth').accessToken = 'YOUR_ACCESS_TOKEN'; -var api_instance = new PetApi(); -var status = []; // BuiltList | Status values that need to be considered for filter +final api = Openapi().getPetApi(); +final BuiltList status = ; // BuiltList | Status values that need to be considered for filter try { - var result = api_instance.findPetsByStatus(status); - print(result); -} catch (e) { + final response = api.findPetsByStatus(status); + print(response); +} catch on DioError (e) { print('Exception when calling PetApi->findPetsByStatus: $e\n'); } ``` @@ -134,11 +134,11 @@ try { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **status** | [**BuiltList**](String.md)| Status values that need to be considered for filter | + **status** | [**BuiltList<String>**](String.md)| Status values that need to be considered for filter | ### Return type -[**BuiltList**](Pet.md) +[**BuiltList<Pet>**](Pet.md) ### Authorization @@ -164,13 +164,13 @@ import 'package:openapi/api.dart'; // TODO Configure OAuth2 access token for authorization: petstore_auth //defaultApiClient.getAuthentication('petstore_auth').accessToken = 'YOUR_ACCESS_TOKEN'; -var api_instance = new PetApi(); -var tags = []; // BuiltSet | Tags to filter by +final api = Openapi().getPetApi(); +final BuiltSet tags = ; // BuiltSet | Tags to filter by try { - var result = api_instance.findPetsByTags(tags); - print(result); -} catch (e) { + final response = api.findPetsByTags(tags); + print(response); +} catch on DioError (e) { print('Exception when calling PetApi->findPetsByTags: $e\n'); } ``` @@ -179,11 +179,11 @@ try { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **tags** | [**BuiltSet**](String.md)| Tags to filter by | + **tags** | [**BuiltSet<String>**](String.md)| Tags to filter by | ### Return type -[**BuiltSet**](Pet.md) +[**BuiltSet<Pet>**](Pet.md) ### Authorization @@ -211,13 +211,13 @@ import 'package:openapi/api.dart'; // uncomment below to setup prefix (e.g. Bearer) for API key, if needed //defaultApiClient.getAuthentication('api_key').apiKeyPrefix = 'Bearer'; -var api_instance = new PetApi(); -var petId = 789; // int | ID of pet to return +final api = Openapi().getPetApi(); +final int petId = 789; // int | ID of pet to return try { - var result = api_instance.getPetById(petId); - print(result); -} catch (e) { + final response = api.getPetById(petId); + print(response); +} catch on DioError (e) { print('Exception when calling PetApi->getPetById: $e\n'); } ``` @@ -254,12 +254,12 @@ import 'package:openapi/api.dart'; // TODO Configure OAuth2 access token for authorization: petstore_auth //defaultApiClient.getAuthentication('petstore_auth').accessToken = 'YOUR_ACCESS_TOKEN'; -var api_instance = new PetApi(); -var pet = new Pet(); // Pet | Pet object that needs to be added to the store +final api = Openapi().getPetApi(); +final Pet pet = ; // Pet | Pet object that needs to be added to the store try { - api_instance.updatePet(pet); -} catch (e) { + api.updatePet(pet); +} catch on DioError (e) { print('Exception when calling PetApi->updatePet: $e\n'); } ``` @@ -296,14 +296,14 @@ import 'package:openapi/api.dart'; // TODO Configure OAuth2 access token for authorization: petstore_auth //defaultApiClient.getAuthentication('petstore_auth').accessToken = 'YOUR_ACCESS_TOKEN'; -var api_instance = new PetApi(); -var petId = 789; // int | ID of pet that needs to be updated -var name = name_example; // String | Updated name of the pet -var status = status_example; // String | Updated status of the pet +final api = Openapi().getPetApi(); +final int petId = 789; // int | ID of pet that needs to be updated +final String name = name_example; // String | Updated name of the pet +final String status = status_example; // String | Updated status of the pet try { - api_instance.updatePetWithForm(petId, name, status); -} catch (e) { + api.updatePetWithForm(petId, name, status); +} catch on DioError (e) { print('Exception when calling PetApi->updatePetWithForm: $e\n'); } ``` @@ -342,15 +342,15 @@ import 'package:openapi/api.dart'; // TODO Configure OAuth2 access token for authorization: petstore_auth //defaultApiClient.getAuthentication('petstore_auth').accessToken = 'YOUR_ACCESS_TOKEN'; -var api_instance = new PetApi(); -var petId = 789; // int | ID of pet to update -var additionalMetadata = additionalMetadata_example; // String | Additional data to pass to server -var file = BINARY_DATA_HERE; // Uint8List | file to upload +final api = Openapi().getPetApi(); +final int petId = 789; // int | ID of pet to update +final String additionalMetadata = additionalMetadata_example; // String | Additional data to pass to server +final MultipartFile file = BINARY_DATA_HERE; // MultipartFile | file to upload try { - var result = api_instance.uploadFile(petId, additionalMetadata, file); - print(result); -} catch (e) { + final response = api.uploadFile(petId, additionalMetadata, file); + print(response); +} catch on DioError (e) { print('Exception when calling PetApi->uploadFile: $e\n'); } ``` @@ -361,7 +361,7 @@ Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **petId** | **int**| ID of pet to update | **additionalMetadata** | **String**| Additional data to pass to server | [optional] - **file** | **Uint8List**| file to upload | [optional] + **file** | **MultipartFile**| file to upload | [optional] ### Return type @@ -389,15 +389,15 @@ import 'package:openapi/api.dart'; // TODO Configure OAuth2 access token for authorization: petstore_auth //defaultApiClient.getAuthentication('petstore_auth').accessToken = 'YOUR_ACCESS_TOKEN'; -var api_instance = new PetApi(); -var petId = 789; // int | ID of pet to update -var requiredFile = BINARY_DATA_HERE; // Uint8List | file to upload -var additionalMetadata = additionalMetadata_example; // String | Additional data to pass to server +final api = Openapi().getPetApi(); +final int petId = 789; // int | ID of pet to update +final MultipartFile requiredFile = BINARY_DATA_HERE; // MultipartFile | file to upload +final String additionalMetadata = additionalMetadata_example; // String | Additional data to pass to server try { - var result = api_instance.uploadFileWithRequiredFile(petId, requiredFile, additionalMetadata); - print(result); -} catch (e) { + final response = api.uploadFileWithRequiredFile(petId, requiredFile, additionalMetadata); + print(response); +} catch on DioError (e) { print('Exception when calling PetApi->uploadFileWithRequiredFile: $e\n'); } ``` @@ -407,7 +407,7 @@ try { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **petId** | **int**| ID of pet to update | - **requiredFile** | **Uint8List**| file to upload | + **requiredFile** | **MultipartFile**| file to upload | **additionalMetadata** | **String**| Additional data to pass to server | [optional] ### Return type diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/doc/StoreApi.md b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/doc/StoreApi.md index 1fcb8f71eea..e955785ca95 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/doc/StoreApi.md +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/doc/StoreApi.md @@ -9,10 +9,10 @@ All URIs are relative to *http://petstore.swagger.io:80/v2* Method | HTTP request | Description ------------- | ------------- | ------------- -[**deleteOrder**](StoreApi.md#deleteorder) | **delete** /store/order/{order_id} | Delete purchase order by ID -[**getInventory**](StoreApi.md#getinventory) | **get** /store/inventory | Returns pet inventories by status -[**getOrderById**](StoreApi.md#getorderbyid) | **get** /store/order/{order_id} | Find purchase order by ID -[**placeOrder**](StoreApi.md#placeorder) | **post** /store/order | Place an order for a pet +[**deleteOrder**](StoreApi.md#deleteorder) | **DELETE** /store/order/{order_id} | Delete purchase order by ID +[**getInventory**](StoreApi.md#getinventory) | **GET** /store/inventory | Returns pet inventories by status +[**getOrderById**](StoreApi.md#getorderbyid) | **GET** /store/order/{order_id} | Find purchase order by ID +[**placeOrder**](StoreApi.md#placeorder) | **POST** /store/order | Place an order for a pet # **deleteOrder** @@ -26,12 +26,12 @@ For valid response try integer IDs with value < 1000. Anything above 1000 or non ```dart import 'package:openapi/api.dart'; -var api_instance = new StoreApi(); -var orderId = orderId_example; // String | ID of the order that needs to be deleted +final api = Openapi().getStoreApi(); +final String orderId = orderId_example; // String | ID of the order that needs to be deleted try { - api_instance.deleteOrder(orderId); -} catch (e) { + api.deleteOrder(orderId); +} catch on DioError (e) { print('Exception when calling StoreApi->deleteOrder: $e\n'); } ``` @@ -72,12 +72,12 @@ import 'package:openapi/api.dart'; // uncomment below to setup prefix (e.g. Bearer) for API key, if needed //defaultApiClient.getAuthentication('api_key').apiKeyPrefix = 'Bearer'; -var api_instance = new StoreApi(); +final api = Openapi().getStoreApi(); try { - var result = api_instance.getInventory(); - print(result); -} catch (e) { + final response = api.getInventory(); + print(response); +} catch on DioError (e) { print('Exception when calling StoreApi->getInventory: $e\n'); } ``` @@ -87,7 +87,7 @@ This endpoint does not need any parameter. ### Return type -**BuiltMap** +**BuiltMap<String, int>** ### Authorization @@ -111,13 +111,13 @@ For valid response try integer IDs with value <= 5 or > 10. Other values will ge ```dart import 'package:openapi/api.dart'; -var api_instance = new StoreApi(); -var orderId = 789; // int | ID of pet that needs to be fetched +final api = Openapi().getStoreApi(); +final int orderId = 789; // int | ID of pet that needs to be fetched try { - var result = api_instance.getOrderById(orderId); - print(result); -} catch (e) { + final response = api.getOrderById(orderId); + print(response); +} catch on DioError (e) { print('Exception when calling StoreApi->getOrderById: $e\n'); } ``` @@ -152,13 +152,13 @@ Place an order for a pet ```dart import 'package:openapi/api.dart'; -var api_instance = new StoreApi(); -var order = new Order(); // Order | order placed for purchasing the pet +final api = Openapi().getStoreApi(); +final Order order = ; // Order | order placed for purchasing the pet try { - var result = api_instance.placeOrder(order); - print(result); -} catch (e) { + final response = api.placeOrder(order); + print(response); +} catch on DioError (e) { print('Exception when calling StoreApi->placeOrder: $e\n'); } ``` diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/doc/UserApi.md b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/doc/UserApi.md index 62e01652e80..5e96b548e3b 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/doc/UserApi.md +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/doc/UserApi.md @@ -9,14 +9,14 @@ All URIs are relative to *http://petstore.swagger.io:80/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**](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** @@ -30,12 +30,12 @@ This can only be done by the logged in user. ```dart import 'package:openapi/api.dart'; -var api_instance = new UserApi(); -var user = new User(); // User | Created user object +final api = Openapi().getUserApi(); +final User user = ; // User | Created user object try { - api_instance.createUser(user); -} catch (e) { + api.createUser(user); +} catch on DioError (e) { print('Exception when calling UserApi->createUser: $e\n'); } ``` @@ -70,12 +70,12 @@ Creates list of users with given input array ```dart import 'package:openapi/api.dart'; -var api_instance = new UserApi(); -var user = [new BuiltList()]; // BuiltList | List of user object +final api = Openapi().getUserApi(); +final BuiltList user = ; // BuiltList | List of user object try { - api_instance.createUsersWithArrayInput(user); -} catch (e) { + api.createUsersWithArrayInput(user); +} catch on DioError (e) { print('Exception when calling UserApi->createUsersWithArrayInput: $e\n'); } ``` @@ -84,7 +84,7 @@ try { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **user** | [**BuiltList**](User.md)| List of user object | + **user** | [**BuiltList<User>**](User.md)| List of user object | ### Return type @@ -110,12 +110,12 @@ Creates list of users with given input array ```dart import 'package:openapi/api.dart'; -var api_instance = new UserApi(); -var user = [new BuiltList()]; // BuiltList | List of user object +final api = Openapi().getUserApi(); +final BuiltList user = ; // BuiltList | List of user object try { - api_instance.createUsersWithListInput(user); -} catch (e) { + api.createUsersWithListInput(user); +} catch on DioError (e) { print('Exception when calling UserApi->createUsersWithListInput: $e\n'); } ``` @@ -124,7 +124,7 @@ try { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **user** | [**BuiltList**](User.md)| List of user object | + **user** | [**BuiltList<User>**](User.md)| List of user object | ### Return type @@ -152,12 +152,12 @@ This can only be done by the logged in user. ```dart import 'package:openapi/api.dart'; -var api_instance = new UserApi(); -var username = username_example; // String | The name that needs to be deleted +final api = Openapi().getUserApi(); +final String username = username_example; // String | The name that needs to be deleted try { - api_instance.deleteUser(username); -} catch (e) { + api.deleteUser(username); +} catch on DioError (e) { print('Exception when calling UserApi->deleteUser: $e\n'); } ``` @@ -192,13 +192,13 @@ Get user by user name ```dart import 'package:openapi/api.dart'; -var api_instance = new UserApi(); -var username = username_example; // String | The name that needs to be fetched. Use user1 for testing. +final api = Openapi().getUserApi(); +final String username = username_example; // String | The name that needs to be fetched. Use user1 for testing. try { - var result = api_instance.getUserByName(username); - print(result); -} catch (e) { + final response = api.getUserByName(username); + print(response); +} catch on DioError (e) { print('Exception when calling UserApi->getUserByName: $e\n'); } ``` @@ -233,14 +233,14 @@ Logs user into the system ```dart import 'package:openapi/api.dart'; -var api_instance = new UserApi(); -var username = username_example; // String | The user name for login -var password = password_example; // String | The password for login in clear text +final api = Openapi().getUserApi(); +final String username = username_example; // String | The user name for login +final String password = password_example; // String | The password for login in clear text try { - var result = api_instance.loginUser(username, password); - print(result); -} catch (e) { + final response = api.loginUser(username, password); + print(response); +} catch on DioError (e) { print('Exception when calling UserApi->loginUser: $e\n'); } ``` @@ -276,11 +276,11 @@ Logs out current logged in user session ```dart import 'package:openapi/api.dart'; -var api_instance = new UserApi(); +final api = Openapi().getUserApi(); try { - api_instance.logoutUser(); -} catch (e) { + api.logoutUser(); +} catch on DioError (e) { print('Exception when calling UserApi->logoutUser: $e\n'); } ``` @@ -314,13 +314,13 @@ This can only be done by the logged in user. ```dart import 'package:openapi/api.dart'; -var api_instance = new UserApi(); -var username = username_example; // String | name that need to be deleted -var user = new User(); // User | Updated user object +final api = Openapi().getUserApi(); +final String username = username_example; // String | name that need to be deleted +final User user = ; // User | Updated user object try { - api_instance.updateUser(username, user); -} catch (e) { + api.updateUser(username, user); +} catch on DioError (e) { print('Exception when calling UserApi->updateUser: $e\n'); } ``` diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/api/another_fake_api.dart b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/api/another_fake_api.dart index 00d88a5c178..45709153344 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/api/another_fake_api.dart +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/api/another_fake_api.dart @@ -18,8 +18,19 @@ class AnotherFakeApi { const AnotherFakeApi(this._dio, this._serializers); /// To test special tags - /// /// To test special tags and operation ID starting with number + /// + /// Parameters: + /// * [modelClient] - client model + /// * [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] containing a [Response] with a [ModelClient] as data + /// Throws [DioError] if API call or serialization fails Future> call123testSpecialTags({ required ModelClient modelClient, CancelToken? cancelToken, @@ -39,38 +50,31 @@ class AnotherFakeApi { 'secure': >[], ...?extra, }, - contentType: [ - 'application/json', - ].first, + contentType: 'application/json', validateStatus: validateStatus, ); - final _queryParameters = { - }; - dynamic _bodyData; try { const _type = FullType(ModelClient); _bodyData = _serializers.serialize(modelClient, specifiedType: _type); - } catch(error) { + } catch(error, stackTrace) { throw DioError( requestOptions: _options.compose( _dio.options, _path, - queryParameters: _queryParameters, ), type: DioErrorType.other, error: error, - ); + )..stackTrace = stackTrace; } final _response = await _dio.request( _path, data: _bodyData, options: _options, - queryParameters: _queryParameters, cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, @@ -85,13 +89,13 @@ class AnotherFakeApi { specifiedType: _responseType, ) as ModelClient; - } catch (error) { + } catch (error, stackTrace) { throw DioError( requestOptions: _response.requestOptions, response: _response, type: DioErrorType.other, error: error, - ); + )..stackTrace = stackTrace; } return Response( diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/api/default_api.dart b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/api/default_api.dart index 48fc9b8c444..7ad2d45db75 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/api/default_api.dart +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/api/default_api.dart @@ -17,9 +17,19 @@ class DefaultApi { const DefaultApi(this._dio, this._serializers); + /// fooGet /// /// - /// + /// Parameters: + /// * [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] containing a [Response] with a [InlineResponseDefault] as data + /// Throws [DioError] if API call or serialization fails Future> fooGet({ CancelToken? cancelToken, Map? headers, @@ -38,19 +48,12 @@ class DefaultApi { 'secure': >[], ...?extra, }, - contentType: [ - 'application/json', - ].first, validateStatus: validateStatus, ); - final _queryParameters = { - }; - final _response = await _dio.request( _path, options: _options, - queryParameters: _queryParameters, cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, @@ -65,13 +68,13 @@ class DefaultApi { specifiedType: _responseType, ) as InlineResponseDefault; - } catch (error) { + } catch (error, stackTrace) { throw DioError( requestOptions: _response.requestOptions, response: _response, type: DioErrorType.other, error: error, - ); + )..stackTrace = stackTrace; } return Response( diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/api/fake_api.dart b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/api/fake_api.dart index fed890a78c1..fbc60334177 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/api/fake_api.dart +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/api/fake_api.dart @@ -28,8 +28,18 @@ class FakeApi { const FakeApi(this._dio, this._serializers); /// Health check endpoint - /// /// + /// + /// Parameters: + /// * [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] containing a [Response] with a [HealthCheckResult] as data + /// Throws [DioError] if API call or serialization fails Future> fakeHealthGet({ CancelToken? cancelToken, Map? headers, @@ -48,19 +58,12 @@ class FakeApi { 'secure': >[], ...?extra, }, - contentType: [ - 'application/json', - ].first, validateStatus: validateStatus, ); - final _queryParameters = { - }; - final _response = await _dio.request( _path, options: _options, - queryParameters: _queryParameters, cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, @@ -75,13 +78,13 @@ class FakeApi { specifiedType: _responseType, ) as HealthCheckResult; - } catch (error) { + } catch (error, stackTrace) { throw DioError( requestOptions: _response.requestOptions, response: _response, type: DioErrorType.other, error: error, - ); + )..stackTrace = stackTrace; } return Response( @@ -97,8 +100,21 @@ class FakeApi { } /// test http signature authentication - /// /// + /// + /// Parameters: + /// * [pet] - Pet object that needs to be added to the store + /// * [query1] - query parameter + /// * [header1] - header parameter + /// * [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 [DioError] if API call or serialization fails Future> fakeHttpSignatureTest({ required Pet pet, String? query1, @@ -126,15 +142,12 @@ class FakeApi { ], ...?extra, }, - contentType: [ - 'application/json', - 'application/xml', - ].first, + contentType: 'application/json', validateStatus: validateStatus, ); final _queryParameters = { - if (query1 != null) r'query_1': query1, + if (query1 != null) r'query_1': encodeQueryParameter(_serializers, query1, const FullType(String)), }; dynamic _bodyData; @@ -143,7 +156,7 @@ class FakeApi { const _type = FullType(Pet); _bodyData = _serializers.serialize(pet, specifiedType: _type); - } catch(error) { + } catch(error, stackTrace) { throw DioError( requestOptions: _options.compose( _dio.options, @@ -152,7 +165,7 @@ class FakeApi { ), type: DioErrorType.other, error: error, - ); + )..stackTrace = stackTrace; } final _response = await _dio.request( @@ -168,9 +181,20 @@ class FakeApi { return _response; } - /// - /// + /// fakeOuterBooleanSerialize /// Test serialization of outer boolean types + /// + /// Parameters: + /// * [body] - Input boolean as post 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] containing a [Response] with a [bool] as data + /// Throws [DioError] if API call or serialization fails Future> fakeOuterBooleanSerialize({ bool? body, CancelToken? cancelToken, @@ -190,37 +214,30 @@ class FakeApi { 'secure': >[], ...?extra, }, - contentType: [ - 'application/json', - ].first, + contentType: 'application/json', validateStatus: validateStatus, ); - final _queryParameters = { - }; - dynamic _bodyData; try { _bodyData = body; - } catch(error) { + } catch(error, stackTrace) { throw DioError( requestOptions: _options.compose( _dio.options, _path, - queryParameters: _queryParameters, ), type: DioErrorType.other, error: error, - ); + )..stackTrace = stackTrace; } final _response = await _dio.request( _path, data: _bodyData, options: _options, - queryParameters: _queryParameters, cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, @@ -231,13 +248,13 @@ class FakeApi { try { _responseData = _response.data as bool; - } catch (error) { + } catch (error, stackTrace) { throw DioError( requestOptions: _response.requestOptions, response: _response, type: DioErrorType.other, error: error, - ); + )..stackTrace = stackTrace; } return Response( @@ -252,9 +269,20 @@ class FakeApi { ); } - /// - /// + /// fakeOuterCompositeSerialize /// Test serialization of object with outer number type + /// + /// Parameters: + /// * [outerComposite] - Input composite as post 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] containing a [Response] with a [OuterComposite] as data + /// Throws [DioError] if API call or serialization fails Future> fakeOuterCompositeSerialize({ OuterComposite? outerComposite, CancelToken? cancelToken, @@ -274,38 +302,31 @@ class FakeApi { 'secure': >[], ...?extra, }, - contentType: [ - 'application/json', - ].first, + contentType: 'application/json', validateStatus: validateStatus, ); - final _queryParameters = { - }; - dynamic _bodyData; try { const _type = FullType(OuterComposite); _bodyData = outerComposite == null ? null : _serializers.serialize(outerComposite, specifiedType: _type); - } catch(error) { + } catch(error, stackTrace) { throw DioError( requestOptions: _options.compose( _dio.options, _path, - queryParameters: _queryParameters, ), type: DioErrorType.other, error: error, - ); + )..stackTrace = stackTrace; } final _response = await _dio.request( _path, data: _bodyData, options: _options, - queryParameters: _queryParameters, cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, @@ -320,13 +341,13 @@ class FakeApi { specifiedType: _responseType, ) as OuterComposite; - } catch (error) { + } catch (error, stackTrace) { throw DioError( requestOptions: _response.requestOptions, response: _response, type: DioErrorType.other, error: error, - ); + )..stackTrace = stackTrace; } return Response( @@ -341,9 +362,20 @@ class FakeApi { ); } - /// - /// + /// fakeOuterNumberSerialize /// Test serialization of outer number types + /// + /// Parameters: + /// * [body] - Input number as post 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] containing a [Response] with a [num] as data + /// Throws [DioError] if API call or serialization fails Future> fakeOuterNumberSerialize({ num? body, CancelToken? cancelToken, @@ -363,37 +395,30 @@ class FakeApi { 'secure': >[], ...?extra, }, - contentType: [ - 'application/json', - ].first, + contentType: 'application/json', validateStatus: validateStatus, ); - final _queryParameters = { - }; - dynamic _bodyData; try { _bodyData = body; - } catch(error) { + } catch(error, stackTrace) { throw DioError( requestOptions: _options.compose( _dio.options, _path, - queryParameters: _queryParameters, ), type: DioErrorType.other, error: error, - ); + )..stackTrace = stackTrace; } final _response = await _dio.request( _path, data: _bodyData, options: _options, - queryParameters: _queryParameters, cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, @@ -404,13 +429,13 @@ class FakeApi { try { _responseData = _response.data as num; - } catch (error) { + } catch (error, stackTrace) { throw DioError( requestOptions: _response.requestOptions, response: _response, type: DioErrorType.other, error: error, - ); + )..stackTrace = stackTrace; } return Response( @@ -425,9 +450,20 @@ class FakeApi { ); } - /// - /// + /// fakeOuterStringSerialize /// Test serialization of outer string types + /// + /// Parameters: + /// * [body] - Input string as post 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] containing a [Response] with a [String] as data + /// Throws [DioError] if API call or serialization fails Future> fakeOuterStringSerialize({ String? body, CancelToken? cancelToken, @@ -447,37 +483,30 @@ class FakeApi { 'secure': >[], ...?extra, }, - contentType: [ - 'application/json', - ].first, + contentType: 'application/json', validateStatus: validateStatus, ); - final _queryParameters = { - }; - dynamic _bodyData; try { _bodyData = body; - } catch(error) { + } catch(error, stackTrace) { throw DioError( requestOptions: _options.compose( _dio.options, _path, - queryParameters: _queryParameters, ), type: DioErrorType.other, error: error, - ); + )..stackTrace = stackTrace; } final _response = await _dio.request( _path, data: _bodyData, options: _options, - queryParameters: _queryParameters, cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, @@ -488,13 +517,13 @@ class FakeApi { try { _responseData = _response.data as String; - } catch (error) { + } catch (error, stackTrace) { throw DioError( requestOptions: _response.requestOptions, response: _response, type: DioErrorType.other, error: error, - ); + )..stackTrace = stackTrace; } return Response( @@ -509,9 +538,20 @@ class FakeApi { ); } - /// - /// + /// fakePropertyEnumIntegerSerialize /// Test serialization of enum (int) properties with examples + /// + /// Parameters: + /// * [outerObjectWithEnumProperty] - Input enum (int) as post 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] containing a [Response] with a [OuterObjectWithEnumProperty] as data + /// Throws [DioError] if API call or serialization fails Future> fakePropertyEnumIntegerSerialize({ required OuterObjectWithEnumProperty outerObjectWithEnumProperty, CancelToken? cancelToken, @@ -531,38 +571,31 @@ class FakeApi { 'secure': >[], ...?extra, }, - contentType: [ - 'application/json', - ].first, + contentType: 'application/json', validateStatus: validateStatus, ); - final _queryParameters = { - }; - dynamic _bodyData; try { const _type = FullType(OuterObjectWithEnumProperty); _bodyData = _serializers.serialize(outerObjectWithEnumProperty, specifiedType: _type); - } catch(error) { + } catch(error, stackTrace) { throw DioError( requestOptions: _options.compose( _dio.options, _path, - queryParameters: _queryParameters, ), type: DioErrorType.other, error: error, - ); + )..stackTrace = stackTrace; } final _response = await _dio.request( _path, data: _bodyData, options: _options, - queryParameters: _queryParameters, cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, @@ -577,13 +610,13 @@ class FakeApi { specifiedType: _responseType, ) as OuterObjectWithEnumProperty; - } catch (error) { + } catch (error, stackTrace) { throw DioError( requestOptions: _response.requestOptions, response: _response, type: DioErrorType.other, error: error, - ); + )..stackTrace = stackTrace; } return Response( @@ -598,9 +631,85 @@ class FakeApi { ); } - /// + /// testBodyWithBinary + /// For this test, the body has to be a binary file. /// - /// For this test, the body for this request much reference a schema named `File`. + /// Parameters: + /// * [body] - image to upload + /// * [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 [DioError] if API call or serialization fails + Future> testBodyWithBinary({ + required MultipartFile body, + CancelToken? cancelToken, + Map? headers, + Map? extra, + ValidateStatus? validateStatus, + ProgressCallback? onSendProgress, + ProgressCallback? onReceiveProgress, + }) async { + final _path = r'/fake/body-with-binary'; + final _options = Options( + method: r'PUT', + headers: { + ...?headers, + }, + extra: { + 'secure': >[], + ...?extra, + }, + contentType: 'image/png', + validateStatus: validateStatus, + ); + + dynamic _bodyData; + + try { + _bodyData = body.finalize(); + + } catch(error, stackTrace) { + throw DioError( + requestOptions: _options.compose( + _dio.options, + _path, + ), + type: DioErrorType.other, + error: error, + )..stackTrace = stackTrace; + } + + final _response = await _dio.request( + _path, + data: _bodyData, + options: _options, + cancelToken: cancelToken, + onSendProgress: onSendProgress, + onReceiveProgress: onReceiveProgress, + ); + + return _response; + } + + /// testBodyWithFileSchema + /// For this test, the body for this request must reference a schema named `File`. + /// + /// Parameters: + /// * [fileSchemaTestClass] + /// * [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 [DioError] if API call or serialization fails Future> testBodyWithFileSchema({ required FileSchemaTestClass fileSchemaTestClass, CancelToken? cancelToken, @@ -620,38 +729,31 @@ class FakeApi { 'secure': >[], ...?extra, }, - contentType: [ - 'application/json', - ].first, + contentType: 'application/json', validateStatus: validateStatus, ); - final _queryParameters = { - }; - dynamic _bodyData; try { const _type = FullType(FileSchemaTestClass); _bodyData = _serializers.serialize(fileSchemaTestClass, specifiedType: _type); - } catch(error) { + } catch(error, stackTrace) { throw DioError( requestOptions: _options.compose( _dio.options, _path, - queryParameters: _queryParameters, ), type: DioErrorType.other, error: error, - ); + )..stackTrace = stackTrace; } final _response = await _dio.request( _path, data: _bodyData, options: _options, - queryParameters: _queryParameters, cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, @@ -660,9 +762,21 @@ class FakeApi { return _response; } + /// testBodyWithQueryParams /// /// - /// + /// Parameters: + /// * [query] + /// * [user] + /// * [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 [DioError] if API call or serialization fails Future> testBodyWithQueryParams({ required String query, required User user, @@ -683,14 +797,12 @@ class FakeApi { 'secure': >[], ...?extra, }, - contentType: [ - 'application/json', - ].first, + contentType: 'application/json', validateStatus: validateStatus, ); final _queryParameters = { - r'query': query, + r'query': encodeQueryParameter(_serializers, query, const FullType(String)), }; dynamic _bodyData; @@ -699,7 +811,7 @@ class FakeApi { const _type = FullType(User); _bodyData = _serializers.serialize(user, specifiedType: _type); - } catch(error) { + } catch(error, stackTrace) { throw DioError( requestOptions: _options.compose( _dio.options, @@ -708,7 +820,7 @@ class FakeApi { ), type: DioErrorType.other, error: error, - ); + )..stackTrace = stackTrace; } final _response = await _dio.request( @@ -724,9 +836,20 @@ class FakeApi { return _response; } - /// To test \"client\" model + /// To test \"client\" model + /// To test \"client\" model /// - /// To test \"client\" model + /// Parameters: + /// * [modelClient] - client model + /// * [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] containing a [Response] with a [ModelClient] as data + /// Throws [DioError] if API call or serialization fails Future> testClientModel({ required ModelClient modelClient, CancelToken? cancelToken, @@ -746,38 +869,31 @@ class FakeApi { 'secure': >[], ...?extra, }, - contentType: [ - 'application/json', - ].first, + contentType: 'application/json', validateStatus: validateStatus, ); - final _queryParameters = { - }; - dynamic _bodyData; try { const _type = FullType(ModelClient); _bodyData = _serializers.serialize(modelClient, specifiedType: _type); - } catch(error) { + } catch(error, stackTrace) { throw DioError( requestOptions: _options.compose( _dio.options, _path, - queryParameters: _queryParameters, ), type: DioErrorType.other, error: error, - ); + )..stackTrace = stackTrace; } final _response = await _dio.request( _path, data: _bodyData, options: _options, - queryParameters: _queryParameters, cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, @@ -792,13 +908,13 @@ class FakeApi { specifiedType: _responseType, ) as ModelClient; - } catch (error) { + } catch (error, stackTrace) { throw DioError( requestOptions: _response.requestOptions, response: _response, type: DioErrorType.other, error: error, - ); + )..stackTrace = stackTrace; } return Response( @@ -814,8 +930,32 @@ class FakeApi { } /// Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - /// /// Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + /// + /// Parameters: + /// * [number] - None + /// * [double_] - None + /// * [patternWithoutDelimiter] - None + /// * [byte] - None + /// * [integer] - None + /// * [int32] - None + /// * [int64] - None + /// * [float] - None + /// * [string] - None + /// * [binary] - None + /// * [date] - None + /// * [dateTime] - None + /// * [password] - None + /// * [callback] - None + /// * [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 [DioError] if API call or serialization fails Future> testEndpointParameters({ required num number, required double double_, @@ -853,52 +993,45 @@ class FakeApi { ], ...?extra, }, - contentType: [ - 'application/x-www-form-urlencoded', - ].first, + contentType: 'application/x-www-form-urlencoded', validateStatus: validateStatus, ); - final _queryParameters = { - }; - dynamic _bodyData; try { _bodyData = { - if (integer != null) r'integer': encodeFormParameter(_serializers, integer, const FullType(int)), - if (int32 != null) r'int32': encodeFormParameter(_serializers, int32, const FullType(int)), - if (int64 != null) r'int64': encodeFormParameter(_serializers, int64, const FullType(int)), - r'number': encodeFormParameter(_serializers, number, const FullType(num)), - if (float != null) r'float': encodeFormParameter(_serializers, float, const FullType(double)), - r'double': encodeFormParameter(_serializers, double_, const FullType(double)), - if (string != null) r'string': encodeFormParameter(_serializers, string, const FullType(String)), - r'pattern_without_delimiter': encodeFormParameter(_serializers, patternWithoutDelimiter, const FullType(String)), - r'byte': encodeFormParameter(_serializers, byte, const FullType(String)), - if (binary != null) r'binary': MultipartFile.fromBytes(binary, filename: r'binary'), - if (date != null) r'date': encodeFormParameter(_serializers, date, const FullType(Date)), - if (dateTime != null) r'dateTime': encodeFormParameter(_serializers, dateTime, const FullType(DateTime)), - if (password != null) r'password': encodeFormParameter(_serializers, password, const FullType(String)), - if (callback != null) r'callback': encodeFormParameter(_serializers, callback, const FullType(String)), + if (integer != null) r'integer': encodeQueryParameter(_serializers, integer, const FullType(int)), + if (int32 != null) r'int32': encodeQueryParameter(_serializers, int32, const FullType(int)), + if (int64 != null) r'int64': encodeQueryParameter(_serializers, int64, const FullType(int)), + r'number': encodeQueryParameter(_serializers, number, const FullType(num)), + if (float != null) r'float': encodeQueryParameter(_serializers, float, const FullType(double)), + r'double': encodeQueryParameter(_serializers, double_, const FullType(double)), + if (string != null) r'string': encodeQueryParameter(_serializers, string, const FullType(String)), + r'pattern_without_delimiter': encodeQueryParameter(_serializers, patternWithoutDelimiter, const FullType(String)), + r'byte': encodeQueryParameter(_serializers, byte, const FullType(String)), + if (binary != null) r'binary': encodeQueryParameter(_serializers, binary, const FullType(Uint8List)), + if (date != null) r'date': encodeQueryParameter(_serializers, date, const FullType(Date)), + if (dateTime != null) r'dateTime': encodeQueryParameter(_serializers, dateTime, const FullType(DateTime)), + if (password != null) r'password': encodeQueryParameter(_serializers, password, const FullType(String)), + if (callback != null) r'callback': encodeQueryParameter(_serializers, callback, const FullType(String)), }; - } catch(error) { + } catch(error, stackTrace) { throw DioError( requestOptions: _options.compose( _dio.options, _path, - queryParameters: _queryParameters, ), type: DioErrorType.other, error: error, - ); + )..stackTrace = stackTrace; } final _response = await _dio.request( _path, data: _bodyData, options: _options, - queryParameters: _queryParameters, cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, @@ -908,8 +1041,26 @@ class FakeApi { } /// To test enum parameters - /// /// To test enum parameters + /// + /// Parameters: + /// * [enumHeaderStringArray] - Header parameter enum test (string array) + /// * [enumHeaderString] - Header parameter enum test (string) + /// * [enumQueryStringArray] - Query parameter enum test (string array) + /// * [enumQueryString] - Query parameter enum test (string) + /// * [enumQueryInteger] - Query parameter enum test (double) + /// * [enumQueryDouble] - Query parameter enum test (double) + /// * [enumFormStringArray] - Form parameter enum test (string array) + /// * [enumFormString] - Form parameter enum test (string) + /// * [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 [DioError] if API call or serialization fails Future> testEnumParameters({ BuiltList? enumHeaderStringArray, String? enumHeaderString, @@ -938,28 +1089,26 @@ class FakeApi { 'secure': >[], ...?extra, }, - contentType: [ - 'application/x-www-form-urlencoded', - ].first, + contentType: 'application/x-www-form-urlencoded', validateStatus: validateStatus, ); final _queryParameters = { - if (enumQueryStringArray != null) r'enum_query_string_array': enumQueryStringArray, - if (enumQueryString != null) r'enum_query_string': enumQueryString, - if (enumQueryInteger != null) r'enum_query_integer': enumQueryInteger, - if (enumQueryDouble != null) r'enum_query_double': enumQueryDouble, + if (enumQueryStringArray != null) r'enum_query_string_array': encodeCollectionQueryParameter(_serializers, enumQueryStringArray, const FullType(BuiltList, [FullType(String)]), format: ListFormat.multi), + if (enumQueryString != null) r'enum_query_string': encodeQueryParameter(_serializers, enumQueryString, const FullType(String)), + if (enumQueryInteger != null) r'enum_query_integer': encodeQueryParameter(_serializers, enumQueryInteger, const FullType(int)), + if (enumQueryDouble != null) r'enum_query_double': encodeQueryParameter(_serializers, enumQueryDouble, const FullType(double)), }; dynamic _bodyData; try { _bodyData = { - if (enumFormStringArray != null) r'enum_form_string_array': encodeFormParameter(_serializers, enumFormStringArray, const FullType(BuiltList, [FullType(String)])), - if (enumFormString != null) r'enum_form_string': encodeFormParameter(_serializers, enumFormString, const FullType(String)), + if (enumFormStringArray != null) r'enum_form_string_array': encodeCollectionQueryParameter(_serializers, enumFormStringArray, const FullType(BuiltList, [FullType(String)]), format: ListFormat.csv), + if (enumFormString != null) r'enum_form_string': encodeQueryParameter(_serializers, enumFormString, const FullType(String)), }; - } catch(error) { + } catch(error, stackTrace) { throw DioError( requestOptions: _options.compose( _dio.options, @@ -968,7 +1117,7 @@ class FakeApi { ), type: DioErrorType.other, error: error, - ); + )..stackTrace = stackTrace; } final _response = await _dio.request( @@ -985,8 +1134,24 @@ class FakeApi { } /// Fake endpoint to test group parameters (optional) - /// /// Fake endpoint to test group parameters (optional) + /// + /// Parameters: + /// * [requiredStringGroup] - Required String in group parameters + /// * [requiredBooleanGroup] - Required Boolean in group parameters + /// * [requiredInt64Group] - Required Integer in group parameters + /// * [stringGroup] - String in group parameters + /// * [booleanGroup] - Boolean in group parameters + /// * [int64Group] - Integer in group parameters + /// * [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 [DioError] if API call or serialization fails Future> testGroupParameters({ required int requiredStringGroup, required bool requiredBooleanGroup, @@ -1018,17 +1183,14 @@ class FakeApi { ], ...?extra, }, - contentType: [ - 'application/json', - ].first, validateStatus: validateStatus, ); final _queryParameters = { - r'required_string_group': requiredStringGroup, - r'required_int64_group': requiredInt64Group, - if (stringGroup != null) r'string_group': stringGroup, - if (int64Group != null) r'int64_group': int64Group, + r'required_string_group': encodeQueryParameter(_serializers, requiredStringGroup, const FullType(int)), + r'required_int64_group': encodeQueryParameter(_serializers, requiredInt64Group, const FullType(int)), + if (stringGroup != null) r'string_group': encodeQueryParameter(_serializers, stringGroup, const FullType(int)), + if (int64Group != null) r'int64_group': encodeQueryParameter(_serializers, int64Group, const FullType(int)), }; final _response = await _dio.request( @@ -1044,8 +1206,19 @@ class FakeApi { } /// test inline 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 [DioError] if API call or serialization fails Future> testInlineAdditionalProperties({ required BuiltMap requestBody, CancelToken? cancelToken, @@ -1065,38 +1238,31 @@ class FakeApi { 'secure': >[], ...?extra, }, - contentType: [ - 'application/json', - ].first, + contentType: 'application/json', validateStatus: validateStatus, ); - final _queryParameters = { - }; - dynamic _bodyData; try { const _type = FullType(BuiltMap, [FullType(String), FullType(String)]); _bodyData = _serializers.serialize(requestBody, specifiedType: _type); - } catch(error) { + } catch(error, stackTrace) { throw DioError( requestOptions: _options.compose( _dio.options, _path, - queryParameters: _queryParameters, ), type: DioErrorType.other, error: error, - ); + )..stackTrace = stackTrace; } final _response = await _dio.request( _path, data: _bodyData, options: _options, - queryParameters: _queryParameters, cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, @@ -1106,8 +1272,20 @@ class FakeApi { } /// test json serialization of form data - /// /// + /// + /// Parameters: + /// * [param] - field1 + /// * [param2] - field2 + /// * [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 [DioError] if API call or serialization fails Future> testJsonFormData({ required String param, required String param2, @@ -1128,40 +1306,33 @@ class FakeApi { 'secure': >[], ...?extra, }, - contentType: [ - 'application/x-www-form-urlencoded', - ].first, + contentType: 'application/x-www-form-urlencoded', validateStatus: validateStatus, ); - final _queryParameters = { - }; - dynamic _bodyData; try { _bodyData = { - r'param': encodeFormParameter(_serializers, param, const FullType(String)), - r'param2': encodeFormParameter(_serializers, param2, const FullType(String)), + r'param': encodeQueryParameter(_serializers, param, const FullType(String)), + r'param2': encodeQueryParameter(_serializers, param2, const FullType(String)), }; - } catch(error) { + } catch(error, stackTrace) { throw DioError( requestOptions: _options.compose( _dio.options, _path, - queryParameters: _queryParameters, ), type: DioErrorType.other, error: error, - ); + )..stackTrace = stackTrace; } final _response = await _dio.request( _path, data: _bodyData, options: _options, - queryParameters: _queryParameters, cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, @@ -1170,9 +1341,24 @@ class FakeApi { return _response; } - /// - /// + /// testQueryParameterCollectionFormat /// To test the collection format in query parameters + /// + /// Parameters: + /// * [pipe] + /// * [ioutil] + /// * [http] + /// * [url] + /// * [context] + /// * [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 [DioError] if API call or serialization fails Future> testQueryParameterCollectionFormat({ required BuiltList pipe, required BuiltList ioutil, @@ -1196,18 +1382,15 @@ class FakeApi { 'secure': >[], ...?extra, }, - contentType: [ - 'application/json', - ].first, validateStatus: validateStatus, ); final _queryParameters = { - r'pipe': pipe, - r'ioutil': ioutil, - r'http': http, - r'url': url, - r'context': context, + r'pipe': encodeCollectionQueryParameter(_serializers, pipe, const FullType(BuiltList, [FullType(String)]), format: ListFormat.pipes), + r'ioutil': encodeCollectionQueryParameter(_serializers, ioutil, const FullType(BuiltList, [FullType(String)]), format: ListFormat.csv), + r'http': encodeCollectionQueryParameter(_serializers, http, const FullType(BuiltList, [FullType(String)]), format: ListFormat.ssv), + r'url': encodeCollectionQueryParameter(_serializers, url, const FullType(BuiltList, [FullType(String)]), format: ListFormat.csv), + r'context': encodeCollectionQueryParameter(_serializers, context, const FullType(BuiltList, [FullType(String)]), format: ListFormat.multi), }; final _response = await _dio.request( diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/api/fake_classname_tags123_api.dart b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/api/fake_classname_tags123_api.dart index 01d0383fd16..96329ea11f2 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/api/fake_classname_tags123_api.dart +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/api/fake_classname_tags123_api.dart @@ -18,8 +18,19 @@ class FakeClassnameTags123Api { const FakeClassnameTags123Api(this._dio, this._serializers); /// To test class name in snake case - /// /// To test class name in snake case + /// + /// Parameters: + /// * [modelClient] - client model + /// * [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] containing a [Response] with a [ModelClient] as data + /// Throws [DioError] if API call or serialization fails Future> testClassname({ required ModelClient modelClient, CancelToken? cancelToken, @@ -46,38 +57,31 @@ class FakeClassnameTags123Api { ], ...?extra, }, - contentType: [ - 'application/json', - ].first, + contentType: 'application/json', validateStatus: validateStatus, ); - final _queryParameters = { - }; - dynamic _bodyData; try { const _type = FullType(ModelClient); _bodyData = _serializers.serialize(modelClient, specifiedType: _type); - } catch(error) { + } catch(error, stackTrace) { throw DioError( requestOptions: _options.compose( _dio.options, _path, - queryParameters: _queryParameters, ), type: DioErrorType.other, error: error, - ); + )..stackTrace = stackTrace; } final _response = await _dio.request( _path, data: _bodyData, options: _options, - queryParameters: _queryParameters, cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, @@ -92,13 +96,13 @@ class FakeClassnameTags123Api { specifiedType: _responseType, ) as ModelClient; - } catch (error) { + } catch (error, stackTrace) { throw DioError( requestOptions: _response.requestOptions, response: _response, type: DioErrorType.other, error: error, - ); + )..stackTrace = stackTrace; } return Response( diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/api/pet_api.dart b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/api/pet_api.dart index 219b0cecd26..1dedc0456eb 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/api/pet_api.dart +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/api/pet_api.dart @@ -7,7 +7,6 @@ import 'dart:async'; import 'package:built_value/serializer.dart'; import 'package:dio/dio.dart'; -import 'dart:typed_data'; import 'package:built_collection/built_collection.dart'; import 'package:openapi/src/api_util.dart'; import 'package:openapi/src/model/api_response.dart'; @@ -22,8 +21,19 @@ class PetApi { const PetApi(this._dio, this._serializers); /// Add a new pet to the store - /// /// + /// + /// Parameters: + /// * [pet] - Pet object that needs to be added to the store + /// * [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 [DioError] if API call or serialization fails Future> addPet({ required Pet pet, CancelToken? cancelToken, @@ -48,39 +58,31 @@ class PetApi { ], ...?extra, }, - contentType: [ - 'application/json', - 'application/xml', - ].first, + contentType: 'application/json', validateStatus: validateStatus, ); - final _queryParameters = { - }; - dynamic _bodyData; try { const _type = FullType(Pet); _bodyData = _serializers.serialize(pet, specifiedType: _type); - } catch(error) { + } catch(error, stackTrace) { throw DioError( requestOptions: _options.compose( _dio.options, _path, - queryParameters: _queryParameters, ), type: DioErrorType.other, error: error, - ); + )..stackTrace = stackTrace; } final _response = await _dio.request( _path, data: _bodyData, options: _options, - queryParameters: _queryParameters, cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, @@ -90,8 +92,20 @@ class PetApi { } /// Deletes a pet - /// /// + /// + /// Parameters: + /// * [petId] - Pet id to delete + /// * [apiKey] + /// * [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 [DioError] if API call or serialization fails Future> deletePet({ required int petId, String? apiKey, @@ -118,19 +132,12 @@ class PetApi { ], ...?extra, }, - contentType: [ - 'application/json', - ].first, validateStatus: validateStatus, ); - final _queryParameters = { - }; - final _response = await _dio.request( _path, options: _options, - queryParameters: _queryParameters, cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, @@ -140,8 +147,19 @@ class PetApi { } /// Finds Pets by status - /// /// Multiple status values can be provided with comma separated strings + /// + /// Parameters: + /// * [status] - Status values that need to be considered for filter + /// * [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] containing a [Response] with a [BuiltList] as data + /// Throws [DioError] if API call or serialization fails Future>> findPetsByStatus({ required BuiltList status, CancelToken? cancelToken, @@ -166,14 +184,11 @@ class PetApi { ], ...?extra, }, - contentType: [ - 'application/json', - ].first, validateStatus: validateStatus, ); final _queryParameters = { - r'status': status, + r'status': encodeCollectionQueryParameter(_serializers, status, const FullType(BuiltList, [FullType(String)]), format: ListFormat.csv), }; final _response = await _dio.request( @@ -194,13 +209,13 @@ class PetApi { specifiedType: _responseType, ) as BuiltList; - } catch (error) { + } catch (error, stackTrace) { throw DioError( requestOptions: _response.requestOptions, response: _response, type: DioErrorType.other, error: error, - ); + )..stackTrace = stackTrace; } return Response>( @@ -216,8 +231,20 @@ class PetApi { } /// Finds Pets by tags - /// /// Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + /// + /// Parameters: + /// * [tags] - Tags to filter by + /// * [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] containing a [Response] with a [BuiltSet] as data + /// Throws [DioError] if API call or serialization fails + @Deprecated('This operation has been deprecated') Future>> findPetsByTags({ required BuiltSet tags, CancelToken? cancelToken, @@ -242,14 +269,11 @@ class PetApi { ], ...?extra, }, - contentType: [ - 'application/json', - ].first, validateStatus: validateStatus, ); final _queryParameters = { - r'tags': tags, + r'tags': encodeCollectionQueryParameter(_serializers, tags, const FullType(BuiltSet, [FullType(String)]), format: ListFormat.csv), }; final _response = await _dio.request( @@ -270,13 +294,13 @@ class PetApi { specifiedType: _responseType, ) as BuiltSet; - } catch (error) { + } catch (error, stackTrace) { throw DioError( requestOptions: _response.requestOptions, response: _response, type: DioErrorType.other, error: error, - ); + )..stackTrace = stackTrace; } return Response>( @@ -292,8 +316,19 @@ class PetApi { } /// Find pet by ID - /// /// Returns a single pet + /// + /// Parameters: + /// * [petId] - ID of pet to return + /// * [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] containing a [Response] with a [Pet] as data + /// Throws [DioError] if API call or serialization fails Future> getPetById({ required int petId, CancelToken? cancelToken, @@ -320,19 +355,12 @@ class PetApi { ], ...?extra, }, - contentType: [ - 'application/json', - ].first, validateStatus: validateStatus, ); - final _queryParameters = { - }; - final _response = await _dio.request( _path, options: _options, - queryParameters: _queryParameters, cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, @@ -347,13 +375,13 @@ class PetApi { specifiedType: _responseType, ) as Pet; - } catch (error) { + } catch (error, stackTrace) { throw DioError( requestOptions: _response.requestOptions, response: _response, type: DioErrorType.other, error: error, - ); + )..stackTrace = stackTrace; } return Response( @@ -369,8 +397,19 @@ class PetApi { } /// Update an existing pet - /// /// + /// + /// Parameters: + /// * [pet] - Pet object that needs to be added to the store + /// * [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 [DioError] if API call or serialization fails Future> updatePet({ required Pet pet, CancelToken? cancelToken, @@ -395,39 +434,31 @@ class PetApi { ], ...?extra, }, - contentType: [ - 'application/json', - 'application/xml', - ].first, + contentType: 'application/json', validateStatus: validateStatus, ); - final _queryParameters = { - }; - dynamic _bodyData; try { const _type = FullType(Pet); _bodyData = _serializers.serialize(pet, specifiedType: _type); - } catch(error) { + } catch(error, stackTrace) { throw DioError( requestOptions: _options.compose( _dio.options, _path, - queryParameters: _queryParameters, ), type: DioErrorType.other, error: error, - ); + )..stackTrace = stackTrace; } final _response = await _dio.request( _path, data: _bodyData, options: _options, - queryParameters: _queryParameters, cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, @@ -437,8 +468,21 @@ class PetApi { } /// Updates a pet in the store with form data - /// /// + /// + /// Parameters: + /// * [petId] - ID of pet that needs to be updated + /// * [name] - Updated name of the pet + /// * [status] - Updated status of the pet + /// * [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 [DioError] if API call or serialization fails Future> updatePetWithForm({ required int petId, String? name, @@ -465,40 +509,33 @@ class PetApi { ], ...?extra, }, - contentType: [ - 'application/x-www-form-urlencoded', - ].first, + contentType: 'application/x-www-form-urlencoded', validateStatus: validateStatus, ); - final _queryParameters = { - }; - dynamic _bodyData; try { _bodyData = { - if (name != null) r'name': encodeFormParameter(_serializers, name, const FullType(String)), - if (status != null) r'status': encodeFormParameter(_serializers, status, const FullType(String)), + if (name != null) r'name': encodeQueryParameter(_serializers, name, const FullType(String)), + if (status != null) r'status': encodeQueryParameter(_serializers, status, const FullType(String)), }; - } catch(error) { + } catch(error, stackTrace) { throw DioError( requestOptions: _options.compose( _dio.options, _path, - queryParameters: _queryParameters, ), type: DioErrorType.other, error: error, - ); + )..stackTrace = stackTrace; } final _response = await _dio.request( _path, data: _bodyData, options: _options, - queryParameters: _queryParameters, cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, @@ -508,12 +545,25 @@ class PetApi { } /// uploads an image - /// /// + /// + /// Parameters: + /// * [petId] - ID of pet to update + /// * [additionalMetadata] - Additional data to pass to server + /// * [file] - file to upload + /// * [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] containing a [Response] with a [ApiResponse] as data + /// Throws [DioError] if API call or serialization fails Future> uploadFile({ required int petId, String? additionalMetadata, - Uint8List? file, + MultipartFile? file, CancelToken? cancelToken, Map? headers, Map? extra, @@ -536,40 +586,33 @@ class PetApi { ], ...?extra, }, - contentType: [ - 'multipart/form-data', - ].first, + contentType: 'multipart/form-data', validateStatus: validateStatus, ); - final _queryParameters = { - }; - dynamic _bodyData; try { _bodyData = FormData.fromMap({ if (additionalMetadata != null) r'additionalMetadata': encodeFormParameter(_serializers, additionalMetadata, const FullType(String)), - if (file != null) r'file': MultipartFile.fromBytes(file, filename: r'file'), + if (file != null) r'file': file, }); - } catch(error) { + } catch(error, stackTrace) { throw DioError( requestOptions: _options.compose( _dio.options, _path, - queryParameters: _queryParameters, ), type: DioErrorType.other, error: error, - ); + )..stackTrace = stackTrace; } final _response = await _dio.request( _path, data: _bodyData, options: _options, - queryParameters: _queryParameters, cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, @@ -584,13 +627,13 @@ class PetApi { specifiedType: _responseType, ) as ApiResponse; - } catch (error) { + } catch (error, stackTrace) { throw DioError( requestOptions: _response.requestOptions, response: _response, type: DioErrorType.other, error: error, - ); + )..stackTrace = stackTrace; } return Response( @@ -606,11 +649,24 @@ class PetApi { } /// uploads an image (required) - /// /// + /// + /// Parameters: + /// * [petId] - ID of pet to update + /// * [requiredFile] - file to upload + /// * [additionalMetadata] - Additional data to pass to server + /// * [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] containing a [Response] with a [ApiResponse] as data + /// Throws [DioError] if API call or serialization fails Future> uploadFileWithRequiredFile({ required int petId, - required Uint8List requiredFile, + required MultipartFile requiredFile, String? additionalMetadata, CancelToken? cancelToken, Map? headers, @@ -634,40 +690,33 @@ class PetApi { ], ...?extra, }, - contentType: [ - 'multipart/form-data', - ].first, + contentType: 'multipart/form-data', validateStatus: validateStatus, ); - final _queryParameters = { - }; - dynamic _bodyData; try { _bodyData = FormData.fromMap({ if (additionalMetadata != null) r'additionalMetadata': encodeFormParameter(_serializers, additionalMetadata, const FullType(String)), - r'requiredFile': MultipartFile.fromBytes(requiredFile, filename: r'requiredFile'), + r'requiredFile': requiredFile, }); - } catch(error) { + } catch(error, stackTrace) { throw DioError( requestOptions: _options.compose( _dio.options, _path, - queryParameters: _queryParameters, ), type: DioErrorType.other, error: error, - ); + )..stackTrace = stackTrace; } final _response = await _dio.request( _path, data: _bodyData, options: _options, - queryParameters: _queryParameters, cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, @@ -682,13 +731,13 @@ class PetApi { specifiedType: _responseType, ) as ApiResponse; - } catch (error) { + } catch (error, stackTrace) { throw DioError( requestOptions: _response.requestOptions, response: _response, type: DioErrorType.other, error: error, - ); + )..stackTrace = stackTrace; } return Response( diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/api/store_api.dart b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/api/store_api.dart index 0c0b9f44794..93d5ccbe97c 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/api/store_api.dart +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/api/store_api.dart @@ -19,8 +19,19 @@ class StoreApi { const StoreApi(this._dio, this._serializers); /// 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 + /// Parameters: + /// * [orderId] - ID of the order that needs to be deleted + /// * [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 [DioError] if API call or serialization fails Future> deleteOrder({ required String orderId, CancelToken? cancelToken, @@ -40,19 +51,12 @@ class StoreApi { 'secure': >[], ...?extra, }, - contentType: [ - 'application/json', - ].first, validateStatus: validateStatus, ); - final _queryParameters = { - }; - final _response = await _dio.request( _path, options: _options, - queryParameters: _queryParameters, cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, @@ -62,8 +66,18 @@ class StoreApi { } /// Returns pet inventories by status - /// /// Returns a map of status codes to quantities + /// + /// Parameters: + /// * [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] containing a [Response] with a [BuiltMap] as data + /// Throws [DioError] if API call or serialization fails Future>> getInventory({ CancelToken? cancelToken, Map? headers, @@ -89,19 +103,12 @@ class StoreApi { ], ...?extra, }, - contentType: [ - 'application/json', - ].first, validateStatus: validateStatus, ); - final _queryParameters = { - }; - final _response = await _dio.request( _path, options: _options, - queryParameters: _queryParameters, cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, @@ -116,13 +123,13 @@ class StoreApi { specifiedType: _responseType, ) as BuiltMap; - } catch (error) { + } catch (error, stackTrace) { throw DioError( requestOptions: _response.requestOptions, response: _response, type: DioErrorType.other, error: error, - ); + )..stackTrace = stackTrace; } return Response>( @@ -138,8 +145,19 @@ class StoreApi { } /// Find purchase order by ID + /// For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions /// - /// For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + /// Parameters: + /// * [orderId] - ID of pet that needs to be fetched + /// * [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] containing a [Response] with a [Order] as data + /// Throws [DioError] if API call or serialization fails Future> getOrderById({ required int orderId, CancelToken? cancelToken, @@ -159,19 +177,12 @@ class StoreApi { 'secure': >[], ...?extra, }, - contentType: [ - 'application/json', - ].first, validateStatus: validateStatus, ); - final _queryParameters = { - }; - final _response = await _dio.request( _path, options: _options, - queryParameters: _queryParameters, cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, @@ -186,13 +197,13 @@ class StoreApi { specifiedType: _responseType, ) as Order; - } catch (error) { + } catch (error, stackTrace) { throw DioError( requestOptions: _response.requestOptions, response: _response, type: DioErrorType.other, error: error, - ); + )..stackTrace = stackTrace; } return Response( @@ -208,8 +219,19 @@ class StoreApi { } /// Place an order for a pet - /// /// + /// + /// Parameters: + /// * [order] - order placed for purchasing the pet + /// * [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] containing a [Response] with a [Order] as data + /// Throws [DioError] if API call or serialization fails Future> placeOrder({ required Order order, CancelToken? cancelToken, @@ -229,38 +251,31 @@ class StoreApi { 'secure': >[], ...?extra, }, - contentType: [ - 'application/json', - ].first, + contentType: 'application/json', validateStatus: validateStatus, ); - final _queryParameters = { - }; - dynamic _bodyData; try { const _type = FullType(Order); _bodyData = _serializers.serialize(order, specifiedType: _type); - } catch(error) { + } catch(error, stackTrace) { throw DioError( requestOptions: _options.compose( _dio.options, _path, - queryParameters: _queryParameters, ), type: DioErrorType.other, error: error, - ); + )..stackTrace = stackTrace; } final _response = await _dio.request( _path, data: _bodyData, options: _options, - queryParameters: _queryParameters, cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, @@ -275,13 +290,13 @@ class StoreApi { specifiedType: _responseType, ) as Order; - } catch (error) { + } catch (error, stackTrace) { throw DioError( requestOptions: _response.requestOptions, response: _response, type: DioErrorType.other, error: error, - ); + )..stackTrace = stackTrace; } return Response( diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/api/user_api.dart b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/api/user_api.dart index c0551df5e51..6faaed6336d 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/api/user_api.dart +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/api/user_api.dart @@ -8,6 +8,7 @@ import 'package:built_value/serializer.dart'; import 'package:dio/dio.dart'; import 'package:built_collection/built_collection.dart'; +import 'package:openapi/src/api_util.dart'; import 'package:openapi/src/model/user.dart'; class UserApi { @@ -19,8 +20,19 @@ class UserApi { const UserApi(this._dio, this._serializers); /// Create user - /// /// This can only be done by the logged in user. + /// + /// Parameters: + /// * [user] - Created user object + /// * [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 [DioError] if API call or serialization fails Future> createUser({ required User user, CancelToken? cancelToken, @@ -40,38 +52,31 @@ class UserApi { 'secure': >[], ...?extra, }, - contentType: [ - 'application/json', - ].first, + contentType: 'application/json', validateStatus: validateStatus, ); - final _queryParameters = { - }; - dynamic _bodyData; try { const _type = FullType(User); _bodyData = _serializers.serialize(user, specifiedType: _type); - } catch(error) { + } catch(error, stackTrace) { throw DioError( requestOptions: _options.compose( _dio.options, _path, - queryParameters: _queryParameters, ), type: DioErrorType.other, error: error, - ); + )..stackTrace = stackTrace; } final _response = await _dio.request( _path, data: _bodyData, options: _options, - queryParameters: _queryParameters, cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, @@ -81,8 +86,19 @@ class UserApi { } /// Creates list of users with given input array - /// /// + /// + /// Parameters: + /// * [user] - List of user object + /// * [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 [DioError] if API call or serialization fails Future> createUsersWithArrayInput({ required BuiltList user, CancelToken? cancelToken, @@ -102,38 +118,31 @@ class UserApi { 'secure': >[], ...?extra, }, - contentType: [ - 'application/json', - ].first, + contentType: 'application/json', validateStatus: validateStatus, ); - final _queryParameters = { - }; - dynamic _bodyData; try { const _type = FullType(BuiltList, [FullType(User)]); _bodyData = _serializers.serialize(user, specifiedType: _type); - } catch(error) { + } catch(error, stackTrace) { throw DioError( requestOptions: _options.compose( _dio.options, _path, - queryParameters: _queryParameters, ), type: DioErrorType.other, error: error, - ); + )..stackTrace = stackTrace; } final _response = await _dio.request( _path, data: _bodyData, options: _options, - queryParameters: _queryParameters, cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, @@ -143,8 +152,19 @@ class UserApi { } /// Creates list of users with given input array - /// /// + /// + /// Parameters: + /// * [user] - List of user object + /// * [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 [DioError] if API call or serialization fails Future> createUsersWithListInput({ required BuiltList user, CancelToken? cancelToken, @@ -164,38 +184,31 @@ class UserApi { 'secure': >[], ...?extra, }, - contentType: [ - 'application/json', - ].first, + contentType: 'application/json', validateStatus: validateStatus, ); - final _queryParameters = { - }; - dynamic _bodyData; try { const _type = FullType(BuiltList, [FullType(User)]); _bodyData = _serializers.serialize(user, specifiedType: _type); - } catch(error) { + } catch(error, stackTrace) { throw DioError( requestOptions: _options.compose( _dio.options, _path, - queryParameters: _queryParameters, ), type: DioErrorType.other, error: error, - ); + )..stackTrace = stackTrace; } final _response = await _dio.request( _path, data: _bodyData, options: _options, - queryParameters: _queryParameters, cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, @@ -205,8 +218,19 @@ class UserApi { } /// Delete user - /// /// This can only be done by the logged in user. + /// + /// Parameters: + /// * [username] - The name that needs to be deleted + /// * [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 [DioError] if API call or serialization fails Future> deleteUser({ required String username, CancelToken? cancelToken, @@ -226,19 +250,12 @@ class UserApi { 'secure': >[], ...?extra, }, - contentType: [ - 'application/json', - ].first, validateStatus: validateStatus, ); - final _queryParameters = { - }; - final _response = await _dio.request( _path, options: _options, - queryParameters: _queryParameters, cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, @@ -248,8 +265,19 @@ class UserApi { } /// Get user by user name - /// /// + /// + /// Parameters: + /// * [username] - The name that needs to be fetched. Use user1 for testing. + /// * [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] containing a [Response] with a [User] as data + /// Throws [DioError] if API call or serialization fails Future> getUserByName({ required String username, CancelToken? cancelToken, @@ -269,19 +297,12 @@ class UserApi { 'secure': >[], ...?extra, }, - contentType: [ - 'application/json', - ].first, validateStatus: validateStatus, ); - final _queryParameters = { - }; - final _response = await _dio.request( _path, options: _options, - queryParameters: _queryParameters, cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, @@ -296,13 +317,13 @@ class UserApi { specifiedType: _responseType, ) as User; - } catch (error) { + } catch (error, stackTrace) { throw DioError( requestOptions: _response.requestOptions, response: _response, type: DioErrorType.other, error: error, - ); + )..stackTrace = stackTrace; } return Response( @@ -318,8 +339,20 @@ class UserApi { } /// Logs user into the system - /// /// + /// + /// Parameters: + /// * [username] - The user name for login + /// * [password] - The password for login in clear text + /// * [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] containing a [Response] with a [String] as data + /// Throws [DioError] if API call or serialization fails Future> loginUser({ required String username, required String password, @@ -340,15 +373,12 @@ class UserApi { 'secure': >[], ...?extra, }, - contentType: [ - 'application/json', - ].first, validateStatus: validateStatus, ); final _queryParameters = { - r'username': username, - r'password': password, + r'username': encodeQueryParameter(_serializers, username, const FullType(String)), + r'password': encodeQueryParameter(_serializers, password, const FullType(String)), }; final _response = await _dio.request( @@ -365,13 +395,13 @@ class UserApi { try { _responseData = _response.data as String; - } catch (error) { + } catch (error, stackTrace) { throw DioError( requestOptions: _response.requestOptions, response: _response, type: DioErrorType.other, error: error, - ); + )..stackTrace = stackTrace; } return Response( @@ -387,8 +417,18 @@ class UserApi { } /// Logs out current logged in user session - /// /// + /// + /// Parameters: + /// * [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 [DioError] if API call or serialization fails Future> logoutUser({ CancelToken? cancelToken, Map? headers, @@ -407,19 +447,12 @@ class UserApi { 'secure': >[], ...?extra, }, - contentType: [ - 'application/json', - ].first, validateStatus: validateStatus, ); - final _queryParameters = { - }; - final _response = await _dio.request( _path, options: _options, - queryParameters: _queryParameters, cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, @@ -429,8 +462,20 @@ class UserApi { } /// Updated user - /// /// This can only be done by the logged in user. + /// + /// Parameters: + /// * [username] - name that need to be deleted + /// * [user] - Updated user object + /// * [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 [DioError] if API call or serialization fails Future> updateUser({ required String username, required User user, @@ -451,38 +496,31 @@ class UserApi { 'secure': >[], ...?extra, }, - contentType: [ - 'application/json', - ].first, + contentType: 'application/json', validateStatus: validateStatus, ); - final _queryParameters = { - }; - dynamic _bodyData; try { const _type = FullType(User); _bodyData = _serializers.serialize(user, specifiedType: _type); - } catch(error) { + } catch(error, stackTrace) { throw DioError( requestOptions: _options.compose( _dio.options, _path, - queryParameters: _queryParameters, ), type: DioErrorType.other, error: error, - ); + )..stackTrace = stackTrace; } final _response = await _dio.request( _path, data: _bodyData, options: _options, - queryParameters: _queryParameters, cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/api_util.dart b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/api_util.dart index ca7832e3693..09b9ba88fd9 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/api_util.dart +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/api_util.dart @@ -3,9 +3,12 @@ // import 'dart:convert'; +import 'dart:typed_data'; import 'package:built_collection/built_collection.dart'; import 'package:built_value/serializer.dart'; +import 'package:dio/dio.dart'; +import 'package:dio/src/parameter.dart'; /// Format the given form parameter object into something that Dio can handle. /// Returns primitive or String. @@ -24,8 +27,52 @@ dynamic encodeFormParameter(Serializers serializers, dynamic value, FullType typ if (serialized is String) { return serialized; } - if (value is BuiltList || value is BuiltMap) { + if (value is BuiltList || value is BuiltSet || value is BuiltMap) { return serialized; } return json.encode(serialized); } + +dynamic encodeQueryParameter( + Serializers serializers, + dynamic value, + FullType type, +) { + if (value == null) { + return ''; + } + if (value is String || value is num || value is bool) { + return value; + } + if (value is Uint8List) { + // Currently not sure how to serialize this + return value; + } + final serialized = serializers.serialize( + value as Object, + specifiedType: type, + ); + if (serialized == null) { + return ''; + } + if (serialized is String) { + return serialized; + } + return serialized; +} + +ListParam encodeCollectionQueryParameter( + Serializers serializers, + dynamic value, + FullType type, { + ListFormat format = ListFormat.multi, +}) { + final serialized = serializers.serialize( + value as Object, + specifiedType: type, + ); + if (value is BuiltList || value is BuiltSet) { + return ListParam(List.of((serialized as Iterable).cast()), format); + } + throw ArgumentError('Invalid value passed to encodeCollectionQueryParameter'); +} diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/additional_properties_class.dart b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/additional_properties_class.dart index f92d8336bbb..25e0fb4fdbf 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/additional_properties_class.dart +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/additional_properties_class.dart @@ -8,8 +8,11 @@ import 'package:built_value/serializer.dart'; part 'additional_properties_class.g.dart'; - - +/// AdditionalPropertiesClass +/// +/// Properties: +/// * [mapProperty] +/// * [mapOfMapProperty] abstract class AdditionalPropertiesClass implements Built { @BuiltValueField(wireName: r'map_property') BuiltMap? get mapProperty; diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/animal.dart b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/animal.dart index 14419f9eca4..d51c6d7b0be 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/animal.dart +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/animal.dart @@ -7,8 +7,11 @@ import 'package:built_value/serializer.dart'; part 'animal.g.dart'; - - +/// Animal +/// +/// Properties: +/// * [className] +/// * [color] abstract class Animal implements Built { @BuiltValueField(wireName: r'className') String get className; diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/api_response.dart b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/api_response.dart index 4c9fa0b7159..fc9554f36ce 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/api_response.dart +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/api_response.dart @@ -7,8 +7,12 @@ import 'package:built_value/serializer.dart'; part 'api_response.g.dart'; - - +/// ApiResponse +/// +/// Properties: +/// * [code] +/// * [type] +/// * [message] abstract class ApiResponse implements Built { @BuiltValueField(wireName: r'code') int? get code; diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/array_of_array_of_number_only.dart b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/array_of_array_of_number_only.dart index 0f86aa08c5b..899697f7efc 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/array_of_array_of_number_only.dart +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/array_of_array_of_number_only.dart @@ -8,8 +8,10 @@ import 'package:built_value/serializer.dart'; part 'array_of_array_of_number_only.g.dart'; - - +/// ArrayOfArrayOfNumberOnly +/// +/// Properties: +/// * [arrayArrayNumber] abstract class ArrayOfArrayOfNumberOnly implements Built { @BuiltValueField(wireName: r'ArrayArrayNumber') BuiltList>? get arrayArrayNumber; diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/array_of_number_only.dart b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/array_of_number_only.dart index b68a04794aa..2e886df9b04 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/array_of_number_only.dart +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/array_of_number_only.dart @@ -8,8 +8,10 @@ import 'package:built_value/serializer.dart'; part 'array_of_number_only.g.dart'; - - +/// ArrayOfNumberOnly +/// +/// Properties: +/// * [arrayNumber] abstract class ArrayOfNumberOnly implements Built { @BuiltValueField(wireName: r'ArrayNumber') BuiltList? get arrayNumber; diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/array_test.dart b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/array_test.dart index e9657764dc4..82ee6c2c01a 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/array_test.dart +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/array_test.dart @@ -9,8 +9,12 @@ import 'package:built_value/serializer.dart'; part 'array_test.g.dart'; - - +/// ArrayTest +/// +/// Properties: +/// * [arrayOfString] +/// * [arrayArrayOfInteger] +/// * [arrayArrayOfModel] abstract class ArrayTest implements Built { @BuiltValueField(wireName: r'array_of_string') BuiltList? get arrayOfString; diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/capitalization.dart b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/capitalization.dart index 9b7cd294db3..fb1bfd7a5b9 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/capitalization.dart +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/capitalization.dart @@ -7,8 +7,15 @@ import 'package:built_value/serializer.dart'; part 'capitalization.g.dart'; - - +/// Capitalization +/// +/// Properties: +/// * [smallCamel] +/// * [capitalCamel] +/// * [smallSnake] +/// * [capitalSnake] +/// * [sCAETHFlowPoints] +/// * [ATT_NAME] - Name of the pet abstract class Capitalization implements Built { @BuiltValueField(wireName: r'smallCamel') String? get smallCamel; diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/cat.dart b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/cat.dart index 1ee68912ba7..fa9282bb8cb 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/cat.dart +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/cat.dart @@ -11,6 +11,12 @@ part 'cat.g.dart'; // ignore_for_file: unused_import +/// Cat +/// +/// Properties: +/// * [className] +/// * [color] +/// * [declawed] abstract class Cat implements Built { @BuiltValueField(wireName: r'className') String get className; diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/cat_all_of.dart b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/cat_all_of.dart index cbbf6321603..b8019b936d8 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/cat_all_of.dart +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/cat_all_of.dart @@ -7,8 +7,10 @@ import 'package:built_value/serializer.dart'; part 'cat_all_of.g.dart'; - - +/// CatAllOf +/// +/// Properties: +/// * [declawed] abstract class CatAllOf implements Built { @BuiltValueField(wireName: r'declawed') bool? get declawed; diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/category.dart b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/category.dart index 3bc36cefbcc..35184265992 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/category.dart +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/category.dart @@ -7,8 +7,11 @@ import 'package:built_value/serializer.dart'; part 'category.g.dart'; - - +/// Category +/// +/// Properties: +/// * [id] +/// * [name] abstract class Category implements Built { @BuiltValueField(wireName: r'id') int? get id; diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/class_model.dart b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/class_model.dart index bdc392005cf..7b99dc2be1a 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/class_model.dart +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/class_model.dart @@ -7,8 +7,10 @@ import 'package:built_value/serializer.dart'; part 'class_model.g.dart'; - - +/// Model for testing model with \"_class\" property +/// +/// Properties: +/// * [class_] abstract class ClassModel implements Built { @BuiltValueField(wireName: r'_class') String? get class_; diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/date.dart b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/date.dart index c3a87eae259..b21c7f544be 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/date.dart +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/date.dart @@ -24,9 +24,10 @@ class Date implements Comparable { /// Convert to a [DateTime]. DateTime toDateTime({bool utc = false}) { if (utc) { - DateTime.utc(year, month, day); + return DateTime.utc(year, month, day); + } else { + return DateTime(year, month, day); } - return DateTime(year, month, day); } @override @@ -66,4 +67,4 @@ class Date implements Comparable { extension DateTimeToDate on DateTime { Date toDate() => Date(year, month, day); -} \ No newline at end of file +} diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/dog.dart b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/dog.dart index 63f2d483d5d..9ca43e05402 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/dog.dart +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/dog.dart @@ -11,6 +11,12 @@ part 'dog.g.dart'; // ignore_for_file: unused_import +/// Dog +/// +/// Properties: +/// * [className] +/// * [color] +/// * [breed] abstract class Dog implements Built { @BuiltValueField(wireName: r'className') String get className; diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/dog_all_of.dart b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/dog_all_of.dart index e896ffe4b1b..291310df2c2 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/dog_all_of.dart +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/dog_all_of.dart @@ -7,8 +7,10 @@ import 'package:built_value/serializer.dart'; part 'dog_all_of.g.dart'; - - +/// DogAllOf +/// +/// Properties: +/// * [breed] abstract class DogAllOf implements Built { @BuiltValueField(wireName: r'breed') String? get breed; diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/enum_arrays.dart b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/enum_arrays.dart index 371f28947d8..0e28f7247a8 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/enum_arrays.dart +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/enum_arrays.dart @@ -8,8 +8,11 @@ import 'package:built_value/serializer.dart'; part 'enum_arrays.g.dart'; - - +/// EnumArrays +/// +/// Properties: +/// * [justSymbol] +/// * [arrayEnum] abstract class EnumArrays implements Built { @BuiltValueField(wireName: r'just_symbol') EnumArraysJustSymbolEnum? get justSymbol; diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/enum_test.dart b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/enum_test.dart index 51c417dcadd..8e6d8c6d23e 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/enum_test.dart +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/enum_test.dart @@ -12,8 +12,17 @@ import 'package:built_value/serializer.dart'; part 'enum_test.g.dart'; - - +/// EnumTest +/// +/// Properties: +/// * [enumString] +/// * [enumStringRequired] +/// * [enumInteger] +/// * [enumNumber] +/// * [outerEnum] +/// * [outerEnumInteger] +/// * [outerEnumDefaultValue] +/// * [outerEnumIntegerDefaultValue] abstract class EnumTest implements Built { @BuiltValueField(wireName: r'enum_string') EnumTestEnumStringEnum? get enumString; diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/file_schema_test_class.dart b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/file_schema_test_class.dart index 083b61e326a..0fdd8367085 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/file_schema_test_class.dart +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/file_schema_test_class.dart @@ -9,8 +9,11 @@ import 'package:built_value/serializer.dart'; part 'file_schema_test_class.g.dart'; - - +/// FileSchemaTestClass +/// +/// Properties: +/// * [file] +/// * [files] abstract class FileSchemaTestClass implements Built { @BuiltValueField(wireName: r'file') ModelFile? get file; diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/foo.dart b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/foo.dart index 045d8857577..148b67aacea 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/foo.dart +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/foo.dart @@ -7,8 +7,10 @@ import 'package:built_value/serializer.dart'; part 'foo.g.dart'; - - +/// Foo +/// +/// Properties: +/// * [bar] abstract class Foo implements Built { @BuiltValueField(wireName: r'bar') String? get bar; diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/format_test.dart b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/format_test.dart index 745e9b5c63b..eb013af8673 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/format_test.dart +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/format_test.dart @@ -9,8 +9,25 @@ import 'package:built_value/serializer.dart'; part 'format_test.g.dart'; - - +/// FormatTest +/// +/// Properties: +/// * [integer] +/// * [int32] +/// * [int64] +/// * [number] +/// * [float] +/// * [double_] +/// * [decimal] +/// * [string] +/// * [byte] +/// * [binary] +/// * [date] +/// * [dateTime] +/// * [uuid] +/// * [password] +/// * [patternWithDigits] - A string that is a 10 digit number. Can have leading zeros. +/// * [patternWithDigitsAndDelimiter] - A string starting with 'image_' (case insensitive) and one to three digits following i.e. Image_01. abstract class FormatTest implements Built { @BuiltValueField(wireName: r'integer') int? get integer; diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/has_only_read_only.dart b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/has_only_read_only.dart index f7cb2cd2e5a..d1ed7b46954 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/has_only_read_only.dart +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/has_only_read_only.dart @@ -7,8 +7,11 @@ import 'package:built_value/serializer.dart'; part 'has_only_read_only.g.dart'; - - +/// HasOnlyReadOnly +/// +/// Properties: +/// * [bar] +/// * [foo] abstract class HasOnlyReadOnly implements Built { @BuiltValueField(wireName: r'bar') String? get bar; diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/health_check_result.dart b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/health_check_result.dart index 69bca6dce0f..a071f956787 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/health_check_result.dart +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/health_check_result.dart @@ -7,8 +7,10 @@ import 'package:built_value/serializer.dart'; part 'health_check_result.g.dart'; - - +/// Just a string to inform instance is up and running. Make it nullable in hope to get it as pointer in generated model. +/// +/// Properties: +/// * [nullableMessage] abstract class HealthCheckResult implements Built { @BuiltValueField(wireName: r'NullableMessage') String? get nullableMessage; diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/inline_response_default.dart b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/inline_response_default.dart index 875b612c5d6..d6eb09c8797 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/inline_response_default.dart +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/inline_response_default.dart @@ -8,8 +8,10 @@ import 'package:built_value/serializer.dart'; part 'inline_response_default.g.dart'; - - +/// InlineResponseDefault +/// +/// Properties: +/// * [string] abstract class InlineResponseDefault implements Built { @BuiltValueField(wireName: r'string') Foo? get string; diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/map_test.dart b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/map_test.dart index 21af21a52bb..89fa1e3065e 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/map_test.dart +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/map_test.dart @@ -8,8 +8,13 @@ import 'package:built_value/serializer.dart'; part 'map_test.g.dart'; - - +/// MapTest +/// +/// Properties: +/// * [mapMapOfString] +/// * [mapOfEnumString] +/// * [directMap] +/// * [indirectMap] abstract class MapTest implements Built { @BuiltValueField(wireName: r'map_map_of_string') BuiltMap>? get mapMapOfString; diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/mixed_properties_and_additional_properties_class.dart b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/mixed_properties_and_additional_properties_class.dart index 4da5f4d520d..55328c39f6f 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/mixed_properties_and_additional_properties_class.dart +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/mixed_properties_and_additional_properties_class.dart @@ -9,8 +9,12 @@ import 'package:built_value/serializer.dart'; part 'mixed_properties_and_additional_properties_class.g.dart'; - - +/// MixedPropertiesAndAdditionalPropertiesClass +/// +/// Properties: +/// * [uuid] +/// * [dateTime] +/// * [map] abstract class MixedPropertiesAndAdditionalPropertiesClass implements Built { @BuiltValueField(wireName: r'uuid') String? get uuid; diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/model200_response.dart b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/model200_response.dart index be8614351cb..f8eaf0f3e2d 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/model200_response.dart +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/model200_response.dart @@ -7,8 +7,11 @@ import 'package:built_value/serializer.dart'; part 'model200_response.g.dart'; - - +/// Model for testing model name starting with number +/// +/// Properties: +/// * [name] +/// * [class_] abstract class Model200Response implements Built { @BuiltValueField(wireName: r'name') int? get name; diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/model_client.dart b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/model_client.dart index 57871562a07..045a6805707 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/model_client.dart +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/model_client.dart @@ -7,8 +7,10 @@ import 'package:built_value/serializer.dart'; part 'model_client.g.dart'; - - +/// ModelClient +/// +/// Properties: +/// * [client] abstract class ModelClient implements Built { @BuiltValueField(wireName: r'client') String? get client; diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/model_file.dart b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/model_file.dart index 8a6c468bc00..2ad4601d2f0 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/model_file.dart +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/model_file.dart @@ -7,8 +7,10 @@ import 'package:built_value/serializer.dart'; part 'model_file.g.dart'; - - +/// Must be named `File` for test. +/// +/// Properties: +/// * [sourceURI] - Test capitalization abstract class ModelFile implements Built { /// Test capitalization @BuiltValueField(wireName: r'sourceURI') diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/model_list.dart b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/model_list.dart index 901616e8dc6..4bb83e5f277 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/model_list.dart +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/model_list.dart @@ -7,8 +7,10 @@ import 'package:built_value/serializer.dart'; part 'model_list.g.dart'; - - +/// ModelList +/// +/// Properties: +/// * [n123list] abstract class ModelList implements Built { @BuiltValueField(wireName: r'123-list') String? get n123list; diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/model_return.dart b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/model_return.dart index 42c03755627..4e7bad16424 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/model_return.dart +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/model_return.dart @@ -7,8 +7,10 @@ import 'package:built_value/serializer.dart'; part 'model_return.g.dart'; - - +/// Model for testing reserved words +/// +/// Properties: +/// * [return_] abstract class ModelReturn implements Built { @BuiltValueField(wireName: r'return') int? get return_; diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/name.dart b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/name.dart index 911fa0a5471..1963c3ace07 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/name.dart +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/name.dart @@ -7,8 +7,13 @@ import 'package:built_value/serializer.dart'; part 'name.g.dart'; - - +/// Model for testing model name same as property name +/// +/// Properties: +/// * [name] +/// * [snakeCase] +/// * [property] +/// * [n123number] abstract class Name implements Built { @BuiltValueField(wireName: r'name') int get name; diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/nullable_class.dart b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/nullable_class.dart index 13fa27880f6..30dc376cb02 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/nullable_class.dart +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/nullable_class.dart @@ -10,8 +10,21 @@ import 'package:built_value/serializer.dart'; part 'nullable_class.g.dart'; - - +/// NullableClass +/// +/// Properties: +/// * [integerProp] +/// * [numberProp] +/// * [booleanProp] +/// * [stringProp] +/// * [dateProp] +/// * [datetimeProp] +/// * [arrayNullableProp] +/// * [arrayAndItemsNullableProp] +/// * [arrayItemsNullable] +/// * [objectNullableProp] +/// * [objectAndItemsNullableProp] +/// * [objectItemsNullable] abstract class NullableClass implements Built { @BuiltValueField(wireName: r'integer_prop') int? get integerProp; diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/number_only.dart b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/number_only.dart index 55e00d4d65c..b423c6fc656 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/number_only.dart +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/number_only.dart @@ -7,8 +7,10 @@ import 'package:built_value/serializer.dart'; part 'number_only.g.dart'; - - +/// NumberOnly +/// +/// Properties: +/// * [justNumber] abstract class NumberOnly implements Built { @BuiltValueField(wireName: r'JustNumber') num? get justNumber; diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/order.dart b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/order.dart index 9c65fbf0c3a..cdebcd96b1e 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/order.dart +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/order.dart @@ -8,8 +8,15 @@ import 'package:built_value/serializer.dart'; part 'order.g.dart'; - - +/// Order +/// +/// Properties: +/// * [id] +/// * [petId] +/// * [quantity] +/// * [shipDate] +/// * [status] - Order Status +/// * [complete] abstract class Order implements Built { @BuiltValueField(wireName: r'id') int? get id; diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/outer_composite.dart b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/outer_composite.dart index 69007a11464..0a8f4296c13 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/outer_composite.dart +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/outer_composite.dart @@ -7,8 +7,12 @@ import 'package:built_value/serializer.dart'; part 'outer_composite.g.dart'; - - +/// OuterComposite +/// +/// Properties: +/// * [myNumber] +/// * [myString] +/// * [myBoolean] abstract class OuterComposite implements Built { @BuiltValueField(wireName: r'my_number') num? get myNumber; diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/outer_object_with_enum_property.dart b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/outer_object_with_enum_property.dart index 6f4563d7a5e..a95f92d8837 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/outer_object_with_enum_property.dart +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/outer_object_with_enum_property.dart @@ -8,8 +8,10 @@ import 'package:built_value/serializer.dart'; part 'outer_object_with_enum_property.g.dart'; - - +/// OuterObjectWithEnumProperty +/// +/// Properties: +/// * [value] abstract class OuterObjectWithEnumProperty implements Built { @BuiltValueField(wireName: r'value') OuterEnumInteger get value; diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/pet.dart b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/pet.dart index 99ef939eb1b..ea94306056c 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/pet.dart +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/pet.dart @@ -10,8 +10,15 @@ import 'package:built_value/serializer.dart'; part 'pet.g.dart'; - - +/// Pet +/// +/// Properties: +/// * [id] +/// * [category] +/// * [name] +/// * [photoUrls] +/// * [tags] +/// * [status] - pet status in the store abstract class Pet implements Built { @BuiltValueField(wireName: r'id') int? get id; diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/read_only_first.dart b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/read_only_first.dart index d53617d1c0b..ce46f919ea3 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/read_only_first.dart +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/read_only_first.dart @@ -7,8 +7,11 @@ import 'package:built_value/serializer.dart'; part 'read_only_first.g.dart'; - - +/// ReadOnlyFirst +/// +/// Properties: +/// * [bar] +/// * [baz] abstract class ReadOnlyFirst implements Built { @BuiltValueField(wireName: r'bar') String? get bar; diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/special_model_name.dart b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/special_model_name.dart index 36880f32998..dc69b29e496 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/special_model_name.dart +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/special_model_name.dart @@ -7,8 +7,10 @@ import 'package:built_value/serializer.dart'; part 'special_model_name.g.dart'; - - +/// SpecialModelName +/// +/// Properties: +/// * [dollarSpecialLeftSquareBracketPropertyPeriodNameRightSquareBracket] abstract class SpecialModelName implements Built { @BuiltValueField(wireName: r'$special[property.name]') int? get dollarSpecialLeftSquareBracketPropertyPeriodNameRightSquareBracket; diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/tag.dart b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/tag.dart index d46c2aa4045..6723a6ea9f2 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/tag.dart +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/tag.dart @@ -7,8 +7,11 @@ import 'package:built_value/serializer.dart'; part 'tag.g.dart'; - - +/// Tag +/// +/// Properties: +/// * [id] +/// * [name] abstract class Tag implements Built { @BuiltValueField(wireName: r'id') int? get id; diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/user.dart b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/user.dart index dec21c7e473..8aeb8f43ade 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/user.dart +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/model/user.dart @@ -7,8 +7,17 @@ import 'package:built_value/serializer.dart'; part 'user.g.dart'; - - +/// User +/// +/// Properties: +/// * [id] +/// * [username] +/// * [firstName] +/// * [lastName] +/// * [email] +/// * [password] +/// * [phone] +/// * [userStatus] - User Status abstract class User implements Built { @BuiltValueField(wireName: r'id') int? get id; diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/pom.xml b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/pom.xml index 86285381f97..dec7604a53a 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/pom.xml +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/pom.xml @@ -39,26 +39,6 @@ - - format - pre-integration-test - - exec - - - dart - - format - - --output=none - . - - - pub-run-build-runner pre-integration-test diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/pubspec.yaml b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/pubspec.yaml index 4a109ee28d3..2a62f274f36 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/pubspec.yaml +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/pubspec.yaml @@ -2,8 +2,6 @@ name: openapi version: 1.0.0 description: OpenAPI API client homepage: homepage -authors: - - 'Author ' environment: sdk: '>=2.12.0 <3.0.0' diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake_tests/pubspec.yaml b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake_tests/pubspec.yaml index 6c33286cb5a..398c6a07470 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake_tests/pubspec.yaml +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake_tests/pubspec.yaml @@ -8,11 +8,11 @@ environment: sdk: '>=2.10.0 <3.0.0' dev_dependencies: - built_collection: '5.0.0' - built_value: '8.0.4' - dio: '4.0.0' + built_collection: 5.0.0 + built_value: 8.0.6 + dio: 4.0.0 http_mock_adapter: 0.2.1 - mockito: '5.0.3' + mockito: 5.0.8 openapi: path: ../petstore_client_lib_fake - test: '1.16.8' + test: 1.17.4 diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake_tests/test/api/fake_api_test.dart b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake_tests/test/api/fake_api_test.dart index e1a40f57fe5..180815a69f1 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake_tests/test/api/fake_api_test.dart +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake_tests/test/api/fake_api_test.dart @@ -2,10 +2,13 @@ import 'dart:typed_data'; import 'package:built_collection/built_collection.dart'; import 'package:dio/dio.dart'; +import 'package:dio/src/parameter.dart'; import 'package:http_mock_adapter/http_mock_adapter.dart'; import 'package:openapi/openapi.dart'; import 'package:test/test.dart'; +import '../matcher/list_param_matcher.dart'; + void main() { Openapi client; DioAdapter server; @@ -36,7 +39,7 @@ void main() { 'int64': '9223372036854775807', 'date': '2020-08-11', 'dateTime': '2020-08-11T12:30:55.123Z', - 'binary': "Instance of 'MultipartFile'", + 'binary': '[0, 1, 2, 3, 4, 5]', }, headers: { 'content-type': 'application/x-www-form-urlencoded', @@ -97,7 +100,20 @@ void main() { (request) => request.reply(200, null), data: { 'enum_form_string': 'formString', - 'enum_form_string_array': '[foo, bar]', + 'enum_form_string_array': ListParamMatcher( + expected: ListParam( + ['foo', 'bar'], + ListFormat.csv, + ), + ), + }, + queryParameters: { + 'enum_query_string_array': ListParamMatcher( + expected: ListParam( + ['a', 'b', 'c'], + ListFormat.multi, + ), + ), }, headers: { 'content-type': 'application/x-www-form-urlencoded', @@ -105,6 +121,9 @@ void main() { ); final response = await client.getFakeApi().testEnumParameters( + enumQueryStringArray: ListBuilder( + ['a', 'b', 'c'], + ).build(), enumFormString: 'formString', enumFormStringArray: ListBuilder( ['foo', 'bar'], diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake_tests/test/api/pet_api_test.dart b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake_tests/test/api/pet_api_test.dart index 5aae7639fda..1ae3964851d 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake_tests/test/api/pet_api_test.dart +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake_tests/test/api/pet_api_test.dart @@ -1,9 +1,14 @@ import 'package:built_collection/built_collection.dart'; import 'package:dio/dio.dart'; +import 'package:dio/src/parameter.dart'; import 'package:http_mock_adapter/http_mock_adapter.dart'; +import 'package:http_parser/http_parser.dart'; import 'package:openapi/openapi.dart'; import 'package:test/test.dart'; +import '../matcher/form_data_matcher.dart'; +import '../matcher/list_param_matcher.dart'; + void main() { const photo1 = 'https://localhost/photo1.jpg'; const photo2 = 'https://localhost/photo2.jpg'; @@ -192,10 +197,12 @@ void main() { request: Request( method: RequestMethods.get, queryParameters: { - 'status': [ - 'available', - 'sold', - ], + 'status': ListParamMatcher( + expected: ListParam( + ['available', 'sold'], + ListFormat.csv, + ), + ), }, headers: { Headers.contentTypeHeader: Matchers.pattern('application/json'), @@ -221,5 +228,83 @@ void main() { expect(response.data[1].status, PetStatusEnum.available); }); }); + + group('uploadFile', () { + test('uploadFileWithRequiredFile', () async { + final file = MultipartFile.fromBytes( + [1, 2, 3, 4], + filename: 'test.png', + contentType: MediaType.parse('image/png'), + ); + + server.onRoute( + '/fake/5/uploadImageWithRequiredFile', + (request) => request.reply(200, { + 'code': 200, + 'type': 'success', + 'message': 'File uploaded', + }), + request: Request( + method: RequestMethods.post, + headers: { + Headers.contentTypeHeader: + Matchers.pattern('multipart/form-data'), + Headers.contentLengthHeader: Matchers.integer, + }, + data: FormDataMatcher( + expected: FormData.fromMap({ + r'requiredFile': file, + }), + ), + ), + ); + final response = await client.getPetApi().uploadFileWithRequiredFile( + petId: 5, + requiredFile: file, + ); + + expect(response.statusCode, 200); + expect(response.data.message, 'File uploaded'); + }); + + test('uploadFileWithRequiredFile & additionalMetadata', () async { + final file = MultipartFile.fromBytes( + [1, 2, 3, 4], + filename: 'test.png', + contentType: MediaType.parse('image/png'), + ); + + server.onRoute( + '/fake/3/uploadImageWithRequiredFile', + (request) => request.reply(200, { + 'code': 200, + 'type': 'success', + 'message': 'File uploaded', + }), + request: Request( + method: RequestMethods.post, + headers: { + Headers.contentTypeHeader: + Matchers.pattern('multipart/form-data'), + Headers.contentLengthHeader: Matchers.integer, + }, + data: FormDataMatcher( + expected: FormData.fromMap({ + 'additionalMetadata': 'foo', + r'requiredFile': file, + }), + ), + ), + ); + final response = await client.getPetApi().uploadFileWithRequiredFile( + petId: 3, + requiredFile: file, + additionalMetadata: 'foo', + ); + + expect(response.statusCode, 200); + expect(response.data.message, 'File uploaded'); + }); + }); }); } diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake_tests/test/matcher/form_data_matcher.dart b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake_tests/test/matcher/form_data_matcher.dart new file mode 100644 index 00000000000..8e0a7a6c032 --- /dev/null +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake_tests/test/matcher/form_data_matcher.dart @@ -0,0 +1,26 @@ +import 'package:dio/dio.dart'; +import 'package:meta/meta.dart'; +import 'package:collection/collection.dart'; +import 'package:http_mock_adapter/src/matchers/matcher.dart'; + +class FormDataMatcher extends Matcher { + final FormData expected; + + const FormDataMatcher({@required this.expected}); + + @override + bool matches(dynamic actual) { + if (actual is! FormData) { + return false; + } + final data = actual as FormData; + return MapEquality().equals( + Map.fromEntries(expected.fields), + Map.fromEntries(data.fields), + ) && + MapEquality().equals( + Map.fromEntries(expected.files), + Map.fromEntries(data.files), + ); + } +} diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake_tests/test/matcher/list_param_matcher.dart b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake_tests/test/matcher/list_param_matcher.dart new file mode 100644 index 00000000000..649ef67ccec --- /dev/null +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake_tests/test/matcher/list_param_matcher.dart @@ -0,0 +1,20 @@ +import 'package:dio/src/parameter.dart'; +import 'package:meta/meta.dart'; +import 'package:collection/collection.dart'; +import 'package:http_mock_adapter/src/matchers/matcher.dart'; + +class ListParamMatcher extends Matcher { + final ListParam expected; + + const ListParamMatcher({@required this.expected}); + + @override + bool matches(dynamic actual) { + return actual is ListParam && + ListEquality().equals( + actual.value, + expected.value, + ) && + actual.format == expected.format; + } +} diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake_tests/test/model/date_serializer_test.dart b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake_tests/test/model/date_serializer_test.dart index acae38e3d90..9422fe8e47d 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake_tests/test/model/date_serializer_test.dart +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake_tests/test/model/date_serializer_test.dart @@ -8,15 +8,24 @@ void main() { group(DateSerializer, () { test('serialize', () { - expect(serializer.serialize(serializers, date1), '1999-03-25'); + expect( + serializer.serialize(serializers, date1), + '1999-03-25', + ); }); test('deserialize date', () { - expect(serializer.deserialize(serializers, '1999-03-25'), date1); + expect( + serializer.deserialize(serializers, '1999-03-25'), + date1, + ); }); test('deserialize ISO', () { - expect(serializer.deserialize(serializers, '1999-03-25T12:30:55.123Z'), date1); + expect( + serializer.deserialize(serializers, '1999-03-25T12:30:55.123Z'), + date1, + ); }); }); } diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/.gitignore b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/.gitignore index 8092a49d515..6d2ac22c0b4 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/.gitignore +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/.gitignore @@ -30,8 +30,12 @@ pubspec.lock # Don’t commit files and directories created by other development environments. # For example, if your development environment creates any of the following files, # consider putting them in a global ignore file: -*.iml // IntelliJ -*.ipr // IntelliJ -*.iws // IntelliJ -.idea/ // IntelliJ -.DS_Store // Mac + +# IntelliJ +*.iml +*.ipr +*.iws +.idea/ + +# Mac +.DS_Store diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/.openapi-generator/VERSION b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/.openapi-generator/VERSION +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/README.md b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/README.md index af1b22de4d5..ac04fa9f72b 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/README.md +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/README.md @@ -58,26 +58,26 @@ All URIs are relative to *http://petstore.swagger.io/v2* Class | Method | HTTP request | Description ------------ | ------------- | ------------- | ------------- -*PetApi* | [**addPet**](doc/PetApi.md#addpet) | **post** /pet | Add a new pet to the store -*PetApi* | [**deletePet**](doc/PetApi.md#deletepet) | **delete** /pet/{petId} | Deletes a pet -*PetApi* | [**findPetsByStatus**](doc/PetApi.md#findpetsbystatus) | **get** /pet/findByStatus | Finds Pets by status -*PetApi* | [**findPetsByTags**](doc/PetApi.md#findpetsbytags) | **get** /pet/findByTags | Finds Pets by tags -*PetApi* | [**getPetById**](doc/PetApi.md#getpetbyid) | **get** /pet/{petId} | Find pet by ID -*PetApi* | [**updatePet**](doc/PetApi.md#updatepet) | **put** /pet | Update an existing pet -*PetApi* | [**updatePetWithForm**](doc/PetApi.md#updatepetwithform) | **post** /pet/{petId} | Updates a pet in the store with form data -*PetApi* | [**uploadFile**](doc/PetApi.md#uploadfile) | **post** /pet/{petId}/uploadImage | uploads an image -*StoreApi* | [**deleteOrder**](doc/StoreApi.md#deleteorder) | **delete** /store/order/{orderId} | Delete purchase order by ID -*StoreApi* | [**getInventory**](doc/StoreApi.md#getinventory) | **get** /store/inventory | Returns pet inventories by status -*StoreApi* | [**getOrderById**](doc/StoreApi.md#getorderbyid) | **get** /store/order/{orderId} | Find purchase order by ID -*StoreApi* | [**placeOrder**](doc/StoreApi.md#placeorder) | **post** /store/order | Place an order for a pet -*UserApi* | [**createUser**](doc/UserApi.md#createuser) | **post** /user | Create user -*UserApi* | [**createUsersWithArrayInput**](doc/UserApi.md#createuserswitharrayinput) | **post** /user/createWithArray | Creates list of users with given input array -*UserApi* | [**createUsersWithListInput**](doc/UserApi.md#createuserswithlistinput) | **post** /user/createWithList | Creates list of users with given input array -*UserApi* | [**deleteUser**](doc/UserApi.md#deleteuser) | **delete** /user/{username} | Delete user -*UserApi* | [**getUserByName**](doc/UserApi.md#getuserbyname) | **get** /user/{username} | Get user by user name -*UserApi* | [**loginUser**](doc/UserApi.md#loginuser) | **get** /user/login | Logs user into the system -*UserApi* | [**logoutUser**](doc/UserApi.md#logoutuser) | **get** /user/logout | Logs out current logged in user session -*UserApi* | [**updateUser**](doc/UserApi.md#updateuser) | **put** /user/{username} | Updated user +*PetApi* | [**addPet**](doc/PetApi.md#addpet) | **POST** /pet | Add a new pet to the store +*PetApi* | [**deletePet**](doc/PetApi.md#deletepet) | **DELETE** /pet/{petId} | Deletes a pet +*PetApi* | [**findPetsByStatus**](doc/PetApi.md#findpetsbystatus) | **GET** /pet/findByStatus | Finds Pets by status +*PetApi* | [**findPetsByTags**](doc/PetApi.md#findpetsbytags) | **GET** /pet/findByTags | Finds Pets by tags +*PetApi* | [**getPetById**](doc/PetApi.md#getpetbyid) | **GET** /pet/{petId} | Find pet by ID +*PetApi* | [**updatePet**](doc/PetApi.md#updatepet) | **PUT** /pet | Update an existing pet +*PetApi* | [**updatePetWithForm**](doc/PetApi.md#updatepetwithform) | **POST** /pet/{petId} | Updates a pet in the store with form data +*PetApi* | [**uploadFile**](doc/PetApi.md#uploadfile) | **POST** /pet/{petId}/uploadImage | uploads an image +*StoreApi* | [**deleteOrder**](doc/StoreApi.md#deleteorder) | **DELETE** /store/order/{orderId} | Delete purchase order by ID +*StoreApi* | [**getInventory**](doc/StoreApi.md#getinventory) | **GET** /store/inventory | Returns pet inventories by status +*StoreApi* | [**getOrderById**](doc/StoreApi.md#getorderbyid) | **GET** /store/order/{orderId} | Find purchase order by ID +*StoreApi* | [**placeOrder**](doc/StoreApi.md#placeorder) | **POST** /store/order | Place an order for a pet +*UserApi* | [**createUser**](doc/UserApi.md#createuser) | **POST** /user | Create user +*UserApi* | [**createUsersWithArrayInput**](doc/UserApi.md#createuserswitharrayinput) | **POST** /user/createWithArray | Creates list of users with given input array +*UserApi* | [**createUsersWithListInput**](doc/UserApi.md#createuserswithlistinput) | **POST** /user/createWithList | Creates list of users with given input array +*UserApi* | [**deleteUser**](doc/UserApi.md#deleteuser) | **DELETE** /user/{username} | Delete user +*UserApi* | [**getUserByName**](doc/UserApi.md#getuserbyname) | **GET** /user/{username} | Get user by user name +*UserApi* | [**loginUser**](doc/UserApi.md#loginuser) | **GET** /user/login | Logs user into the system +*UserApi* | [**logoutUser**](doc/UserApi.md#logoutuser) | **GET** /user/logout | Logs out current logged in user session +*UserApi* | [**updateUser**](doc/UserApi.md#updateuser) | **PUT** /user/{username} | Updated user ## Documentation For Models diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/doc/PetApi.md b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/doc/PetApi.md index 3a78296f383..74c87b72acc 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/doc/PetApi.md +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/doc/PetApi.md @@ -9,14 +9,14 @@ 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**](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** diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/doc/StoreApi.md b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/doc/StoreApi.md index 0b016d70a84..6075223c741 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/doc/StoreApi.md +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/doc/StoreApi.md @@ -9,10 +9,10 @@ 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**](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** diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/doc/UserApi.md b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/doc/UserApi.md index c939d874a99..b3b11fe6748 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/doc/UserApi.md +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/doc/UserApi.md @@ -9,14 +9,14 @@ 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**](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** diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/lib/api/pet_api.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/lib/api/pet_api.dart index 9b378a4b3fa..70fc2b2dbe6 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/lib/api/pet_api.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/lib/api/pet_api.dart @@ -51,10 +51,7 @@ class PetApi { ...?extra, }, validateStatus: validateStatus, - contentType: [ - 'application/json', - 'application/xml', - ].first, + contentType: 'application/json', cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, @@ -119,9 +116,7 @@ class PetApi { ...?extra, }, validateStatus: validateStatus, - contentType: [ - 'application/json', - ].first, + contentType: 'application/json', cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, @@ -169,9 +164,7 @@ class PetApi { ...?extra, }, validateStatus: validateStatus, - contentType: [ - 'application/json', - ].first, + contentType: 'application/json', cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, @@ -234,9 +227,7 @@ class PetApi { ...?extra, }, validateStatus: validateStatus, - contentType: [ - 'application/json', - ].first, + contentType: 'application/json', cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, @@ -298,9 +289,7 @@ class PetApi { ...?extra, }, validateStatus: validateStatus, - contentType: [ - 'application/json', - ].first, + contentType: 'application/json', cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, @@ -360,10 +349,7 @@ class PetApi { ...?extra, }, validateStatus: validateStatus, - contentType: [ - 'application/json', - 'application/xml', - ].first, + contentType: 'application/json', cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, @@ -428,9 +414,7 @@ class PetApi { ...?extra, }, validateStatus: validateStatus, - contentType: [ - 'application/x-www-form-urlencoded', - ].first, + contentType: 'application/x-www-form-urlencoded', cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, @@ -482,9 +466,7 @@ class PetApi { ...?extra, }, validateStatus: validateStatus, - contentType: [ - 'multipart/form-data', - ].first, + contentType: 'multipart/form-data', cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/lib/api/store_api.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/lib/api/store_api.dart index d0184f6eda8..80b074645c8 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/lib/api/store_api.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/lib/api/store_api.dart @@ -43,9 +43,7 @@ class StoreApi { ...?extra, }, validateStatus: validateStatus, - contentType: [ - 'application/json', - ].first, + contentType: 'application/json', cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, @@ -91,9 +89,7 @@ class StoreApi { ...?extra, }, validateStatus: validateStatus, - contentType: [ - 'application/json', - ].first, + contentType: 'application/json', cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, @@ -148,9 +144,7 @@ class StoreApi { ...?extra, }, validateStatus: validateStatus, - contentType: [ - 'application/json', - ].first, + contentType: 'application/json', cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, @@ -205,9 +199,7 @@ class StoreApi { ...?extra, }, validateStatus: validateStatus, - contentType: [ - 'application/json', - ].first, + contentType: 'application/json', cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/lib/api/user_api.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/lib/api/user_api.dart index 5253ac66028..fef22be0b97 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/lib/api/user_api.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/lib/api/user_api.dart @@ -50,9 +50,7 @@ class UserApi { ...?extra, }, validateStatus: validateStatus, - contentType: [ - 'application/json', - ].first, + contentType: 'application/json', cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, @@ -102,9 +100,7 @@ class UserApi { ...?extra, }, validateStatus: validateStatus, - contentType: [ - 'application/json', - ].first, + contentType: 'application/json', cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, @@ -154,9 +150,7 @@ class UserApi { ...?extra, }, validateStatus: validateStatus, - contentType: [ - 'application/json', - ].first, + contentType: 'application/json', cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, @@ -206,9 +200,7 @@ class UserApi { ...?extra, }, validateStatus: validateStatus, - contentType: [ - 'application/json', - ].first, + contentType: 'application/json', cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, @@ -248,9 +240,7 @@ class UserApi { ...?extra, }, validateStatus: validateStatus, - contentType: [ - 'application/json', - ].first, + contentType: 'application/json', cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, @@ -310,9 +300,7 @@ class UserApi { ...?extra, }, validateStatus: validateStatus, - contentType: [ - 'application/json', - ].first, + contentType: 'application/json', cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, @@ -369,9 +357,7 @@ class UserApi { ...?extra, }, validateStatus: validateStatus, - contentType: [ - 'application/json', - ].first, + contentType: 'application/json', cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, @@ -419,9 +405,7 @@ class UserApi { ...?extra, }, validateStatus: validateStatus, - contentType: [ - 'application/json', - ].first, + contentType: 'application/json', cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/pubspec.yaml b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/pubspec.yaml index 3182395f579..34a1aa76180 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/pubspec.yaml +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib/pubspec.yaml @@ -2,8 +2,6 @@ name: openapi version: 1.0.0 description: OpenAPI API client homepage: homepage -authors: - - 'Author ' environment: sdk: '>=2.7.0 <3.0.0' diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/.gitignore b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/.gitignore index 8092a49d515..6d2ac22c0b4 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/.gitignore +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/.gitignore @@ -30,8 +30,12 @@ pubspec.lock # Don’t commit files and directories created by other development environments. # For example, if your development environment creates any of the following files, # consider putting them in a global ignore file: -*.iml // IntelliJ -*.ipr // IntelliJ -*.iws // IntelliJ -.idea/ // IntelliJ -.DS_Store // Mac + +# IntelliJ +*.iml +*.ipr +*.iws +.idea/ + +# Mac +.DS_Store 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 5f68295fc19..e8415097f3a 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,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x 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 af00b20ee1d..b1d9fbe962c 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 @@ -58,46 +58,47 @@ All URIs are relative to *http://petstore.swagger.io:80/v2* Class | Method | HTTP request | Description ------------ | ------------- | ------------- | ------------- -*AnotherFakeApi* | [**call123testSpecialTags**](doc/AnotherFakeApi.md#call123testspecialtags) | **patch** /another-fake/dummy | To test special tags -*DefaultApi* | [**fooGet**](doc/DefaultApi.md#fooget) | **get** /foo | -*FakeApi* | [**fakeHealthGet**](doc/FakeApi.md#fakehealthget) | **get** /fake/health | Health check endpoint -*FakeApi* | [**fakeHttpSignatureTest**](doc/FakeApi.md#fakehttpsignaturetest) | **get** /fake/http-signature-test | test http signature authentication -*FakeApi* | [**fakeOuterBooleanSerialize**](doc/FakeApi.md#fakeouterbooleanserialize) | **post** /fake/outer/boolean | -*FakeApi* | [**fakeOuterCompositeSerialize**](doc/FakeApi.md#fakeoutercompositeserialize) | **post** /fake/outer/composite | -*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* | [**testBodyWithFileSchema**](doc/FakeApi.md#testbodywithfileschema) | **put** /fake/body-with-file-schema | -*FakeApi* | [**testBodyWithQueryParams**](doc/FakeApi.md#testbodywithqueryparams) | **put** /fake/body-with-query-params | -*FakeApi* | [**testClientModel**](doc/FakeApi.md#testclientmodel) | **patch** /fake | To test \"client\" model -*FakeApi* | [**testEndpointParameters**](doc/FakeApi.md#testendpointparameters) | **post** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 -*FakeApi* | [**testEnumParameters**](doc/FakeApi.md#testenumparameters) | **get** /fake | To test enum parameters -*FakeApi* | [**testGroupParameters**](doc/FakeApi.md#testgroupparameters) | **delete** /fake | Fake endpoint to test group parameters (optional) -*FakeApi* | [**testInlineAdditionalProperties**](doc/FakeApi.md#testinlineadditionalproperties) | **post** /fake/inline-additionalProperties | test inline additionalProperties -*FakeApi* | [**testJsonFormData**](doc/FakeApi.md#testjsonformdata) | **get** /fake/jsonFormData | test json serialization of form data -*FakeApi* | [**testQueryParameterCollectionFormat**](doc/FakeApi.md#testqueryparametercollectionformat) | **put** /fake/test-query-paramters | -*FakeClassnameTags123Api* | [**testClassname**](doc/FakeClassnameTags123Api.md#testclassname) | **patch** /fake_classname_test | To test class name in snake case -*PetApi* | [**addPet**](doc/PetApi.md#addpet) | **post** /pet | Add a new pet to the store -*PetApi* | [**deletePet**](doc/PetApi.md#deletepet) | **delete** /pet/{petId} | Deletes a pet -*PetApi* | [**findPetsByStatus**](doc/PetApi.md#findpetsbystatus) | **get** /pet/findByStatus | Finds Pets by status -*PetApi* | [**findPetsByTags**](doc/PetApi.md#findpetsbytags) | **get** /pet/findByTags | Finds Pets by tags -*PetApi* | [**getPetById**](doc/PetApi.md#getpetbyid) | **get** /pet/{petId} | Find pet by ID -*PetApi* | [**updatePet**](doc/PetApi.md#updatepet) | **put** /pet | Update an existing pet -*PetApi* | [**updatePetWithForm**](doc/PetApi.md#updatepetwithform) | **post** /pet/{petId} | Updates a pet in the store with form data -*PetApi* | [**uploadFile**](doc/PetApi.md#uploadfile) | **post** /pet/{petId}/uploadImage | uploads an image -*PetApi* | [**uploadFileWithRequiredFile**](doc/PetApi.md#uploadfilewithrequiredfile) | **post** /fake/{petId}/uploadImageWithRequiredFile | uploads an image (required) -*StoreApi* | [**deleteOrder**](doc/StoreApi.md#deleteorder) | **delete** /store/order/{order_id} | Delete purchase order by ID -*StoreApi* | [**getInventory**](doc/StoreApi.md#getinventory) | **get** /store/inventory | Returns pet inventories by status -*StoreApi* | [**getOrderById**](doc/StoreApi.md#getorderbyid) | **get** /store/order/{order_id} | Find purchase order by ID -*StoreApi* | [**placeOrder**](doc/StoreApi.md#placeorder) | **post** /store/order | Place an order for a pet -*UserApi* | [**createUser**](doc/UserApi.md#createuser) | **post** /user | Create user -*UserApi* | [**createUsersWithArrayInput**](doc/UserApi.md#createuserswitharrayinput) | **post** /user/createWithArray | Creates list of users with given input array -*UserApi* | [**createUsersWithListInput**](doc/UserApi.md#createuserswithlistinput) | **post** /user/createWithList | Creates list of users with given input array -*UserApi* | [**deleteUser**](doc/UserApi.md#deleteuser) | **delete** /user/{username} | Delete user -*UserApi* | [**getUserByName**](doc/UserApi.md#getuserbyname) | **get** /user/{username} | Get user by user name -*UserApi* | [**loginUser**](doc/UserApi.md#loginuser) | **get** /user/login | Logs user into the system -*UserApi* | [**logoutUser**](doc/UserApi.md#logoutuser) | **get** /user/logout | Logs out current logged in user session -*UserApi* | [**updateUser**](doc/UserApi.md#updateuser) | **put** /user/{username} | Updated user +*AnotherFakeApi* | [**call123testSpecialTags**](doc/AnotherFakeApi.md#call123testspecialtags) | **PATCH** /another-fake/dummy | To test special tags +*DefaultApi* | [**fooGet**](doc/DefaultApi.md#fooget) | **GET** /foo | +*FakeApi* | [**fakeHealthGet**](doc/FakeApi.md#fakehealthget) | **GET** /fake/health | Health check endpoint +*FakeApi* | [**fakeHttpSignatureTest**](doc/FakeApi.md#fakehttpsignaturetest) | **GET** /fake/http-signature-test | test http signature authentication +*FakeApi* | [**fakeOuterBooleanSerialize**](doc/FakeApi.md#fakeouterbooleanserialize) | **POST** /fake/outer/boolean | +*FakeApi* | [**fakeOuterCompositeSerialize**](doc/FakeApi.md#fakeoutercompositeserialize) | **POST** /fake/outer/composite | +*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* | [**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 | +*FakeApi* | [**testClientModel**](doc/FakeApi.md#testclientmodel) | **PATCH** /fake | To test \"client\" model +*FakeApi* | [**testEndpointParameters**](doc/FakeApi.md#testendpointparameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 +*FakeApi* | [**testEnumParameters**](doc/FakeApi.md#testenumparameters) | **GET** /fake | To test enum parameters +*FakeApi* | [**testGroupParameters**](doc/FakeApi.md#testgroupparameters) | **DELETE** /fake | Fake endpoint to test group parameters (optional) +*FakeApi* | [**testInlineAdditionalProperties**](doc/FakeApi.md#testinlineadditionalproperties) | **POST** /fake/inline-additionalProperties | test inline additionalProperties +*FakeApi* | [**testJsonFormData**](doc/FakeApi.md#testjsonformdata) | **GET** /fake/jsonFormData | test json serialization of form data +*FakeApi* | [**testQueryParameterCollectionFormat**](doc/FakeApi.md#testqueryparametercollectionformat) | **PUT** /fake/test-query-paramters | +*FakeClassnameTags123Api* | [**testClassname**](doc/FakeClassnameTags123Api.md#testclassname) | **PATCH** /fake_classname_test | To test class name in snake case +*PetApi* | [**addPet**](doc/PetApi.md#addpet) | **POST** /pet | Add a new pet to the store +*PetApi* | [**deletePet**](doc/PetApi.md#deletepet) | **DELETE** /pet/{petId} | Deletes a pet +*PetApi* | [**findPetsByStatus**](doc/PetApi.md#findpetsbystatus) | **GET** /pet/findByStatus | Finds Pets by status +*PetApi* | [**findPetsByTags**](doc/PetApi.md#findpetsbytags) | **GET** /pet/findByTags | Finds Pets by tags +*PetApi* | [**getPetById**](doc/PetApi.md#getpetbyid) | **GET** /pet/{petId} | Find pet by ID +*PetApi* | [**updatePet**](doc/PetApi.md#updatepet) | **PUT** /pet | Update an existing pet +*PetApi* | [**updatePetWithForm**](doc/PetApi.md#updatepetwithform) | **POST** /pet/{petId} | Updates a pet in the store with form data +*PetApi* | [**uploadFile**](doc/PetApi.md#uploadfile) | **POST** /pet/{petId}/uploadImage | uploads an image +*PetApi* | [**uploadFileWithRequiredFile**](doc/PetApi.md#uploadfilewithrequiredfile) | **POST** /fake/{petId}/uploadImageWithRequiredFile | uploads an image (required) +*StoreApi* | [**deleteOrder**](doc/StoreApi.md#deleteorder) | **DELETE** /store/order/{order_id} | Delete purchase order by ID +*StoreApi* | [**getInventory**](doc/StoreApi.md#getinventory) | **GET** /store/inventory | Returns pet inventories by status +*StoreApi* | [**getOrderById**](doc/StoreApi.md#getorderbyid) | **GET** /store/order/{order_id} | Find purchase order by ID +*StoreApi* | [**placeOrder**](doc/StoreApi.md#placeorder) | **POST** /store/order | Place an order for a pet +*UserApi* | [**createUser**](doc/UserApi.md#createuser) | **POST** /user | Create user +*UserApi* | [**createUsersWithArrayInput**](doc/UserApi.md#createuserswitharrayinput) | **POST** /user/createWithArray | Creates list of users with given input array +*UserApi* | [**createUsersWithListInput**](doc/UserApi.md#createuserswithlistinput) | **POST** /user/createWithList | Creates list of users with given input array +*UserApi* | [**deleteUser**](doc/UserApi.md#deleteuser) | **DELETE** /user/{username} | Delete user +*UserApi* | [**getUserByName**](doc/UserApi.md#getuserbyname) | **GET** /user/{username} | Get user by user name +*UserApi* | [**loginUser**](doc/UserApi.md#loginuser) | **GET** /user/login | Logs user into the system +*UserApi* | [**logoutUser**](doc/UserApi.md#logoutuser) | **GET** /user/logout | Logs out current logged in user session +*UserApi* | [**updateUser**](doc/UserApi.md#updateuser) | **PUT** /user/{username} | Updated user ## Documentation For Models diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/doc/AnotherFakeApi.md b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/doc/AnotherFakeApi.md index d55663297c1..bb401f7c20c 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/doc/AnotherFakeApi.md +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/doc/AnotherFakeApi.md @@ -9,7 +9,7 @@ All URIs are relative to *http://petstore.swagger.io:80/v2* Method | HTTP request | Description ------------- | ------------- | ------------- -[**call123testSpecialTags**](AnotherFakeApi.md#call123testspecialtags) | **patch** /another-fake/dummy | To test special tags +[**call123testSpecialTags**](AnotherFakeApi.md#call123testspecialtags) | **PATCH** /another-fake/dummy | To test special tags # **call123testSpecialTags** diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/doc/DefaultApi.md b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/doc/DefaultApi.md index be916c3037d..5c305ecaa71 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/doc/DefaultApi.md +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/doc/DefaultApi.md @@ -9,7 +9,7 @@ All URIs are relative to *http://petstore.swagger.io:80/v2* Method | HTTP request | Description ------------- | ------------- | ------------- -[**fooGet**](DefaultApi.md#fooget) | **get** /foo | +[**fooGet**](DefaultApi.md#fooget) | **GET** /foo | # **fooGet** 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 41ab4e4fc12..da4601dbec5 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 @@ -9,22 +9,23 @@ All URIs are relative to *http://petstore.swagger.io:80/v2* Method | HTTP request | Description ------------- | ------------- | ------------- -[**fakeHealthGet**](FakeApi.md#fakehealthget) | **get** /fake/health | Health check endpoint -[**fakeHttpSignatureTest**](FakeApi.md#fakehttpsignaturetest) | **get** /fake/http-signature-test | test http signature authentication -[**fakeOuterBooleanSerialize**](FakeApi.md#fakeouterbooleanserialize) | **post** /fake/outer/boolean | -[**fakeOuterCompositeSerialize**](FakeApi.md#fakeoutercompositeserialize) | **post** /fake/outer/composite | -[**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 | -[**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 -[**testEndpointParameters**](FakeApi.md#testendpointparameters) | **post** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 -[**testEnumParameters**](FakeApi.md#testenumparameters) | **get** /fake | To test enum parameters -[**testGroupParameters**](FakeApi.md#testgroupparameters) | **delete** /fake | Fake endpoint to test group parameters (optional) -[**testInlineAdditionalProperties**](FakeApi.md#testinlineadditionalproperties) | **post** /fake/inline-additionalProperties | test inline additionalProperties -[**testJsonFormData**](FakeApi.md#testjsonformdata) | **get** /fake/jsonFormData | test json serialization of form data -[**testQueryParameterCollectionFormat**](FakeApi.md#testqueryparametercollectionformat) | **put** /fake/test-query-paramters | +[**fakeHealthGet**](FakeApi.md#fakehealthget) | **GET** /fake/health | Health check endpoint +[**fakeHttpSignatureTest**](FakeApi.md#fakehttpsignaturetest) | **GET** /fake/http-signature-test | test http signature authentication +[**fakeOuterBooleanSerialize**](FakeApi.md#fakeouterbooleanserialize) | **POST** /fake/outer/boolean | +[**fakeOuterCompositeSerialize**](FakeApi.md#fakeoutercompositeserialize) | **POST** /fake/outer/composite | +[**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 | +[**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 | +[**testClientModel**](FakeApi.md#testclientmodel) | **PATCH** /fake | To test \"client\" model +[**testEndpointParameters**](FakeApi.md#testendpointparameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 +[**testEnumParameters**](FakeApi.md#testenumparameters) | **GET** /fake | To test enum parameters +[**testGroupParameters**](FakeApi.md#testgroupparameters) | **DELETE** /fake | Fake endpoint to test group parameters (optional) +[**testInlineAdditionalProperties**](FakeApi.md#testinlineadditionalproperties) | **POST** /fake/inline-additionalProperties | test inline additionalProperties +[**testJsonFormData**](FakeApi.md#testjsonformdata) | **GET** /fake/jsonFormData | test json serialization of form data +[**testQueryParameterCollectionFormat**](FakeApi.md#testqueryparametercollectionformat) | **PUT** /fake/test-query-paramters | # **fakeHealthGet** @@ -326,12 +327,54 @@ 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) +# **testBodyWithBinary** +> testBodyWithBinary(body) + + + +For this test, the body has to be a binary file. + +### Example +```dart +import 'package:openapi/api.dart'; + +var api_instance = new FakeApi(); +var body = new Uint8List(); // Uint8List | image to upload + +try { + api_instance.testBodyWithBinary(body); +} catch (e) { + print('Exception when calling FakeApi->testBodyWithBinary: $e\n'); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | **Uint8List**| image to upload | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: image/png + - **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(fileSchemaTestClass) -For this test, the body for this request much reference a schema named `File`. +For this test, the body for this request must reference a schema named `File`. ### Example ```dart diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/doc/FakeClassnameTags123Api.md b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/doc/FakeClassnameTags123Api.md index 9745ca8e3ff..98fe0b47358 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/doc/FakeClassnameTags123Api.md +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/doc/FakeClassnameTags123Api.md @@ -9,7 +9,7 @@ All URIs are relative to *http://petstore.swagger.io:80/v2* Method | HTTP request | Description ------------- | ------------- | ------------- -[**testClassname**](FakeClassnameTags123Api.md#testclassname) | **patch** /fake_classname_test | To test class name in snake case +[**testClassname**](FakeClassnameTags123Api.md#testclassname) | **PATCH** /fake_classname_test | To test class name in snake case # **testClassname** diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/doc/PetApi.md b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/doc/PetApi.md index d5a07d5046e..841eed63291 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/doc/PetApi.md +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/doc/PetApi.md @@ -9,15 +9,15 @@ All URIs are relative to *http://petstore.swagger.io:80/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 -[**uploadFileWithRequiredFile**](PetApi.md#uploadfilewithrequiredfile) | **post** /fake/{petId}/uploadImageWithRequiredFile | uploads an image (required) +[**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 +[**uploadFileWithRequiredFile**](PetApi.md#uploadfilewithrequiredfile) | **POST** /fake/{petId}/uploadImageWithRequiredFile | uploads an image (required) # **addPet** diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/doc/StoreApi.md b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/doc/StoreApi.md index 1fcb8f71eea..a7dbf9ad019 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/doc/StoreApi.md +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/doc/StoreApi.md @@ -9,10 +9,10 @@ All URIs are relative to *http://petstore.swagger.io:80/v2* Method | HTTP request | Description ------------- | ------------- | ------------- -[**deleteOrder**](StoreApi.md#deleteorder) | **delete** /store/order/{order_id} | Delete purchase order by ID -[**getInventory**](StoreApi.md#getinventory) | **get** /store/inventory | Returns pet inventories by status -[**getOrderById**](StoreApi.md#getorderbyid) | **get** /store/order/{order_id} | Find purchase order by ID -[**placeOrder**](StoreApi.md#placeorder) | **post** /store/order | Place an order for a pet +[**deleteOrder**](StoreApi.md#deleteorder) | **DELETE** /store/order/{order_id} | Delete purchase order by ID +[**getInventory**](StoreApi.md#getinventory) | **GET** /store/inventory | Returns pet inventories by status +[**getOrderById**](StoreApi.md#getorderbyid) | **GET** /store/order/{order_id} | Find purchase order by ID +[**placeOrder**](StoreApi.md#placeorder) | **POST** /store/order | Place an order for a pet # **deleteOrder** diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/doc/UserApi.md b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/doc/UserApi.md index 62e01652e80..32bc2e675da 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/doc/UserApi.md +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/doc/UserApi.md @@ -9,14 +9,14 @@ All URIs are relative to *http://petstore.swagger.io:80/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**](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** diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/api/another_fake_api.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/api/another_fake_api.dart index 4bea8f87dbd..cabc80b7798 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/api/another_fake_api.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/api/another_fake_api.dart @@ -42,9 +42,7 @@ class AnotherFakeApi { ...?extra, }, validateStatus: validateStatus, - contentType: [ - 'application/json', - ].first, + contentType: 'application/json', cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/api/default_api.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/api/default_api.dart index ab47f0a6571..51dd7ea125e 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/api/default_api.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/api/default_api.dart @@ -41,9 +41,7 @@ class DefaultApi { ...?extra, }, validateStatus: validateStatus, - contentType: [ - 'application/json', - ].first, + contentType: 'application/json', cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/api/fake_api.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/api/fake_api.dart index b50d02d5cf6..9dadc9c1988 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/api/fake_api.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/api/fake_api.dart @@ -50,9 +50,7 @@ class FakeApi { ...?extra, }, validateStatus: validateStatus, - contentType: [ - 'application/json', - ].first, + contentType: 'application/json', cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, @@ -118,10 +116,7 @@ class FakeApi { ...?extra, }, validateStatus: validateStatus, - contentType: [ - 'application/json', - 'application/xml', - ].first, + contentType: 'application/json', cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, @@ -164,9 +159,7 @@ class FakeApi { ...?extra, }, validateStatus: validateStatus, - contentType: [ - 'application/json', - ].first, + contentType: 'application/json', cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, @@ -219,9 +212,7 @@ class FakeApi { ...?extra, }, validateStatus: validateStatus, - contentType: [ - 'application/json', - ].first, + contentType: 'application/json', cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, @@ -279,9 +270,7 @@ class FakeApi { ...?extra, }, validateStatus: validateStatus, - contentType: [ - 'application/json', - ].first, + contentType: 'application/json', cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, @@ -334,9 +323,7 @@ class FakeApi { ...?extra, }, validateStatus: validateStatus, - contentType: [ - 'application/json', - ].first, + contentType: 'application/json', cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, @@ -389,9 +376,7 @@ class FakeApi { ...?extra, }, validateStatus: validateStatus, - contentType: [ - 'application/json', - ].first, + contentType: 'application/json', cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, @@ -428,7 +413,49 @@ class FakeApi { /// /// - /// For this test, the body for this request much reference a schema named `File`. + /// For this test, the body has to be a binary file. + Future> testBodyWithBinary( + Uint8List body, { + CancelToken cancelToken, + Map headers, + Map extra, + ValidateStatus validateStatus, + ProgressCallback onSendProgress, + ProgressCallback onReceiveProgress, + }) async { + final _request = RequestOptions( + path: r'/fake/body-with-binary', + method: 'PUT', + headers: { + ...?headers, + }, + extra: { + 'secure': >[], + ...?extra, + }, + validateStatus: validateStatus, + contentType: 'image/png', + cancelToken: cancelToken, + onSendProgress: onSendProgress, + onReceiveProgress: onReceiveProgress, + ); + + dynamic _bodyData; + + _bodyData = body; + + final _response = await _dio.request( + _request.path, + data: _bodyData, + options: _request, + ); + + return _response; + } + + /// + /// + /// For this test, the body for this request must reference a schema named `File`. Future> testBodyWithFileSchema( FileSchemaTestClass fileSchemaTestClass, { CancelToken cancelToken, @@ -449,9 +476,7 @@ class FakeApi { ...?extra, }, validateStatus: validateStatus, - contentType: [ - 'application/json', - ].first, + contentType: 'application/json', cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, @@ -498,9 +523,7 @@ class FakeApi { ...?extra, }, validateStatus: validateStatus, - contentType: [ - 'application/json', - ].first, + contentType: 'application/json', cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, @@ -543,9 +566,7 @@ class FakeApi { ...?extra, }, validateStatus: validateStatus, - contentType: [ - 'application/json', - ].first, + contentType: 'application/json', cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, @@ -621,9 +642,7 @@ class FakeApi { ...?extra, }, validateStatus: validateStatus, - contentType: [ - 'application/x-www-form-urlencoded', - ].first, + contentType: 'application/x-www-form-urlencoded', cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, @@ -695,9 +714,7 @@ class FakeApi { ...?extra, }, validateStatus: validateStatus, - contentType: [ - 'application/x-www-form-urlencoded', - ].first, + contentType: 'application/x-www-form-urlencoded', cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, @@ -760,9 +777,7 @@ class FakeApi { ...?extra, }, validateStatus: validateStatus, - contentType: [ - 'application/json', - ].first, + contentType: 'application/json', cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, @@ -802,9 +817,7 @@ class FakeApi { ...?extra, }, validateStatus: validateStatus, - contentType: [ - 'application/json', - ].first, + contentType: 'application/json', cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, @@ -848,9 +861,7 @@ class FakeApi { ...?extra, }, validateStatus: validateStatus, - contentType: [ - 'application/x-www-form-urlencoded', - ].first, + contentType: 'application/x-www-form-urlencoded', cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, @@ -906,9 +917,7 @@ class FakeApi { ...?extra, }, validateStatus: validateStatus, - contentType: [ - 'application/json', - ].first, + contentType: 'application/json', cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/api/fake_classname_tags123_api.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/api/fake_classname_tags123_api.dart index f9b44deb6d5..54c40f0e343 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/api/fake_classname_tags123_api.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/api/fake_classname_tags123_api.dart @@ -49,9 +49,7 @@ class FakeClassnameTags123Api { ...?extra, }, validateStatus: validateStatus, - contentType: [ - 'application/json', - ].first, + contentType: 'application/json', cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/api/pet_api.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/api/pet_api.dart index 56bdd8556bc..9cc7beeb57e 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/api/pet_api.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/api/pet_api.dart @@ -51,10 +51,7 @@ class PetApi { ...?extra, }, validateStatus: validateStatus, - contentType: [ - 'application/json', - 'application/xml', - ].first, + contentType: 'application/json', cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, @@ -104,9 +101,7 @@ class PetApi { ...?extra, }, validateStatus: validateStatus, - contentType: [ - 'application/json', - ].first, + contentType: 'application/json', cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, @@ -154,9 +149,7 @@ class PetApi { ...?extra, }, validateStatus: validateStatus, - contentType: [ - 'application/json', - ].first, + contentType: 'application/json', cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, @@ -219,9 +212,7 @@ class PetApi { ...?extra, }, validateStatus: validateStatus, - contentType: [ - 'application/json', - ].first, + contentType: 'application/json', cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, @@ -283,9 +274,7 @@ class PetApi { ...?extra, }, validateStatus: validateStatus, - contentType: [ - 'application/json', - ].first, + contentType: 'application/json', cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, @@ -345,10 +334,7 @@ class PetApi { ...?extra, }, validateStatus: validateStatus, - contentType: [ - 'application/json', - 'application/xml', - ].first, + contentType: 'application/json', cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, @@ -398,9 +384,7 @@ class PetApi { ...?extra, }, validateStatus: validateStatus, - contentType: [ - 'application/x-www-form-urlencoded', - ].first, + contentType: 'application/x-www-form-urlencoded', cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, @@ -452,9 +436,7 @@ class PetApi { ...?extra, }, validateStatus: validateStatus, - contentType: [ - 'multipart/form-data', - ].first, + contentType: 'multipart/form-data', cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, @@ -521,9 +503,7 @@ class PetApi { ...?extra, }, validateStatus: validateStatus, - contentType: [ - 'multipart/form-data', - ].first, + contentType: 'multipart/form-data', cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/api/store_api.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/api/store_api.dart index e6c7679d1cd..14fa8b60121 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/api/store_api.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/api/store_api.dart @@ -43,9 +43,7 @@ class StoreApi { ...?extra, }, validateStatus: validateStatus, - contentType: [ - 'application/json', - ].first, + contentType: 'application/json', cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, @@ -91,9 +89,7 @@ class StoreApi { ...?extra, }, validateStatus: validateStatus, - contentType: [ - 'application/json', - ].first, + contentType: 'application/json', cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, @@ -148,9 +144,7 @@ class StoreApi { ...?extra, }, validateStatus: validateStatus, - contentType: [ - 'application/json', - ].first, + contentType: 'application/json', cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, @@ -205,9 +199,7 @@ class StoreApi { ...?extra, }, validateStatus: validateStatus, - contentType: [ - 'application/json', - ].first, + contentType: 'application/json', cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/api/user_api.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/api/user_api.dart index d85fbcc8585..86032dba94a 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/api/user_api.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/api/user_api.dart @@ -43,9 +43,7 @@ class UserApi { ...?extra, }, validateStatus: validateStatus, - contentType: [ - 'application/json', - ].first, + contentType: 'application/json', cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, @@ -88,9 +86,7 @@ class UserApi { ...?extra, }, validateStatus: validateStatus, - contentType: [ - 'application/json', - ].first, + contentType: 'application/json', cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, @@ -133,9 +129,7 @@ class UserApi { ...?extra, }, validateStatus: validateStatus, - contentType: [ - 'application/json', - ].first, + contentType: 'application/json', cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, @@ -178,9 +172,7 @@ class UserApi { ...?extra, }, validateStatus: validateStatus, - contentType: [ - 'application/json', - ].first, + contentType: 'application/json', cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, @@ -220,9 +212,7 @@ class UserApi { ...?extra, }, validateStatus: validateStatus, - contentType: [ - 'application/json', - ].first, + contentType: 'application/json', cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, @@ -282,9 +272,7 @@ class UserApi { ...?extra, }, validateStatus: validateStatus, - contentType: [ - 'application/json', - ].first, + contentType: 'application/json', cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, @@ -334,9 +322,7 @@ class UserApi { ...?extra, }, validateStatus: validateStatus, - contentType: [ - 'application/json', - ].first, + contentType: 'application/json', cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, @@ -377,9 +363,7 @@ class UserApi { ...?extra, }, validateStatus: validateStatus, - contentType: [ - 'application/json', - ].first, + contentType: 'application/json', cancelToken: cancelToken, onSendProgress: onSendProgress, onReceiveProgress: onReceiveProgress, diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/pubspec.yaml b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/pubspec.yaml index 3182395f579..34a1aa76180 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/pubspec.yaml +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/pubspec.yaml @@ -2,8 +2,6 @@ name: openapi version: 1.0.0 description: OpenAPI API client homepage: homepage -authors: - - 'Author ' environment: sdk: '>=2.7.0 <3.0.0' diff --git a/samples/openapi3/client/petstore/dart2/petstore/.analysis_options b/samples/openapi3/client/petstore/dart2/petstore/.analysis_options deleted file mode 100644 index a10d4c5a05c..00000000000 --- a/samples/openapi3/client/petstore/dart2/petstore/.analysis_options +++ /dev/null @@ -1,2 +0,0 @@ -analyzer: - strong-mode: true diff --git a/samples/openapi3/client/petstore/dart2/petstore/pubspec.yaml b/samples/openapi3/client/petstore/dart2/petstore/pubspec.yaml index f2630175093..92262618ab4 100644 --- a/samples/openapi3/client/petstore/dart2/petstore/pubspec.yaml +++ b/samples/openapi3/client/petstore/dart2/petstore/pubspec.yaml @@ -1,13 +1,18 @@ name: petstore_client version: 1.0.0 description: Petstore client using OpenAPI library + +publish_to: none + environment: - sdk: '>=2.5.0 <3.0.0' + sdk: '>=2.11.0 <3.0.0' + dependencies: openapi: path: ../petstore_client_lib + dev_dependencies: test: ^1.8.0 mockito: ^4.1.1 - http: ^0.12.0 + http: ^0.13.0 collection: ^1.14.12 diff --git a/samples/openapi3/client/petstore/dart2/petstore/test/fake_client.dart b/samples/openapi3/client/petstore/dart2/petstore/test/fake_client.dart index 95c735deb38..ed60f386aa4 100644 --- a/samples/openapi3/client/petstore/dart2/petstore/test/fake_client.dart +++ b/samples/openapi3/client/petstore/dart2/petstore/test/fake_client.dart @@ -21,9 +21,9 @@ class FakeClient extends Fake implements Client { this.expectedPutRequestBody, this.putResponseBody, this.sendResponseBody, - this.expectedUrl, + String expectedUrl, this.expectedHeaders = null, - }); + }) : this.expectedUrl = Uri.parse(expectedUrl); Exception throwException; Object expectedPostRequestBody; @@ -34,12 +34,12 @@ class FakeClient extends Fake implements Client { String expectedPutRequestBody; String putResponseBody; String sendResponseBody; - String expectedUrl; + Uri expectedUrl; Map expectedHeaders; @override - Future post(url, - {Map headers, body, Encoding encoding}) async { + Future post(Uri url, + {Map headers, Object body, Encoding encoding}) async { // check that the request was made with expected values if (url != expectedUrl) { throw StateError( @@ -67,7 +67,7 @@ class FakeClient extends Fake implements Client { } @override - Future get(url, {Map headers}) async { + Future get(Uri url, {Map headers}) async { // check that the request was made with expected values if (url != expectedUrl) { throw StateError( @@ -85,7 +85,8 @@ class FakeClient extends Fake implements Client { } @override - Future delete(url, {Map headers}) async { + Future delete(Uri url, + {Map headers, Object body, Encoding encoding}) async { // check that the request was made with expected values if (url != expectedUrl) { throw StateError( @@ -103,8 +104,8 @@ class FakeClient extends Fake implements Client { } @override - Future put(url, - {Map headers, body, Encoding encoding}) async { + Future put(Uri url, + {Map headers, Object body, Encoding encoding}) async { // check that the request was made with expected values if (url != expectedUrl) { throw StateError( diff --git a/samples/openapi3/client/petstore/dart2/petstore/test/order_model_test.dart b/samples/openapi3/client/petstore/dart2/petstore/test/order_model_test.dart index 9cdc65fe52d..7048659e894 100644 --- a/samples/openapi3/client/petstore/dart2/petstore/test/order_model_test.dart +++ b/samples/openapi3/client/petstore/dart2/petstore/test/order_model_test.dart @@ -2,8 +2,8 @@ import 'package:openapi/api.dart'; import 'package:test/test.dart'; void main() { - test('Check if default value is generated', () async { - var order = Order(); - expect(order.complete, equals(false)); - }); + test('Check if default value is generated', () async { + var order = Order(); + expect(order.complete, equals(false)); + }); } diff --git a/samples/openapi3/client/petstore/dart2/petstore/test/pet_faked_client_test.dart b/samples/openapi3/client/petstore/dart2/petstore/test/pet_faked_client_test.dart index 277c49b3971..9737df5d488 100644 --- a/samples/openapi3/client/petstore/dart2/petstore/test/pet_faked_client_test.dart +++ b/samples/openapi3/client/petstore/dart2/petstore/test/pet_faked_client_test.dart @@ -26,11 +26,10 @@ void main() { ..id = 124321 ..name = 'Jose' ]; - return Pet() + return Pet(name: name) ..id = id ..category = category ..tags = tags - ..name = name ..status = PetStatusEnum.fromJson(status) ..photoUrls = ['https://petstore.com/sample/photo1.jpg']; } @@ -53,8 +52,7 @@ void main() { // use the pet api to add a pet petApi.apiClient.client = FakeClient( expectedUrl: 'http://petstore.swagger.io/v2/pet', - expectedPostRequestBody: - await petApi.apiClient.serializeAsync(newPet), + expectedPostRequestBody: await petApi.apiClient.serializeAsync(newPet), postResponseBody: await petApi.apiClient.serializeAsync(newPet), expectedHeaders: {'Content-Type': 'application/json'}); await petApi.addPet(newPet); @@ -76,8 +74,7 @@ void main() { expectedUrl: 'http://petstore.swagger.io/v2/pet/$id', throwException: ApiException(400, 'not found'), ); - expect( - petApi.getPetById(id), throwsA(equals(TypeMatcher()))); + expect(petApi.getPetById(id), throwsA(equals(TypeMatcher()))); }); test('deletes existing pet by id', () async { @@ -87,8 +84,7 @@ void main() { // add a new pet petApi.apiClient.client = FakeClient( expectedUrl: 'http://petstore.swagger.io/v2/pet', - expectedPostRequestBody: - await petApi.apiClient.serializeAsync(newPet), + expectedPostRequestBody: await petApi.apiClient.serializeAsync(newPet), postResponseBody: await petApi.apiClient.serializeAsync(newPet), expectedHeaders: {'Content-Type': 'application/json'}); await petApi.addPet(newPet); @@ -106,8 +102,7 @@ void main() { expectedUrl: 'http://petstore.swagger.io/v2/pet/$id', throwException: ApiException(400, 'Not found'), ); - expect( - petApi.getPetById(id), throwsA(equals(TypeMatcher()))); + expect(petApi.getPetById(id), throwsA(equals(TypeMatcher()))); }); test('updates pet with form', () async { @@ -117,16 +112,11 @@ void main() { // add a new pet petApi.apiClient.client = FakeClient( expectedUrl: 'http://petstore.swagger.io/v2/pet', - expectedPostRequestBody: - await petApi.apiClient.serializeAsync(newPet), + expectedPostRequestBody: await petApi.apiClient.serializeAsync(newPet), postResponseBody: await petApi.apiClient.serializeAsync(newPet), expectedHeaders: {'Content-Type': 'application/json'}); await petApi.addPet(newPet); - final multipartRequest = MultipartRequest(null, null); - multipartRequest.fields['name'] = 'Doge'; - multipartRequest.fields['status'] = ''; - // update with form petApi.apiClient.client = FakeClient( expectedUrl: 'http://petstore.swagger.io/v2/pet/$id', @@ -157,8 +147,7 @@ void main() { // add a new pet petApi.apiClient.client = FakeClient( expectedUrl: 'http://petstore.swagger.io/v2/pet', - expectedPostRequestBody: - await petApi.apiClient.serializeAsync(newPet), + expectedPostRequestBody: await petApi.apiClient.serializeAsync(newPet), postResponseBody: await petApi.apiClient.serializeAsync(newPet), expectedHeaders: {'Content-Type': 'application/json'}); await petApi.addPet(newPet); @@ -166,8 +155,7 @@ void main() { // update the same pet petApi.apiClient.client = FakeClient( expectedUrl: 'http://petstore.swagger.io/v2/pet', - expectedPutRequestBody: - await petApi.apiClient.serializeAsync(updatePet), + expectedPutRequestBody: await petApi.apiClient.serializeAsync(updatePet), putResponseBody: await petApi.apiClient.serializeAsync(updatePet), expectedHeaders: {'Content-Type': 'application/json'}); await petApi.updatePet(updatePet); @@ -196,15 +184,13 @@ void main() { // retrieve pets by status petApi.apiClient.client = FakeClient( - expectedUrl: - 'http://petstore.swagger.io/v2/pet/findByStatus?status=$status', + expectedUrl: 'http://petstore.swagger.io/v2/pet/findByStatus?status=$status', getResponseBody: await petApi.apiClient.serializeAsync([pet1, pet2]), ); final pets = await petApi.findPetsByStatus([status]); // tests serialisation and deserialisation of enum - final petsByStatus = - pets.where((p) => p.status == PetStatusEnum.available); + final petsByStatus = pets.where((p) => p.status == PetStatusEnum.available); expect(petsByStatus.length, equals(2)); final petIds = pets.map((pet) => pet.id).toList(); expect(petIds, contains(id1)); @@ -216,14 +202,12 @@ void main() { final id = newId(); final newPet = makePet(id: id); // get some test data (recorded from live response) - final uploadResponse = - await File('test/file_upload_response.json').readAsString(); + final uploadResponse = await File('test/file_upload_response.json').readAsString(); // add a new pet petApi.apiClient.client = FakeClient( expectedUrl: 'http://petstore.swagger.io/v2/pet', - expectedPostRequestBody: - await petApi.apiClient.serializeAsync(newPet), + expectedPostRequestBody: await petApi.apiClient.serializeAsync(newPet), postResponseBody: await petApi.apiClient.serializeAsync(newPet), expectedHeaders: {'Content-Type': 'application/json'}); await petApi.addPet(newPet); @@ -232,9 +216,8 @@ void main() { expectedUrl: 'http://petstore.swagger.io/v2/pet', sendResponseBody: uploadResponse, ); - final file = - new MultipartFile.fromBytes('file', [104, 101, 108, 108, 111]); - await petApi.uploadFile(id, additionalMetadata: '', file: file); + final file = new MultipartFile.fromBytes('file', [104, 101, 108, 108, 111]); + await petApi.uploadFile(id, file: file); }); }); } diff --git a/samples/openapi3/client/petstore/dart2/petstore/test/pet_test.dart b/samples/openapi3/client/petstore/dart2/petstore/test/pet_test.dart index 72126ba6a90..cbd26c68c7e 100644 --- a/samples/openapi3/client/petstore/dart2/petstore/test/pet_test.dart +++ b/samples/openapi3/client/petstore/dart2/petstore/test/pet_test.dart @@ -1,5 +1,4 @@ -import 'dart:async'; - +@Skip('Needs real petstore') import 'package:http/http.dart'; import 'package:openapi/api.dart'; import 'package:test/test.dart'; @@ -46,16 +45,14 @@ void main() { }); test('doesn\'t get non-existing pet by id', () { - expect(petApi.getPetById(newId()), - throwsA(equals(TypeMatcher()))); + expect(petApi.getPetById(newId()), throwsA(equals(TypeMatcher()))); }); test('deletes existing pet by id', () async { var id = newId(); await petApi.addPet(makePet(id: id)); await petApi.deletePet(id, apiKey: 'special-key'); - expect( - petApi.getPetById(id), throwsA(equals(TypeMatcher()))); + expect(petApi.getPetById(id), throwsA(equals(TypeMatcher()))); }); test('updates pet with form', () async { @@ -100,5 +97,5 @@ void main() { var file = new MultipartFile.fromBytes('file', [104, 101, 108, 108, 111]); await petApi.uploadFile(id, additionalMetadata: '', file: file); }); - }, skip: 'e2e tests for CI'); + }); } diff --git a/samples/openapi3/client/petstore/dart2/petstore/test/random_id.dart b/samples/openapi3/client/petstore/dart2/petstore/test/random_id.dart index 0457428c7dd..ca67ac20993 100644 --- a/samples/openapi3/client/petstore/dart2/petstore/test/random_id.dart +++ b/samples/openapi3/client/petstore/dart2/petstore/test/random_id.dart @@ -4,4 +4,4 @@ final _random = new Random(); int newId() { return _random.nextInt(999999); -} \ No newline at end of file +} diff --git a/samples/openapi3/client/petstore/dart2/petstore/test/store_faked_client_test.dart b/samples/openapi3/client/petstore/dart2/petstore/test/store_faked_client_test.dart index 9f75fd55d86..541d08b8c6a 100644 --- a/samples/openapi3/client/petstore/dart2/petstore/test/store_faked_client_test.dart +++ b/samples/openapi3/client/petstore/dart2/petstore/test/store_faked_client_test.dart @@ -21,62 +21,56 @@ void main() { group('Store API with faked client', () { test('places an order and gets it by id', () async { - // TODO: Please uncomment this after a content type of the petstore order in petstore.yaml is fixed. - // final id = newId(); - // final newOrder = makeOrder(id: id); + final id = newId(); + final newOrder = makeOrder(id: id); - // // use the store api to add an order - // storeApi.apiClient.client = FakeClient( - // expectedUrl: 'http://petstore.swagger.io/v2/store/order', - // expectedPostRequestBody: await storeApi.apiClient.serializeAsync(newOrder), - // postResponseBody: await storeApi.apiClient.serializeAsync(newOrder), - // expectedHeaders: {"Content-Type": "application/json"} - // ); - // await storeApi.placeOrder(newOrder); + // use the store api to add an order + storeApi.apiClient.client = FakeClient( + expectedUrl: 'http://petstore.swagger.io/v2/store/order', + expectedPostRequestBody: await storeApi.apiClient.serializeAsync(newOrder), + postResponseBody: await storeApi.apiClient.serializeAsync(newOrder), + expectedHeaders: {"Content-Type": "application/json"}); + await storeApi.placeOrder(newOrder); - // // retrieve the same order by id - // storeApi.apiClient.client = FakeClient( - // expectedUrl: 'http://petstore.swagger.io/v2/store/order/$id', - // getResponseBody: await storeApi.apiClient.serializeAsync(newOrder), - // ); - // final placedOrder = await storeApi.getOrderById(id); - // expect(placedOrder.id, equals(id)); + // retrieve the same order by id + storeApi.apiClient.client = FakeClient( + expectedUrl: 'http://petstore.swagger.io/v2/store/order/$id', + getResponseBody: await storeApi.apiClient.serializeAsync(newOrder), + ); + final placedOrder = await storeApi.getOrderById(id); + expect(placedOrder.id, equals(id)); }); test('deletes an order', () async { - // TODO: Please uncomment this after a content type of the petstore order in petstore.yaml is fixed. - // final id = newId(); - // final newOrder = makeOrder(id: id); + final id = newId(); + final newOrder = makeOrder(id: id); - // // use the store api to add an order - // storeApi.apiClient.client = FakeClient( - // expectedUrl: 'http://petstore.swagger.io/v2/store/order', - // expectedPostRequestBody: await storeApi.apiClient.serializeAsync(newOrder), - // postResponseBody: await storeApi.apiClient.serializeAsync(newOrder), - // expectedHeaders: {"Content-Type": "application/json"} - // ); - // await storeApi.placeOrder(newOrder); + // use the store api to add an order + storeApi.apiClient.client = FakeClient( + expectedUrl: 'http://petstore.swagger.io/v2/store/order', + expectedPostRequestBody: await storeApi.apiClient.serializeAsync(newOrder), + postResponseBody: await storeApi.apiClient.serializeAsync(newOrder), + expectedHeaders: {"Content-Type": "application/json"}); + await storeApi.placeOrder(newOrder); - // // delete the same order - // storeApi.apiClient.client = FakeClient( - // expectedUrl: 'http://petstore.swagger.io/v2/store/order/$id', - // deleteResponseBody: '', - // ); - // await storeApi.deleteOrder(id.toString()); + // delete the same order + storeApi.apiClient.client = FakeClient( + expectedUrl: 'http://petstore.swagger.io/v2/store/order/$id', + deleteResponseBody: '', + ); + await storeApi.deleteOrder(id.toString()); - // // try and retrieve the order - // storeApi.apiClient.client = FakeClient( - // expectedUrl: 'http://petstore.swagger.io/v2/store/order/$id', - // throwException: ApiException(400, 'Not found'), - // ); - // expect(storeApi.getOrderById(id), - // throwsA(equals(TypeMatcher()))); + // try and retrieve the order + storeApi.apiClient.client = FakeClient( + expectedUrl: 'http://petstore.swagger.io/v2/store/order/$id', + throwException: ApiException(400, 'Not found'), + ); + expect(storeApi.getOrderById(id), throwsA(equals(TypeMatcher()))); }); test('gets the store inventory', () async { // get some test data (recorded from live response) - final inventoryResponse = - await File('test/inventory_response.json').readAsString(); + final inventoryResponse = await File('test/inventory_response.json').readAsString(); // use the store api to get the inventory storeApi.apiClient.client = FakeClient( expectedUrl: 'http://petstore.swagger.io/v2/store/inventory', diff --git a/samples/openapi3/client/petstore/dart2/petstore/test/store_test.dart b/samples/openapi3/client/petstore/dart2/petstore/test/store_test.dart index b2175238819..a5b19cd1de5 100644 --- a/samples/openapi3/client/petstore/dart2/petstore/test/store_test.dart +++ b/samples/openapi3/client/petstore/dart2/petstore/test/store_test.dart @@ -1,3 +1,4 @@ +@Skip('Needs real petstore') import 'package:openapi/api.dart'; import 'package:test/test.dart'; @@ -18,27 +19,24 @@ void main() { group('Store API with live client', () { test('places an order and gets it by id', () async { - // TODO: Please uncomment this after a content type of the petstore order in petstore.yaml is fixed. - // var id = newId(); + var id = newId(); - // await storeApi.placeOrder(makeOrder(id: id)); - // var order = await storeApi.getOrderById(id); - // expect(order.id, equals(id)); + await storeApi.placeOrder(makeOrder(id: id)); + var order = await storeApi.getOrderById(id); + expect(order.id, equals(id)); }); test('deletes an order', () async { - // TODO: Please uncomment this after a content type of the petstore order in petstore.yaml is fixed. - // var id = newId(); + var id = newId(); - // await storeApi.placeOrder(makeOrder(id: id)); - // await storeApi.deleteOrder(id.toString()); - // expect(storeApi.getOrderById(id), - // throwsA(equals(TypeMatcher()))); + await storeApi.placeOrder(makeOrder(id: id)); + await storeApi.deleteOrder(id.toString()); + expect(storeApi.getOrderById(id), throwsA(equals(TypeMatcher()))); }); test('gets the store inventory', () async { Map inventory = await storeApi.getInventory(); expect(inventory.length, isNot(equals(0))); }); - }); // , skip: 'e2e tests for CI' + }); } diff --git a/samples/openapi3/client/petstore/dart2/petstore/test/user_test.dart b/samples/openapi3/client/petstore/dart2/petstore/test/user_test.dart index ea34b3713fa..d604363622d 100644 --- a/samples/openapi3/client/petstore/dart2/petstore/test/user_test.dart +++ b/samples/openapi3/client/petstore/dart2/petstore/test/user_test.dart @@ -1,3 +1,4 @@ +@Skip('Needs real petstore') import 'package:openapi/api.dart'; import 'package:test/test.dart'; @@ -6,8 +7,7 @@ import 'random_id.dart'; void main() { var userApi = new UserApi(); - User makeUser( - {int id, String userName = 'username', String password = 'password'}) { + User makeUser({int id, String userName = 'username', String password = 'password'}) { return User() ..id = id ..username = userName @@ -63,8 +63,7 @@ void main() { var username = 'Riddlem325'; await userApi.createUser(makeUser(id: newId(), userName: username)); await userApi.deleteUser(username); - expect(userApi.getUserByName(username), - throwsA(TypeMatcher())); + expect(userApi.getUserByName(username), throwsA(TypeMatcher())); }); test('logs a user in', () async { @@ -76,5 +75,5 @@ void main() { var result = await userApi.loginUser(username, password); expect(result, contains('logged in user session:')); }); - }, skip: 'e2e tests for CI'); + }); } diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib/.openapi-generator/FILES b/samples/openapi3/client/petstore/dart2/petstore_client_lib/.openapi-generator/FILES index 7cc5afea821..733ecbe3062 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib/.openapi-generator/FILES +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib/.openapi-generator/FILES @@ -1,6 +1,7 @@ .gitignore .travis.yml README.md +analysis_options.yaml doc/ApiResponse.md doc/Category.md doc/Order.md 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 5f68295fc19..e8415097f3a 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,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib/analysis_options.yaml b/samples/openapi3/client/petstore/dart2/petstore_client_lib/analysis_options.yaml new file mode 100644 index 00000000000..83d5a10bd7b --- /dev/null +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib/analysis_options.yaml @@ -0,0 +1,3 @@ +analyzer: + strong-mode: + implicit-casts: true diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/api/pet_api.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/api/pet_api.dart index 2ec34d475e2..ee5c6f0d24c 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/api/pet_api.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/api/pet_api.dart @@ -41,17 +41,6 @@ class PetApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = ['petstore_auth']; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -118,17 +107,6 @@ class PetApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = ['petstore_auth']; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -187,17 +165,6 @@ class PetApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = ['petstore_auth']; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -265,17 +232,6 @@ class PetApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = ['petstore_auth']; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -342,17 +298,6 @@ class PetApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = ['api_key']; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -414,17 +359,6 @@ class PetApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = ['petstore_auth']; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -491,30 +425,11 @@ class PetApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = ['petstore_auth']; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (name != null) { - hasFields = true; - mp.fields[r'name'] = parameterToString(name); - } - if (status != null) { - hasFields = true; - mp.fields[r'status'] = parameterToString(status); - } - if (hasFields) { - postBody = mp; - } - } else { - if (name != null) { - formParams[r'name'] = parameterToString(name); - } - if (status != null) { - formParams[r'status'] = parameterToString(status); - } + if (name != null) { + formParams[r'name'] = parameterToString(name); + } + if (status != null) { + formParams[r'status'] = parameterToString(status); } return await apiClient.invokeAPI( @@ -581,28 +496,19 @@ class PetApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = ['petstore_auth']; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (additionalMetadata != null) { - hasFields = true; - mp.fields[r'additionalMetadata'] = parameterToString(additionalMetadata); - } - if (file != null) { - hasFields = true; - mp.fields[r'file'] = file.field; - mp.files.add(file); - } - if (hasFields) { - postBody = mp; - } - } else { - if (additionalMetadata != null) { - formParams[r'additionalMetadata'] = parameterToString(additionalMetadata); - } + bool hasFields = false; + final mp = MultipartRequest('POST', Uri.parse(path)); + if (additionalMetadata != null) { + hasFields = true; + mp.fields[r'additionalMetadata'] = parameterToString(additionalMetadata); + } + if (file != null) { + hasFields = true; + mp.fields[r'file'] = file.field; + mp.files.add(file); + } + if (hasFields) { + postBody = mp; } return await apiClient.invokeAPI( diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/api/store_api.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/api/store_api.dart index 9696bacc9de..4ff0cee3e1a 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/api/store_api.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/api/store_api.dart @@ -44,17 +44,6 @@ class StoreApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = []; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -101,17 +90,6 @@ class StoreApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = ['api_key']; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -171,17 +149,6 @@ class StoreApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = []; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -243,17 +210,6 @@ class StoreApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = []; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/api/user_api.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/api/user_api.dart index fc19afb4e93..274b176291b 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/api/user_api.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/api/user_api.dart @@ -43,17 +43,6 @@ class UserApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = ['api_key']; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -108,17 +97,6 @@ class UserApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = ['api_key']; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -171,17 +149,6 @@ class UserApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = ['api_key']; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -237,17 +204,6 @@ class UserApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = ['api_key']; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -303,17 +259,6 @@ class UserApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = []; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -382,17 +327,6 @@ class UserApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = []; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -445,17 +379,6 @@ class UserApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = ['api_key']; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -512,17 +435,6 @@ class UserApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = ['api_key']; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/api_client.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/api_client.dart index 35b984b86a1..37b6acfd4c6 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/api_client.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/api_client.dart @@ -58,7 +58,7 @@ class ApiClient { Future invokeAPI( String path, String method, - Iterable queryParams, + List queryParams, Object body, Map headerParams, Map formParams, @@ -168,13 +168,13 @@ class ApiClient { List queryParams, Map headerParams, ) { - authNames.forEach((authName) { + for(final authName in authNames) { final auth = _authentications[authName]; if (auth == null) { throw ArgumentError('Authentication undefined: $authName'); } auth.applyToParams(queryParams, headerParams); - }); + } } static dynamic _deserialize(dynamic value, String targetType, {bool growable}) { diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/api_exception.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/api_exception.dart index 1537c9769b2..86e2054bffe 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/api_exception.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/api_exception.dart @@ -19,6 +19,7 @@ class ApiException implements Exception { Exception innerException; StackTrace stackTrace; + @override String toString() { if (message == null) { return 'ApiException'; diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/api_helper.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/api_helper.dart index 4135dcf95b2..cb1db7f0a01 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/api_helper.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/api_helper.dart @@ -28,7 +28,7 @@ Iterable _convertParametersForCollectionFormat( final params = []; // preconditions - if (name != null && !name.isEmpty && value != null) { + if (name != null && name.isNotEmpty && value != null) { if (value is List) { // get the collection format, default: csv collectionFormat = (collectionFormat == null || collectionFormat.isEmpty) diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/model/api_response.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/model/api_response.dart index bd80caff35c..6bb070b7eeb 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/model/api_response.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/model/api_response.dart @@ -65,12 +65,12 @@ class ApiResponse { static List listFromJson(List json, {bool emptyIsNull, bool growable,}) => json == null || json.isEmpty ? true == emptyIsNull ? null : [] - : json.map((v) => ApiResponse.fromJson(v)).toList(growable: true == growable); + : json.map((dynamic value) => ApiResponse.fromJson(value)).toList(growable: true == growable); static Map mapFromJson(Map json) { final map = {}; - if (json != null && json.isNotEmpty) { - json.forEach((String key, dynamic v) => map[key] = ApiResponse.fromJson(v)); + if (json?.isNotEmpty == true) { + json.forEach((key, value) => map[key] = ApiResponse.fromJson(value)); } return map; } @@ -78,9 +78,9 @@ class ApiResponse { // maps a json object with a list of ApiResponse-objects as value to a dart map static Map> mapListFromJson(Map json, {bool emptyIsNull, bool growable,}) { final map = >{}; - if (json != null && json.isNotEmpty) { - json.forEach((String key, dynamic v) { - map[key] = ApiResponse.listFromJson(v, emptyIsNull: emptyIsNull, growable: growable); + if (json?.isNotEmpty == true) { + json.forEach((key, value) { + map[key] = ApiResponse.listFromJson(value, emptyIsNull: emptyIsNull, growable: growable,); }); } return map; diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/model/category.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/model/category.dart index c63ffb1734f..c1c25b5a078 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/model/category.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/model/category.dart @@ -56,12 +56,12 @@ class Category { static List listFromJson(List json, {bool emptyIsNull, bool growable,}) => json == null || json.isEmpty ? true == emptyIsNull ? null : [] - : json.map((v) => Category.fromJson(v)).toList(growable: true == growable); + : json.map((dynamic value) => Category.fromJson(value)).toList(growable: true == growable); static Map mapFromJson(Map json) { final map = {}; - if (json != null && json.isNotEmpty) { - json.forEach((String key, dynamic v) => map[key] = Category.fromJson(v)); + if (json?.isNotEmpty == true) { + json.forEach((key, value) => map[key] = Category.fromJson(value)); } return map; } @@ -69,9 +69,9 @@ class Category { // maps a json object with a list of Category-objects as value to a dart map static Map> mapListFromJson(Map json, {bool emptyIsNull, bool growable,}) { final map = >{}; - if (json != null && json.isNotEmpty) { - json.forEach((String key, dynamic v) { - map[key] = Category.listFromJson(v, emptyIsNull: emptyIsNull, growable: growable); + if (json?.isNotEmpty == true) { + json.forEach((key, value) { + map[key] = Category.listFromJson(value, emptyIsNull: emptyIsNull, growable: growable,); }); } return map; 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 a7b01582664..4cf8b636f47 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 @@ -95,12 +95,12 @@ class Order { static List listFromJson(List json, {bool emptyIsNull, bool growable,}) => json == null || json.isEmpty ? true == emptyIsNull ? null : [] - : json.map((v) => Order.fromJson(v)).toList(growable: true == growable); + : json.map((dynamic value) => Order.fromJson(value)).toList(growable: true == growable); static Map mapFromJson(Map json) { final map = {}; - if (json != null && json.isNotEmpty) { - json.forEach((String key, dynamic v) => map[key] = Order.fromJson(v)); + if (json?.isNotEmpty == true) { + json.forEach((key, value) => map[key] = Order.fromJson(value)); } return map; } @@ -108,9 +108,9 @@ class Order { // maps a json object with a list of Order-objects as value to a dart map static Map> mapListFromJson(Map json, {bool emptyIsNull, bool growable,}) { final map = >{}; - if (json != null && json.isNotEmpty) { - json.forEach((String key, dynamic v) { - map[key] = Order.listFromJson(v, emptyIsNull: emptyIsNull, growable: growable); + if (json?.isNotEmpty == true) { + json.forEach((key, value) { + map[key] = Order.listFromJson(value, emptyIsNull: emptyIsNull, growable: growable,); }); } return map; diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/model/pet.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/model/pet.dart index ee8c7615986..267e1485b8b 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/model/pet.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/model/pet.dart @@ -91,12 +91,12 @@ class Pet { static List listFromJson(List json, {bool emptyIsNull, bool growable,}) => json == null || json.isEmpty ? true == emptyIsNull ? null : [] - : json.map((v) => Pet.fromJson(v)).toList(growable: true == growable); + : json.map((dynamic value) => Pet.fromJson(value)).toList(growable: true == growable); static Map mapFromJson(Map json) { final map = {}; - if (json != null && json.isNotEmpty) { - json.forEach((String key, dynamic v) => map[key] = Pet.fromJson(v)); + if (json?.isNotEmpty == true) { + json.forEach((key, value) => map[key] = Pet.fromJson(value)); } return map; } @@ -104,9 +104,9 @@ class Pet { // maps a json object with a list of Pet-objects as value to a dart map static Map> mapListFromJson(Map json, {bool emptyIsNull, bool growable,}) { final map = >{}; - if (json != null && json.isNotEmpty) { - json.forEach((String key, dynamic v) { - map[key] = Pet.listFromJson(v, emptyIsNull: emptyIsNull, growable: growable); + if (json?.isNotEmpty == true) { + json.forEach((key, value) { + map[key] = Pet.listFromJson(value, emptyIsNull: emptyIsNull, growable: growable,); }); } return map; diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/model/tag.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/model/tag.dart index 63132f08a3a..0cd372910b9 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/model/tag.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/model/tag.dart @@ -56,12 +56,12 @@ class Tag { static List listFromJson(List json, {bool emptyIsNull, bool growable,}) => json == null || json.isEmpty ? true == emptyIsNull ? null : [] - : json.map((v) => Tag.fromJson(v)).toList(growable: true == growable); + : json.map((dynamic value) => Tag.fromJson(value)).toList(growable: true == growable); static Map mapFromJson(Map json) { final map = {}; - if (json != null && json.isNotEmpty) { - json.forEach((String key, dynamic v) => map[key] = Tag.fromJson(v)); + if (json?.isNotEmpty == true) { + json.forEach((key, value) => map[key] = Tag.fromJson(value)); } return map; } @@ -69,9 +69,9 @@ class Tag { // maps a json object with a list of Tag-objects as value to a dart map static Map> mapListFromJson(Map json, {bool emptyIsNull, bool growable,}) { final map = >{}; - if (json != null && json.isNotEmpty) { - json.forEach((String key, dynamic v) { - map[key] = Tag.listFromJson(v, emptyIsNull: emptyIsNull, growable: growable); + if (json?.isNotEmpty == true) { + json.forEach((key, value) { + map[key] = Tag.listFromJson(value, emptyIsNull: emptyIsNull, growable: growable,); }); } return map; diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/model/user.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/model/user.dart index bb512af491f..0eb3716fceb 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/model/user.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/model/user.dart @@ -111,12 +111,12 @@ class User { static List listFromJson(List json, {bool emptyIsNull, bool growable,}) => json == null || json.isEmpty ? true == emptyIsNull ? null : [] - : json.map((v) => User.fromJson(v)).toList(growable: true == growable); + : json.map((dynamic value) => User.fromJson(value)).toList(growable: true == growable); static Map mapFromJson(Map json) { final map = {}; - if (json != null && json.isNotEmpty) { - json.forEach((String key, dynamic v) => map[key] = User.fromJson(v)); + if (json?.isNotEmpty == true) { + json.forEach((key, value) => map[key] = User.fromJson(value)); } return map; } @@ -124,9 +124,9 @@ class User { // maps a json object with a list of User-objects as value to a dart map static Map> mapListFromJson(Map json, {bool emptyIsNull, bool growable,}) { final map = >{}; - if (json != null && json.isNotEmpty) { - json.forEach((String key, dynamic v) { - map[key] = User.listFromJson(v, emptyIsNull: emptyIsNull, growable: growable); + if (json?.isNotEmpty == true) { + json.forEach((key, value) { + map[key] = User.listFromJson(value, emptyIsNull: emptyIsNull, growable: growable,); }); } return map; diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib/pubspec.yaml b/samples/openapi3/client/petstore/dart2/petstore_client_lib/pubspec.yaml index 4d55880cd85..163b29ec3ec 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib/pubspec.yaml +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib/pubspec.yaml @@ -5,8 +5,6 @@ name: 'openapi' version: '1.0.0' description: 'OpenAPI API client' -authors: - - 'Author ' homepage: 'homepage' environment: sdk: '>=2.12.0 <3.0.0' diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/.openapi-generator/FILES b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/.openapi-generator/FILES index 80d5a3a8fc8..a5fe5c494d6 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/.openapi-generator/FILES +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/.openapi-generator/FILES @@ -1,6 +1,7 @@ .gitignore .travis.yml README.md +analysis_options.yaml doc/AdditionalPropertiesClass.md doc/Animal.md doc/AnotherFakeApi.md 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 5f68295fc19..e8415097f3a 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,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x 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 fe39c2f2126..ec001c87cea 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 @@ -67,6 +67,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* | [**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 | *FakeApi* | [**testClientModel**](doc//FakeApi.md#testclientmodel) | **PATCH** /fake | To test \"client\" model diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/analysis_options.yaml b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/analysis_options.yaml new file mode 100644 index 00000000000..83d5a10bd7b --- /dev/null +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/analysis_options.yaml @@ -0,0 +1,3 @@ +analyzer: + strong-mode: + implicit-casts: true 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 8b7f63bf8bd..6d613003880 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 @@ -16,6 +16,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 | +[**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 | [**testClientModel**](FakeApi.md#testclientmodel) | **PATCH** /fake | To test \"client\" model @@ -323,12 +324,54 @@ 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) +# **testBodyWithBinary** +> testBodyWithBinary(body) + + + +For this test, the body has to be a binary file. + +### Example +```dart +import 'package:openapi/api.dart'; + +final api_instance = FakeApi(); +final body = MultipartFile(); // MultipartFile | image to upload + +try { + api_instance.testBodyWithBinary(body); +} catch (e) { + print('Exception when calling FakeApi->testBodyWithBinary: $e\n'); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | **MultipartFile**| image to upload | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: image/png + - **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(fileSchemaTestClass) -For this test, the body for this request much reference a schema named `File`. +For this test, the body for this request must reference a schema named `File`. ### Example ```dart diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api/another_fake_api.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api/another_fake_api.dart index c297f77a8a3..8f8b96abc53 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api/another_fake_api.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api/another_fake_api.dart @@ -43,17 +43,6 @@ class AnotherFakeApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = []; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api/default_api.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api/default_api.dart index 1185af2521c..e811495110f 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api/default_api.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api/default_api.dart @@ -29,17 +29,6 @@ class DefaultApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = []; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, 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 20db8f0c9b0..07742e02082 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 @@ -31,17 +31,6 @@ class FakeApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = []; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -110,17 +99,6 @@ class FakeApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = ['http_signature_test']; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -176,17 +154,6 @@ class FakeApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = []; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -243,17 +210,6 @@ class FakeApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = []; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -310,17 +266,6 @@ class FakeApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = []; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -377,17 +322,6 @@ class FakeApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = []; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -447,17 +381,6 @@ class FakeApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = []; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -491,7 +414,59 @@ class FakeApi { return Future.value(null); } - /// For this test, the body for this request much reference a schema named `File`. + /// For this test, the body has to be a binary file. + /// + /// Note: This method returns the HTTP [Response]. + /// + /// Parameters: + /// + /// * [MultipartFile] body (required): + /// image to upload + Future testBodyWithBinaryWithHttpInfo(MultipartFile body) async { + // Verify required params are set. + if (body == null) { + throw ApiException(HttpStatus.badRequest, 'Missing required param: body'); + } + + final path = r'/fake/body-with-binary'; + + Object postBody = body; + + final queryParams = []; + final headerParams = {}; + final formParams = {}; + + final contentTypes = ['image/png']; + final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; + final authNames = []; + + + return await apiClient.invokeAPI( + path, + 'PUT', + queryParams, + postBody, + headerParams, + formParams, + nullableContentType, + authNames, + ); + } + + /// For this test, the body has to be a binary file. + /// + /// Parameters: + /// + /// * [MultipartFile] body (required): + /// image to upload + Future testBodyWithBinary(MultipartFile body) async { + final response = await testBodyWithBinaryWithHttpInfo(body); + if (response.statusCode >= HttpStatus.badRequest) { + throw ApiException(response.statusCode, await _decodeBodyBytes(response)); + } + } + + /// For this test, the body for this request must reference a schema named `File`. /// /// Note: This method returns the HTTP [Response]. /// @@ -516,17 +491,6 @@ class FakeApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = []; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -540,7 +504,7 @@ class FakeApi { ); } - /// For this test, the body for this request much reference a schema named `File`. + /// For this test, the body for this request must reference a schema named `File`. /// /// Parameters: /// @@ -581,17 +545,6 @@ class FakeApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = []; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -645,17 +598,6 @@ class FakeApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = []; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -767,112 +709,44 @@ class FakeApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = ['http_basic_test']; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (integer != null) { - hasFields = true; - mp.fields[r'integer'] = parameterToString(integer); - } - if (int32 != null) { - hasFields = true; - mp.fields[r'int32'] = parameterToString(int32); - } - if (int64 != null) { - hasFields = true; - mp.fields[r'int64'] = parameterToString(int64); - } - if (number != null) { - hasFields = true; - mp.fields[r'number'] = parameterToString(number); - } - if (float != null) { - hasFields = true; - mp.fields[r'float'] = parameterToString(float); - } - if (double_ != null) { - hasFields = true; - mp.fields[r'double'] = parameterToString(double_); - } - if (string != null) { - hasFields = true; - mp.fields[r'string'] = parameterToString(string); - } - if (patternWithoutDelimiter != null) { - hasFields = true; - mp.fields[r'pattern_without_delimiter'] = parameterToString(patternWithoutDelimiter); - } - if (byte != null) { - hasFields = true; - mp.fields[r'byte'] = parameterToString(byte); - } - if (binary != null) { - hasFields = true; - mp.fields[r'binary'] = binary.field; - mp.files.add(binary); - } - if (date != null) { - hasFields = true; - mp.fields[r'date'] = parameterToString(date); - } - if (dateTime != null) { - hasFields = true; - mp.fields[r'dateTime'] = parameterToString(dateTime); - } - if (password != null) { - hasFields = true; - mp.fields[r'password'] = parameterToString(password); - } - if (callback != null) { - hasFields = true; - mp.fields[r'callback'] = parameterToString(callback); - } - if (hasFields) { - postBody = mp; - } - } else { - if (integer != null) { - formParams[r'integer'] = parameterToString(integer); - } - if (int32 != null) { - formParams[r'int32'] = parameterToString(int32); - } - if (int64 != null) { - formParams[r'int64'] = parameterToString(int64); - } - if (number != null) { - formParams[r'number'] = parameterToString(number); - } - if (float != null) { - formParams[r'float'] = parameterToString(float); - } - if (double_ != null) { - formParams[r'double'] = parameterToString(double_); - } - if (string != null) { - formParams[r'string'] = parameterToString(string); - } - if (patternWithoutDelimiter != null) { - formParams[r'pattern_without_delimiter'] = parameterToString(patternWithoutDelimiter); - } - if (byte != null) { - formParams[r'byte'] = parameterToString(byte); - } - if (date != null) { - formParams[r'date'] = parameterToString(date); - } - if (dateTime != null) { - formParams[r'dateTime'] = parameterToString(dateTime); - } - if (password != null) { - formParams[r'password'] = parameterToString(password); - } - if (callback != null) { - formParams[r'callback'] = parameterToString(callback); - } + if (integer != null) { + formParams[r'integer'] = parameterToString(integer); + } + if (int32 != null) { + formParams[r'int32'] = parameterToString(int32); + } + if (int64 != null) { + formParams[r'int64'] = parameterToString(int64); + } + if (number != null) { + formParams[r'number'] = parameterToString(number); + } + if (float != null) { + formParams[r'float'] = parameterToString(float); + } + if (double_ != null) { + formParams[r'double'] = parameterToString(double_); + } + if (string != null) { + formParams[r'string'] = parameterToString(string); + } + if (patternWithoutDelimiter != null) { + formParams[r'pattern_without_delimiter'] = parameterToString(patternWithoutDelimiter); + } + if (byte != null) { + formParams[r'byte'] = parameterToString(byte); + } + if (date != null) { + formParams[r'date'] = parameterToString(date); + } + if (dateTime != null) { + formParams[r'dateTime'] = parameterToString(dateTime); + } + if (password != null) { + formParams[r'password'] = parameterToString(password); + } + if (callback != null) { + formParams[r'callback'] = parameterToString(callback); } return await apiClient.invokeAPI( @@ -1007,30 +881,11 @@ class FakeApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = []; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (enumFormStringArray != null) { - hasFields = true; - mp.fields[r'enum_form_string_array'] = parameterToString(enumFormStringArray); - } - if (enumFormString != null) { - hasFields = true; - mp.fields[r'enum_form_string'] = parameterToString(enumFormString); - } - if (hasFields) { - postBody = mp; - } - } else { - if (enumFormStringArray != null) { - formParams[r'enum_form_string_array'] = parameterToString(enumFormStringArray); - } - if (enumFormString != null) { - formParams[r'enum_form_string'] = parameterToString(enumFormString); - } + if (enumFormStringArray != null) { + formParams[r'enum_form_string_array'] = parameterToString(enumFormStringArray); + } + if (enumFormString != null) { + formParams[r'enum_form_string'] = parameterToString(enumFormString); } return await apiClient.invokeAPI( @@ -1144,17 +999,6 @@ class FakeApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = ['bearer_test']; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -1224,17 +1068,6 @@ class FakeApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = []; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -1293,30 +1126,11 @@ class FakeApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = []; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (param != null) { - hasFields = true; - mp.fields[r'param'] = parameterToString(param); - } - if (param2 != null) { - hasFields = true; - mp.fields[r'param2'] = parameterToString(param2); - } - if (hasFields) { - postBody = mp; - } - } else { - if (param != null) { - formParams[r'param'] = parameterToString(param); - } - if (param2 != null) { - formParams[r'param2'] = parameterToString(param2); - } + if (param != null) { + formParams[r'param'] = parameterToString(param); + } + if (param2 != null) { + formParams[r'param2'] = parameterToString(param2); } return await apiClient.invokeAPI( @@ -1388,7 +1202,7 @@ class FakeApi { final headerParams = {}; final formParams = {}; - queryParams.addAll(_convertParametersForCollectionFormat('multi', 'pipe', pipe)); + queryParams.addAll(_convertParametersForCollectionFormat('pipes', 'pipe', pipe)); queryParams.addAll(_convertParametersForCollectionFormat('csv', 'ioutil', ioutil)); queryParams.addAll(_convertParametersForCollectionFormat('ssv', 'http', http)); queryParams.addAll(_convertParametersForCollectionFormat('csv', 'url', url)); @@ -1398,17 +1212,6 @@ class FakeApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = []; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api/fake_classname_tags123_api.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api/fake_classname_tags123_api.dart index f7e337dbee5..79ec2cbed45 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api/fake_classname_tags123_api.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api/fake_classname_tags123_api.dart @@ -43,17 +43,6 @@ class FakeClassnameTags123Api { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = ['api_key_query']; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api/pet_api.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api/pet_api.dart index af2215c4db7..50d001f61ce 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api/pet_api.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api/pet_api.dart @@ -41,17 +41,6 @@ class PetApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = ['petstore_auth']; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -111,17 +100,6 @@ class PetApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = ['petstore_auth']; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -180,17 +158,6 @@ class PetApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = ['petstore_auth']; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -258,17 +225,6 @@ class PetApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = ['petstore_auth']; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -335,17 +291,6 @@ class PetApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = ['api_key']; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -407,17 +352,6 @@ class PetApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = ['petstore_auth']; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -477,30 +411,11 @@ class PetApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = ['petstore_auth']; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (name != null) { - hasFields = true; - mp.fields[r'name'] = parameterToString(name); - } - if (status != null) { - hasFields = true; - mp.fields[r'status'] = parameterToString(status); - } - if (hasFields) { - postBody = mp; - } - } else { - if (name != null) { - formParams[r'name'] = parameterToString(name); - } - if (status != null) { - formParams[r'status'] = parameterToString(status); - } + if (name != null) { + formParams[r'name'] = parameterToString(name); + } + if (status != null) { + formParams[r'status'] = parameterToString(status); } return await apiClient.invokeAPI( @@ -567,28 +482,19 @@ class PetApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = ['petstore_auth']; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (additionalMetadata != null) { - hasFields = true; - mp.fields[r'additionalMetadata'] = parameterToString(additionalMetadata); - } - if (file != null) { - hasFields = true; - mp.fields[r'file'] = file.field; - mp.files.add(file); - } - if (hasFields) { - postBody = mp; - } - } else { - if (additionalMetadata != null) { - formParams[r'additionalMetadata'] = parameterToString(additionalMetadata); - } + bool hasFields = false; + final mp = MultipartRequest('POST', Uri.parse(path)); + if (additionalMetadata != null) { + hasFields = true; + mp.fields[r'additionalMetadata'] = parameterToString(additionalMetadata); + } + if (file != null) { + hasFields = true; + mp.fields[r'file'] = file.field; + mp.files.add(file); + } + if (hasFields) { + postBody = mp; } return await apiClient.invokeAPI( @@ -665,28 +571,19 @@ class PetApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = ['petstore_auth']; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (additionalMetadata != null) { - hasFields = true; - mp.fields[r'additionalMetadata'] = parameterToString(additionalMetadata); - } - if (requiredFile != null) { - hasFields = true; - mp.fields[r'requiredFile'] = requiredFile.field; - mp.files.add(requiredFile); - } - if (hasFields) { - postBody = mp; - } - } else { - if (additionalMetadata != null) { - formParams[r'additionalMetadata'] = parameterToString(additionalMetadata); - } + bool hasFields = false; + final mp = MultipartRequest('POST', Uri.parse(path)); + if (additionalMetadata != null) { + hasFields = true; + mp.fields[r'additionalMetadata'] = parameterToString(additionalMetadata); + } + if (requiredFile != null) { + hasFields = true; + mp.fields[r'requiredFile'] = requiredFile.field; + mp.files.add(requiredFile); + } + if (hasFields) { + postBody = mp; } return await apiClient.invokeAPI( diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api/store_api.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api/store_api.dart index ea459d16052..08a73bb8fca 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api/store_api.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api/store_api.dart @@ -44,17 +44,6 @@ class StoreApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = []; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -101,17 +90,6 @@ class StoreApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = ['api_key']; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -171,17 +149,6 @@ class StoreApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = []; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -243,17 +210,6 @@ class StoreApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = []; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api/user_api.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api/user_api.dart index 0a2c54c75fe..d45509dcac5 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api/user_api.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api/user_api.dart @@ -43,17 +43,6 @@ class UserApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = []; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -108,17 +97,6 @@ class UserApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = []; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -171,17 +149,6 @@ class UserApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = []; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -237,17 +204,6 @@ class UserApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = []; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -303,17 +259,6 @@ class UserApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = []; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -382,17 +327,6 @@ class UserApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = []; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -445,17 +379,6 @@ class UserApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = []; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -512,17 +435,6 @@ class UserApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = []; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api_client.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api_client.dart index 0aa83cf0197..cac7efad3bb 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api_client.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api_client.dart @@ -61,7 +61,7 @@ class ApiClient { Future invokeAPI( String path, String method, - Iterable queryParams, + List queryParams, Object body, Map headerParams, Map formParams, @@ -171,13 +171,13 @@ class ApiClient { List queryParams, Map headerParams, ) { - authNames.forEach((authName) { + for(final authName in authNames) { final auth = _authentications[authName]; if (auth == null) { throw ArgumentError('Authentication undefined: $authName'); } auth.applyToParams(queryParams, headerParams); - }); + } } static dynamic _deserialize(dynamic value, String targetType, {bool growable}) { diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api_exception.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api_exception.dart index 1537c9769b2..86e2054bffe 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api_exception.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api_exception.dart @@ -19,6 +19,7 @@ class ApiException implements Exception { Exception innerException; StackTrace stackTrace; + @override String toString() { if (message == null) { return 'ApiException'; diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api_helper.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api_helper.dart index 96214037944..474cfb4294f 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api_helper.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api_helper.dart @@ -28,7 +28,7 @@ Iterable _convertParametersForCollectionFormat( final params = []; // preconditions - if (name != null && !name.isEmpty && value != null) { + if (name != null && name.isNotEmpty && value != null) { if (value is List) { // get the collection format, default: csv collectionFormat = (collectionFormat == null || collectionFormat.isEmpty) diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/additional_properties_class.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/additional_properties_class.dart index 9e021e550b0..b62ac79d3e2 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/additional_properties_class.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/additional_properties_class.dart @@ -54,18 +54,18 @@ class AdditionalPropertiesClass { (json[r'map_property'] as Map).cast(), mapOfMapProperty: json[r'map_of_map_property'] == null ? null - : Map.mapFromJson(json[r'map_of_map_property']), + : (json[r'map_of_map_property'] as Map).cast(), ); static List listFromJson(List json, {bool emptyIsNull, bool growable,}) => json == null || json.isEmpty ? true == emptyIsNull ? null : [] - : json.map((v) => AdditionalPropertiesClass.fromJson(v)).toList(growable: true == growable); + : json.map((dynamic value) => AdditionalPropertiesClass.fromJson(value)).toList(growable: true == growable); static Map mapFromJson(Map json) { final map = {}; - if (json != null && json.isNotEmpty) { - json.forEach((String key, dynamic v) => map[key] = AdditionalPropertiesClass.fromJson(v)); + if (json?.isNotEmpty == true) { + json.forEach((key, value) => map[key] = AdditionalPropertiesClass.fromJson(value)); } return map; } @@ -73,9 +73,9 @@ class AdditionalPropertiesClass { // maps a json object with a list of AdditionalPropertiesClass-objects as value to a dart map static Map> mapListFromJson(Map json, {bool emptyIsNull, bool growable,}) { final map = >{}; - if (json != null && json.isNotEmpty) { - json.forEach((String key, dynamic v) { - map[key] = AdditionalPropertiesClass.listFromJson(v, emptyIsNull: emptyIsNull, growable: growable); + if (json?.isNotEmpty == true) { + json.forEach((key, value) { + map[key] = AdditionalPropertiesClass.listFromJson(value, emptyIsNull: emptyIsNull, growable: growable,); }); } return map; diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/animal.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/animal.dart index 9786d8358b2..ba9066e4ef7 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/animal.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/animal.dart @@ -54,12 +54,12 @@ class Animal { static List listFromJson(List json, {bool emptyIsNull, bool growable,}) => json == null || json.isEmpty ? true == emptyIsNull ? null : [] - : json.map((v) => Animal.fromJson(v)).toList(growable: true == growable); + : json.map((dynamic value) => Animal.fromJson(value)).toList(growable: true == growable); static Map mapFromJson(Map json) { final map = {}; - if (json != null && json.isNotEmpty) { - json.forEach((String key, dynamic v) => map[key] = Animal.fromJson(v)); + if (json?.isNotEmpty == true) { + json.forEach((key, value) => map[key] = Animal.fromJson(value)); } return map; } @@ -67,9 +67,9 @@ class Animal { // maps a json object with a list of Animal-objects as value to a dart map static Map> mapListFromJson(Map json, {bool emptyIsNull, bool growable,}) { final map = >{}; - if (json != null && json.isNotEmpty) { - json.forEach((String key, dynamic v) { - map[key] = Animal.listFromJson(v, emptyIsNull: emptyIsNull, growable: growable); + if (json?.isNotEmpty == true) { + json.forEach((key, value) { + map[key] = Animal.listFromJson(value, emptyIsNull: emptyIsNull, growable: growable,); }); } return map; diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/api_response.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/api_response.dart index bd80caff35c..6bb070b7eeb 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/api_response.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/api_response.dart @@ -65,12 +65,12 @@ class ApiResponse { static List listFromJson(List json, {bool emptyIsNull, bool growable,}) => json == null || json.isEmpty ? true == emptyIsNull ? null : [] - : json.map((v) => ApiResponse.fromJson(v)).toList(growable: true == growable); + : json.map((dynamic value) => ApiResponse.fromJson(value)).toList(growable: true == growable); static Map mapFromJson(Map json) { final map = {}; - if (json != null && json.isNotEmpty) { - json.forEach((String key, dynamic v) => map[key] = ApiResponse.fromJson(v)); + if (json?.isNotEmpty == true) { + json.forEach((key, value) => map[key] = ApiResponse.fromJson(value)); } return map; } @@ -78,9 +78,9 @@ class ApiResponse { // maps a json object with a list of ApiResponse-objects as value to a dart map static Map> mapListFromJson(Map json, {bool emptyIsNull, bool growable,}) { final map = >{}; - if (json != null && json.isNotEmpty) { - json.forEach((String key, dynamic v) { - map[key] = ApiResponse.listFromJson(v, emptyIsNull: emptyIsNull, growable: growable); + if (json?.isNotEmpty == true) { + json.forEach((key, value) { + map[key] = ApiResponse.listFromJson(value, emptyIsNull: emptyIsNull, growable: growable,); }); } return map; diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/array_of_array_of_number_only.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/array_of_array_of_number_only.dart index 7dac34b25c1..90ec9124de9 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/array_of_array_of_number_only.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/array_of_array_of_number_only.dart @@ -51,12 +51,12 @@ class ArrayOfArrayOfNumberOnly { static List listFromJson(List json, {bool emptyIsNull, bool growable,}) => json == null || json.isEmpty ? true == emptyIsNull ? null : [] - : json.map((v) => ArrayOfArrayOfNumberOnly.fromJson(v)).toList(growable: true == growable); + : json.map((dynamic value) => ArrayOfArrayOfNumberOnly.fromJson(value)).toList(growable: true == growable); static Map mapFromJson(Map json) { final map = {}; - if (json != null && json.isNotEmpty) { - json.forEach((String key, dynamic v) => map[key] = ArrayOfArrayOfNumberOnly.fromJson(v)); + if (json?.isNotEmpty == true) { + json.forEach((key, value) => map[key] = ArrayOfArrayOfNumberOnly.fromJson(value)); } return map; } @@ -64,9 +64,9 @@ class ArrayOfArrayOfNumberOnly { // maps a json object with a list of ArrayOfArrayOfNumberOnly-objects as value to a dart map static Map> mapListFromJson(Map json, {bool emptyIsNull, bool growable,}) { final map = >{}; - if (json != null && json.isNotEmpty) { - json.forEach((String key, dynamic v) { - map[key] = ArrayOfArrayOfNumberOnly.listFromJson(v, emptyIsNull: emptyIsNull, growable: growable); + if (json?.isNotEmpty == true) { + json.forEach((key, value) { + map[key] = ArrayOfArrayOfNumberOnly.listFromJson(value, emptyIsNull: emptyIsNull, growable: growable,); }); } return map; diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/array_of_number_only.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/array_of_number_only.dart index 7a1de48923a..19b93cc3d73 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/array_of_number_only.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/array_of_number_only.dart @@ -49,12 +49,12 @@ class ArrayOfNumberOnly { static List listFromJson(List json, {bool emptyIsNull, bool growable,}) => json == null || json.isEmpty ? true == emptyIsNull ? null : [] - : json.map((v) => ArrayOfNumberOnly.fromJson(v)).toList(growable: true == growable); + : json.map((dynamic value) => ArrayOfNumberOnly.fromJson(value)).toList(growable: true == growable); static Map mapFromJson(Map json) { final map = {}; - if (json != null && json.isNotEmpty) { - json.forEach((String key, dynamic v) => map[key] = ArrayOfNumberOnly.fromJson(v)); + if (json?.isNotEmpty == true) { + json.forEach((key, value) => map[key] = ArrayOfNumberOnly.fromJson(value)); } return map; } @@ -62,9 +62,9 @@ class ArrayOfNumberOnly { // maps a json object with a list of ArrayOfNumberOnly-objects as value to a dart map static Map> mapListFromJson(Map json, {bool emptyIsNull, bool growable,}) { final map = >{}; - if (json != null && json.isNotEmpty) { - json.forEach((String key, dynamic v) { - map[key] = ArrayOfNumberOnly.listFromJson(v, emptyIsNull: emptyIsNull, growable: growable); + if (json?.isNotEmpty == true) { + json.forEach((key, value) { + map[key] = ArrayOfNumberOnly.listFromJson(value, emptyIsNull: emptyIsNull, growable: growable,); }); } return map; diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/array_test.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/array_test.dart index 55b131a9e57..c911626fa13 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/array_test.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/array_test.dart @@ -75,12 +75,12 @@ class ArrayTest { static List listFromJson(List json, {bool emptyIsNull, bool growable,}) => json == null || json.isEmpty ? true == emptyIsNull ? null : [] - : json.map((v) => ArrayTest.fromJson(v)).toList(growable: true == growable); + : json.map((dynamic value) => ArrayTest.fromJson(value)).toList(growable: true == growable); static Map mapFromJson(Map json) { final map = {}; - if (json != null && json.isNotEmpty) { - json.forEach((String key, dynamic v) => map[key] = ArrayTest.fromJson(v)); + if (json?.isNotEmpty == true) { + json.forEach((key, value) => map[key] = ArrayTest.fromJson(value)); } return map; } @@ -88,9 +88,9 @@ class ArrayTest { // maps a json object with a list of ArrayTest-objects as value to a dart map static Map> mapListFromJson(Map json, {bool emptyIsNull, bool growable,}) { final map = >{}; - if (json != null && json.isNotEmpty) { - json.forEach((String key, dynamic v) { - map[key] = ArrayTest.listFromJson(v, emptyIsNull: emptyIsNull, growable: growable); + if (json?.isNotEmpty == true) { + json.forEach((key, value) { + map[key] = ArrayTest.listFromJson(value, emptyIsNull: emptyIsNull, growable: growable,); }); } return map; diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/capitalization.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/capitalization.dart index afab73b9769..7b60d37fd39 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/capitalization.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/capitalization.dart @@ -93,12 +93,12 @@ class Capitalization { static List listFromJson(List json, {bool emptyIsNull, bool growable,}) => json == null || json.isEmpty ? true == emptyIsNull ? null : [] - : json.map((v) => Capitalization.fromJson(v)).toList(growable: true == growable); + : json.map((dynamic value) => Capitalization.fromJson(value)).toList(growable: true == growable); static Map mapFromJson(Map json) { final map = {}; - if (json != null && json.isNotEmpty) { - json.forEach((String key, dynamic v) => map[key] = Capitalization.fromJson(v)); + if (json?.isNotEmpty == true) { + json.forEach((key, value) => map[key] = Capitalization.fromJson(value)); } return map; } @@ -106,9 +106,9 @@ class Capitalization { // maps a json object with a list of Capitalization-objects as value to a dart map static Map> mapListFromJson(Map json, {bool emptyIsNull, bool growable,}) { final map = >{}; - if (json != null && json.isNotEmpty) { - json.forEach((String key, dynamic v) { - map[key] = Capitalization.listFromJson(v, emptyIsNull: emptyIsNull, growable: growable); + if (json?.isNotEmpty == true) { + json.forEach((key, value) { + map[key] = Capitalization.listFromJson(value, emptyIsNull: emptyIsNull, growable: growable,); }); } return map; diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/cat.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/cat.dart index 704152151d8..94d0b96a9c7 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/cat.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/cat.dart @@ -63,12 +63,12 @@ class Cat { static List listFromJson(List json, {bool emptyIsNull, bool growable,}) => json == null || json.isEmpty ? true == emptyIsNull ? null : [] - : json.map((v) => Cat.fromJson(v)).toList(growable: true == growable); + : json.map((dynamic value) => Cat.fromJson(value)).toList(growable: true == growable); static Map mapFromJson(Map json) { final map = {}; - if (json != null && json.isNotEmpty) { - json.forEach((String key, dynamic v) => map[key] = Cat.fromJson(v)); + if (json?.isNotEmpty == true) { + json.forEach((key, value) => map[key] = Cat.fromJson(value)); } return map; } @@ -76,9 +76,9 @@ class Cat { // maps a json object with a list of Cat-objects as value to a dart map static Map> mapListFromJson(Map json, {bool emptyIsNull, bool growable,}) { final map = >{}; - if (json != null && json.isNotEmpty) { - json.forEach((String key, dynamic v) { - map[key] = Cat.listFromJson(v, emptyIsNull: emptyIsNull, growable: growable); + if (json?.isNotEmpty == true) { + json.forEach((key, value) { + map[key] = Cat.listFromJson(value, emptyIsNull: emptyIsNull, growable: growable,); }); } return map; diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/cat_all_of.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/cat_all_of.dart index 307e777da3d..e3fe4944874 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/cat_all_of.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/cat_all_of.dart @@ -47,12 +47,12 @@ class CatAllOf { static List listFromJson(List json, {bool emptyIsNull, bool growable,}) => json == null || json.isEmpty ? true == emptyIsNull ? null : [] - : json.map((v) => CatAllOf.fromJson(v)).toList(growable: true == growable); + : json.map((dynamic value) => CatAllOf.fromJson(value)).toList(growable: true == growable); static Map mapFromJson(Map json) { final map = {}; - if (json != null && json.isNotEmpty) { - json.forEach((String key, dynamic v) => map[key] = CatAllOf.fromJson(v)); + if (json?.isNotEmpty == true) { + json.forEach((key, value) => map[key] = CatAllOf.fromJson(value)); } return map; } @@ -60,9 +60,9 @@ class CatAllOf { // maps a json object with a list of CatAllOf-objects as value to a dart map static Map> mapListFromJson(Map json, {bool emptyIsNull, bool growable,}) { final map = >{}; - if (json != null && json.isNotEmpty) { - json.forEach((String key, dynamic v) { - map[key] = CatAllOf.listFromJson(v, emptyIsNull: emptyIsNull, growable: growable); + if (json?.isNotEmpty == true) { + json.forEach((key, value) { + map[key] = CatAllOf.listFromJson(value, emptyIsNull: emptyIsNull, growable: growable,); }); } return map; diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/category.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/category.dart index 59249c157a0..eddc54e7315 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/category.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/category.dart @@ -54,12 +54,12 @@ class Category { static List listFromJson(List json, {bool emptyIsNull, bool growable,}) => json == null || json.isEmpty ? true == emptyIsNull ? null : [] - : json.map((v) => Category.fromJson(v)).toList(growable: true == growable); + : json.map((dynamic value) => Category.fromJson(value)).toList(growable: true == growable); static Map mapFromJson(Map json) { final map = {}; - if (json != null && json.isNotEmpty) { - json.forEach((String key, dynamic v) => map[key] = Category.fromJson(v)); + if (json?.isNotEmpty == true) { + json.forEach((key, value) => map[key] = Category.fromJson(value)); } return map; } @@ -67,9 +67,9 @@ class Category { // maps a json object with a list of Category-objects as value to a dart map static Map> mapListFromJson(Map json, {bool emptyIsNull, bool growable,}) { final map = >{}; - if (json != null && json.isNotEmpty) { - json.forEach((String key, dynamic v) { - map[key] = Category.listFromJson(v, emptyIsNull: emptyIsNull, growable: growable); + if (json?.isNotEmpty == true) { + json.forEach((key, value) { + map[key] = Category.listFromJson(value, emptyIsNull: emptyIsNull, growable: growable,); }); } return map; diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/class_model.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/class_model.dart index 9192701eafd..927f01e06b6 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/class_model.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/class_model.dart @@ -47,12 +47,12 @@ class ClassModel { static List listFromJson(List json, {bool emptyIsNull, bool growable,}) => json == null || json.isEmpty ? true == emptyIsNull ? null : [] - : json.map((v) => ClassModel.fromJson(v)).toList(growable: true == growable); + : json.map((dynamic value) => ClassModel.fromJson(value)).toList(growable: true == growable); static Map mapFromJson(Map json) { final map = {}; - if (json != null && json.isNotEmpty) { - json.forEach((String key, dynamic v) => map[key] = ClassModel.fromJson(v)); + if (json?.isNotEmpty == true) { + json.forEach((key, value) => map[key] = ClassModel.fromJson(value)); } return map; } @@ -60,9 +60,9 @@ class ClassModel { // maps a json object with a list of ClassModel-objects as value to a dart map static Map> mapListFromJson(Map json, {bool emptyIsNull, bool growable,}) { final map = >{}; - if (json != null && json.isNotEmpty) { - json.forEach((String key, dynamic v) { - map[key] = ClassModel.listFromJson(v, emptyIsNull: emptyIsNull, growable: growable); + if (json?.isNotEmpty == true) { + json.forEach((key, value) { + map[key] = ClassModel.listFromJson(value, emptyIsNull: emptyIsNull, growable: growable,); }); } return map; diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/dog.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/dog.dart index eb08c1e227c..3a1efcb1c4f 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/dog.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/dog.dart @@ -63,12 +63,12 @@ class Dog { static List listFromJson(List json, {bool emptyIsNull, bool growable,}) => json == null || json.isEmpty ? true == emptyIsNull ? null : [] - : json.map((v) => Dog.fromJson(v)).toList(growable: true == growable); + : json.map((dynamic value) => Dog.fromJson(value)).toList(growable: true == growable); static Map mapFromJson(Map json) { final map = {}; - if (json != null && json.isNotEmpty) { - json.forEach((String key, dynamic v) => map[key] = Dog.fromJson(v)); + if (json?.isNotEmpty == true) { + json.forEach((key, value) => map[key] = Dog.fromJson(value)); } return map; } @@ -76,9 +76,9 @@ class Dog { // maps a json object with a list of Dog-objects as value to a dart map static Map> mapListFromJson(Map json, {bool emptyIsNull, bool growable,}) { final map = >{}; - if (json != null && json.isNotEmpty) { - json.forEach((String key, dynamic v) { - map[key] = Dog.listFromJson(v, emptyIsNull: emptyIsNull, growable: growable); + if (json?.isNotEmpty == true) { + json.forEach((key, value) { + map[key] = Dog.listFromJson(value, emptyIsNull: emptyIsNull, growable: growable,); }); } return map; diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/dog_all_of.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/dog_all_of.dart index 0199b8707d1..a77ba88b0bf 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/dog_all_of.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/dog_all_of.dart @@ -47,12 +47,12 @@ class DogAllOf { static List listFromJson(List json, {bool emptyIsNull, bool growable,}) => json == null || json.isEmpty ? true == emptyIsNull ? null : [] - : json.map((v) => DogAllOf.fromJson(v)).toList(growable: true == growable); + : json.map((dynamic value) => DogAllOf.fromJson(value)).toList(growable: true == growable); static Map mapFromJson(Map json) { final map = {}; - if (json != null && json.isNotEmpty) { - json.forEach((String key, dynamic v) => map[key] = DogAllOf.fromJson(v)); + if (json?.isNotEmpty == true) { + json.forEach((key, value) => map[key] = DogAllOf.fromJson(value)); } return map; } @@ -60,9 +60,9 @@ class DogAllOf { // maps a json object with a list of DogAllOf-objects as value to a dart map static Map> mapListFromJson(Map json, {bool emptyIsNull, bool growable,}) { final map = >{}; - if (json != null && json.isNotEmpty) { - json.forEach((String key, dynamic v) { - map[key] = DogAllOf.listFromJson(v, emptyIsNull: emptyIsNull, growable: growable); + if (json?.isNotEmpty == true) { + json.forEach((key, value) { + map[key] = DogAllOf.listFromJson(value, emptyIsNull: emptyIsNull, growable: growable,); }); } return map; diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/enum_arrays.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/enum_arrays.dart index f0e7b2417db..dc994bc308a 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/enum_arrays.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/enum_arrays.dart @@ -56,12 +56,12 @@ class EnumArrays { static List listFromJson(List json, {bool emptyIsNull, bool growable,}) => json == null || json.isEmpty ? true == emptyIsNull ? null : [] - : json.map((v) => EnumArrays.fromJson(v)).toList(growable: true == growable); + : json.map((dynamic value) => EnumArrays.fromJson(value)).toList(growable: true == growable); static Map mapFromJson(Map json) { final map = {}; - if (json != null && json.isNotEmpty) { - json.forEach((String key, dynamic v) => map[key] = EnumArrays.fromJson(v)); + if (json?.isNotEmpty == true) { + json.forEach((key, value) => map[key] = EnumArrays.fromJson(value)); } return map; } @@ -69,9 +69,9 @@ class EnumArrays { // maps a json object with a list of EnumArrays-objects as value to a dart map static Map> mapListFromJson(Map json, {bool emptyIsNull, bool growable,}) { final map = >{}; - if (json != null && json.isNotEmpty) { - json.forEach((String key, dynamic v) { - map[key] = EnumArrays.listFromJson(v, emptyIsNull: emptyIsNull, growable: growable); + if (json?.isNotEmpty == true) { + json.forEach((key, value) { + map[key] = EnumArrays.listFromJson(value, emptyIsNull: emptyIsNull, growable: growable,); }); } return map; diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/enum_test.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/enum_test.dart index ae432599c99..51a444f1cea 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/enum_test.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/enum_test.dart @@ -108,12 +108,12 @@ class EnumTest { static List listFromJson(List json, {bool emptyIsNull, bool growable,}) => json == null || json.isEmpty ? true == emptyIsNull ? null : [] - : json.map((v) => EnumTest.fromJson(v)).toList(growable: true == growable); + : json.map((dynamic value) => EnumTest.fromJson(value)).toList(growable: true == growable); static Map mapFromJson(Map json) { final map = {}; - if (json != null && json.isNotEmpty) { - json.forEach((String key, dynamic v) => map[key] = EnumTest.fromJson(v)); + if (json?.isNotEmpty == true) { + json.forEach((key, value) => map[key] = EnumTest.fromJson(value)); } return map; } @@ -121,9 +121,9 @@ class EnumTest { // maps a json object with a list of EnumTest-objects as value to a dart map static Map> mapListFromJson(Map json, {bool emptyIsNull, bool growable,}) { final map = >{}; - if (json != null && json.isNotEmpty) { - json.forEach((String key, dynamic v) { - map[key] = EnumTest.listFromJson(v, emptyIsNull: emptyIsNull, growable: growable); + if (json?.isNotEmpty == true) { + json.forEach((key, value) { + map[key] = EnumTest.listFromJson(value, emptyIsNull: emptyIsNull, growable: growable,); }); } return map; diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/file_schema_test_class.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/file_schema_test_class.dart index fb5f7593554..4f659cddafa 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/file_schema_test_class.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/file_schema_test_class.dart @@ -56,12 +56,12 @@ class FileSchemaTestClass { static List listFromJson(List json, {bool emptyIsNull, bool growable,}) => json == null || json.isEmpty ? true == emptyIsNull ? null : [] - : json.map((v) => FileSchemaTestClass.fromJson(v)).toList(growable: true == growable); + : json.map((dynamic value) => FileSchemaTestClass.fromJson(value)).toList(growable: true == growable); static Map mapFromJson(Map json) { final map = {}; - if (json != null && json.isNotEmpty) { - json.forEach((String key, dynamic v) => map[key] = FileSchemaTestClass.fromJson(v)); + if (json?.isNotEmpty == true) { + json.forEach((key, value) => map[key] = FileSchemaTestClass.fromJson(value)); } return map; } @@ -69,9 +69,9 @@ class FileSchemaTestClass { // maps a json object with a list of FileSchemaTestClass-objects as value to a dart map static Map> mapListFromJson(Map json, {bool emptyIsNull, bool growable,}) { final map = >{}; - if (json != null && json.isNotEmpty) { - json.forEach((String key, dynamic v) { - map[key] = FileSchemaTestClass.listFromJson(v, emptyIsNull: emptyIsNull, growable: growable); + if (json?.isNotEmpty == true) { + json.forEach((key, value) { + map[key] = FileSchemaTestClass.listFromJson(value, emptyIsNull: emptyIsNull, growable: growable,); }); } return map; diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/foo.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/foo.dart index 19994af4cfe..4100fa1fa04 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/foo.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/foo.dart @@ -47,12 +47,12 @@ class Foo { static List listFromJson(List json, {bool emptyIsNull, bool growable,}) => json == null || json.isEmpty ? true == emptyIsNull ? null : [] - : json.map((v) => Foo.fromJson(v)).toList(growable: true == growable); + : json.map((dynamic value) => Foo.fromJson(value)).toList(growable: true == growable); static Map mapFromJson(Map json) { final map = {}; - if (json != null && json.isNotEmpty) { - json.forEach((String key, dynamic v) => map[key] = Foo.fromJson(v)); + if (json?.isNotEmpty == true) { + json.forEach((key, value) => map[key] = Foo.fromJson(value)); } return map; } @@ -60,9 +60,9 @@ class Foo { // maps a json object with a list of Foo-objects as value to a dart map static Map> mapListFromJson(Map json, {bool emptyIsNull, bool growable,}) { final map = >{}; - if (json != null && json.isNotEmpty) { - json.forEach((String key, dynamic v) { - map[key] = Foo.listFromJson(v, emptyIsNull: emptyIsNull, growable: growable); + if (json?.isNotEmpty == true) { + json.forEach((key, value) { + map[key] = Foo.listFromJson(value, emptyIsNull: emptyIsNull, growable: growable,); }); } return map; diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/format_test.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/format_test.dart index f0f2236ba88..5f735c24f86 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/format_test.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/format_test.dart @@ -192,12 +192,12 @@ class FormatTest { static List listFromJson(List json, {bool emptyIsNull, bool growable,}) => json == null || json.isEmpty ? true == emptyIsNull ? null : [] - : json.map((v) => FormatTest.fromJson(v)).toList(growable: true == growable); + : json.map((dynamic value) => FormatTest.fromJson(value)).toList(growable: true == growable); static Map mapFromJson(Map json) { final map = {}; - if (json != null && json.isNotEmpty) { - json.forEach((String key, dynamic v) => map[key] = FormatTest.fromJson(v)); + if (json?.isNotEmpty == true) { + json.forEach((key, value) => map[key] = FormatTest.fromJson(value)); } return map; } @@ -205,9 +205,9 @@ class FormatTest { // maps a json object with a list of FormatTest-objects as value to a dart map static Map> mapListFromJson(Map json, {bool emptyIsNull, bool growable,}) { final map = >{}; - if (json != null && json.isNotEmpty) { - json.forEach((String key, dynamic v) { - map[key] = FormatTest.listFromJson(v, emptyIsNull: emptyIsNull, growable: growable); + if (json?.isNotEmpty == true) { + json.forEach((key, value) { + map[key] = FormatTest.listFromJson(value, emptyIsNull: emptyIsNull, growable: growable,); }); } return map; diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/has_only_read_only.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/has_only_read_only.dart index 2054a4594f3..dee44032840 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/has_only_read_only.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/has_only_read_only.dart @@ -56,12 +56,12 @@ class HasOnlyReadOnly { static List listFromJson(List json, {bool emptyIsNull, bool growable,}) => json == null || json.isEmpty ? true == emptyIsNull ? null : [] - : json.map((v) => HasOnlyReadOnly.fromJson(v)).toList(growable: true == growable); + : json.map((dynamic value) => HasOnlyReadOnly.fromJson(value)).toList(growable: true == growable); static Map mapFromJson(Map json) { final map = {}; - if (json != null && json.isNotEmpty) { - json.forEach((String key, dynamic v) => map[key] = HasOnlyReadOnly.fromJson(v)); + if (json?.isNotEmpty == true) { + json.forEach((key, value) => map[key] = HasOnlyReadOnly.fromJson(value)); } return map; } @@ -69,9 +69,9 @@ class HasOnlyReadOnly { // maps a json object with a list of HasOnlyReadOnly-objects as value to a dart map static Map> mapListFromJson(Map json, {bool emptyIsNull, bool growable,}) { final map = >{}; - if (json != null && json.isNotEmpty) { - json.forEach((String key, dynamic v) { - map[key] = HasOnlyReadOnly.listFromJson(v, emptyIsNull: emptyIsNull, growable: growable); + if (json?.isNotEmpty == true) { + json.forEach((key, value) { + map[key] = HasOnlyReadOnly.listFromJson(value, emptyIsNull: emptyIsNull, growable: growable,); }); } return map; diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/health_check_result.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/health_check_result.dart index 1ea8db9305c..06a044bb153 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/health_check_result.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/health_check_result.dart @@ -47,12 +47,12 @@ class HealthCheckResult { static List listFromJson(List json, {bool emptyIsNull, bool growable,}) => json == null || json.isEmpty ? true == emptyIsNull ? null : [] - : json.map((v) => HealthCheckResult.fromJson(v)).toList(growable: true == growable); + : json.map((dynamic value) => HealthCheckResult.fromJson(value)).toList(growable: true == growable); static Map mapFromJson(Map json) { final map = {}; - if (json != null && json.isNotEmpty) { - json.forEach((String key, dynamic v) => map[key] = HealthCheckResult.fromJson(v)); + if (json?.isNotEmpty == true) { + json.forEach((key, value) => map[key] = HealthCheckResult.fromJson(value)); } return map; } @@ -60,9 +60,9 @@ class HealthCheckResult { // maps a json object with a list of HealthCheckResult-objects as value to a dart map static Map> mapListFromJson(Map json, {bool emptyIsNull, bool growable,}) { final map = >{}; - if (json != null && json.isNotEmpty) { - json.forEach((String key, dynamic v) { - map[key] = HealthCheckResult.listFromJson(v, emptyIsNull: emptyIsNull, growable: growable); + if (json?.isNotEmpty == true) { + json.forEach((key, value) { + map[key] = HealthCheckResult.listFromJson(value, emptyIsNull: emptyIsNull, growable: growable,); }); } return map; diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/inline_response_default.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/inline_response_default.dart index c48b5c28e70..1cdee99a2de 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/inline_response_default.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/inline_response_default.dart @@ -47,12 +47,12 @@ class InlineResponseDefault { static List listFromJson(List json, {bool emptyIsNull, bool growable,}) => json == null || json.isEmpty ? true == emptyIsNull ? null : [] - : json.map((v) => InlineResponseDefault.fromJson(v)).toList(growable: true == growable); + : json.map((dynamic value) => InlineResponseDefault.fromJson(value)).toList(growable: true == growable); static Map mapFromJson(Map json) { final map = {}; - if (json != null && json.isNotEmpty) { - json.forEach((String key, dynamic v) => map[key] = InlineResponseDefault.fromJson(v)); + if (json?.isNotEmpty == true) { + json.forEach((key, value) => map[key] = InlineResponseDefault.fromJson(value)); } return map; } @@ -60,9 +60,9 @@ class InlineResponseDefault { // maps a json object with a list of InlineResponseDefault-objects as value to a dart map static Map> mapListFromJson(Map json, {bool emptyIsNull, bool growable,}) { final map = >{}; - if (json != null && json.isNotEmpty) { - json.forEach((String key, dynamic v) { - map[key] = InlineResponseDefault.listFromJson(v, emptyIsNull: emptyIsNull, growable: growable); + if (json?.isNotEmpty == true) { + json.forEach((key, value) { + map[key] = InlineResponseDefault.listFromJson(value, emptyIsNull: emptyIsNull, growable: growable,); }); } return map; diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/map_test.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/map_test.dart index 9843c474910..23a54bd34ae 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/map_test.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/map_test.dart @@ -67,7 +67,7 @@ class MapTest { : MapTest( mapMapOfString: json[r'map_map_of_string'] == null ? null - : Map.mapFromJson(json[r'map_map_of_string']), + : (json[r'map_map_of_string'] as Map).cast(), mapOfEnumString: json[r'map_of_enum_string'] == null ? null : (json[r'map_of_enum_string'] as Map).cast(), @@ -82,12 +82,12 @@ class MapTest { static List listFromJson(List json, {bool emptyIsNull, bool growable,}) => json == null || json.isEmpty ? true == emptyIsNull ? null : [] - : json.map((v) => MapTest.fromJson(v)).toList(growable: true == growable); + : json.map((dynamic value) => MapTest.fromJson(value)).toList(growable: true == growable); static Map mapFromJson(Map json) { final map = {}; - if (json != null && json.isNotEmpty) { - json.forEach((String key, dynamic v) => map[key] = MapTest.fromJson(v)); + if (json?.isNotEmpty == true) { + json.forEach((key, value) => map[key] = MapTest.fromJson(value)); } return map; } @@ -95,9 +95,9 @@ class MapTest { // maps a json object with a list of MapTest-objects as value to a dart map static Map> mapListFromJson(Map json, {bool emptyIsNull, bool growable,}) { final map = >{}; - if (json != null && json.isNotEmpty) { - json.forEach((String key, dynamic v) { - map[key] = MapTest.listFromJson(v, emptyIsNull: emptyIsNull, growable: growable); + if (json?.isNotEmpty == true) { + json.forEach((key, value) { + map[key] = MapTest.listFromJson(value, emptyIsNull: emptyIsNull, growable: growable,); }); } return map; diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/mixed_properties_and_additional_properties_class.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/mixed_properties_and_additional_properties_class.dart index b9a202de856..053427aafd1 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/mixed_properties_and_additional_properties_class.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/mixed_properties_and_additional_properties_class.dart @@ -61,20 +61,18 @@ class MixedPropertiesAndAdditionalPropertiesClass { dateTime: json[r'dateTime'] == null ? null : DateTime.parse(json[r'dateTime']), - map: json[r'map'] == null - ? null - : Animal.mapFromJson(json[r'map']), + map: json[r'map'] ); static List listFromJson(List json, {bool emptyIsNull, bool growable,}) => json == null || json.isEmpty ? true == emptyIsNull ? null : [] - : json.map((v) => MixedPropertiesAndAdditionalPropertiesClass.fromJson(v)).toList(growable: true == growable); + : json.map((dynamic value) => MixedPropertiesAndAdditionalPropertiesClass.fromJson(value)).toList(growable: true == growable); static Map mapFromJson(Map json) { final map = {}; - if (json != null && json.isNotEmpty) { - json.forEach((String key, dynamic v) => map[key] = MixedPropertiesAndAdditionalPropertiesClass.fromJson(v)); + if (json?.isNotEmpty == true) { + json.forEach((key, value) => map[key] = MixedPropertiesAndAdditionalPropertiesClass.fromJson(value)); } return map; } @@ -82,9 +80,9 @@ class MixedPropertiesAndAdditionalPropertiesClass { // maps a json object with a list of MixedPropertiesAndAdditionalPropertiesClass-objects as value to a dart map static Map> mapListFromJson(Map json, {bool emptyIsNull, bool growable,}) { final map = >{}; - if (json != null && json.isNotEmpty) { - json.forEach((String key, dynamic v) { - map[key] = MixedPropertiesAndAdditionalPropertiesClass.listFromJson(v, emptyIsNull: emptyIsNull, growable: growable); + if (json?.isNotEmpty == true) { + json.forEach((key, value) { + map[key] = MixedPropertiesAndAdditionalPropertiesClass.listFromJson(value, emptyIsNull: emptyIsNull, growable: growable,); }); } return map; diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/model200_response.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/model200_response.dart index 15ecf90f50a..169581175eb 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/model200_response.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/model200_response.dart @@ -56,12 +56,12 @@ class Model200Response { static List listFromJson(List json, {bool emptyIsNull, bool growable,}) => json == null || json.isEmpty ? true == emptyIsNull ? null : [] - : json.map((v) => Model200Response.fromJson(v)).toList(growable: true == growable); + : json.map((dynamic value) => Model200Response.fromJson(value)).toList(growable: true == growable); static Map mapFromJson(Map json) { final map = {}; - if (json != null && json.isNotEmpty) { - json.forEach((String key, dynamic v) => map[key] = Model200Response.fromJson(v)); + if (json?.isNotEmpty == true) { + json.forEach((key, value) => map[key] = Model200Response.fromJson(value)); } return map; } @@ -69,9 +69,9 @@ class Model200Response { // maps a json object with a list of Model200Response-objects as value to a dart map static Map> mapListFromJson(Map json, {bool emptyIsNull, bool growable,}) { final map = >{}; - if (json != null && json.isNotEmpty) { - json.forEach((String key, dynamic v) { - map[key] = Model200Response.listFromJson(v, emptyIsNull: emptyIsNull, growable: growable); + if (json?.isNotEmpty == true) { + json.forEach((key, value) { + map[key] = Model200Response.listFromJson(value, emptyIsNull: emptyIsNull, growable: growable,); }); } return map; diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/model_client.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/model_client.dart index 08b98859176..039517160be 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/model_client.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/model_client.dart @@ -47,12 +47,12 @@ class ModelClient { static List listFromJson(List json, {bool emptyIsNull, bool growable,}) => json == null || json.isEmpty ? true == emptyIsNull ? null : [] - : json.map((v) => ModelClient.fromJson(v)).toList(growable: true == growable); + : json.map((dynamic value) => ModelClient.fromJson(value)).toList(growable: true == growable); static Map mapFromJson(Map json) { final map = {}; - if (json != null && json.isNotEmpty) { - json.forEach((String key, dynamic v) => map[key] = ModelClient.fromJson(v)); + if (json?.isNotEmpty == true) { + json.forEach((key, value) => map[key] = ModelClient.fromJson(value)); } return map; } @@ -60,9 +60,9 @@ class ModelClient { // maps a json object with a list of ModelClient-objects as value to a dart map static Map> mapListFromJson(Map json, {bool emptyIsNull, bool growable,}) { final map = >{}; - if (json != null && json.isNotEmpty) { - json.forEach((String key, dynamic v) { - map[key] = ModelClient.listFromJson(v, emptyIsNull: emptyIsNull, growable: growable); + if (json?.isNotEmpty == true) { + json.forEach((key, value) { + map[key] = ModelClient.listFromJson(value, emptyIsNull: emptyIsNull, growable: growable,); }); } return map; diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/model_file.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/model_file.dart index 0ca3001c062..251cb11748b 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/model_file.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/model_file.dart @@ -48,12 +48,12 @@ class ModelFile { static List listFromJson(List json, {bool emptyIsNull, bool growable,}) => json == null || json.isEmpty ? true == emptyIsNull ? null : [] - : json.map((v) => ModelFile.fromJson(v)).toList(growable: true == growable); + : json.map((dynamic value) => ModelFile.fromJson(value)).toList(growable: true == growable); static Map mapFromJson(Map json) { final map = {}; - if (json != null && json.isNotEmpty) { - json.forEach((String key, dynamic v) => map[key] = ModelFile.fromJson(v)); + if (json?.isNotEmpty == true) { + json.forEach((key, value) => map[key] = ModelFile.fromJson(value)); } return map; } @@ -61,9 +61,9 @@ class ModelFile { // maps a json object with a list of ModelFile-objects as value to a dart map static Map> mapListFromJson(Map json, {bool emptyIsNull, bool growable,}) { final map = >{}; - if (json != null && json.isNotEmpty) { - json.forEach((String key, dynamic v) { - map[key] = ModelFile.listFromJson(v, emptyIsNull: emptyIsNull, growable: growable); + if (json?.isNotEmpty == true) { + json.forEach((key, value) { + map[key] = ModelFile.listFromJson(value, emptyIsNull: emptyIsNull, growable: growable,); }); } return map; diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/model_list.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/model_list.dart index 973198375ad..c269cec60cf 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/model_list.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/model_list.dart @@ -47,12 +47,12 @@ class ModelList { static List listFromJson(List json, {bool emptyIsNull, bool growable,}) => json == null || json.isEmpty ? true == emptyIsNull ? null : [] - : json.map((v) => ModelList.fromJson(v)).toList(growable: true == growable); + : json.map((dynamic value) => ModelList.fromJson(value)).toList(growable: true == growable); static Map mapFromJson(Map json) { final map = {}; - if (json != null && json.isNotEmpty) { - json.forEach((String key, dynamic v) => map[key] = ModelList.fromJson(v)); + if (json?.isNotEmpty == true) { + json.forEach((key, value) => map[key] = ModelList.fromJson(value)); } return map; } @@ -60,9 +60,9 @@ class ModelList { // maps a json object with a list of ModelList-objects as value to a dart map static Map> mapListFromJson(Map json, {bool emptyIsNull, bool growable,}) { final map = >{}; - if (json != null && json.isNotEmpty) { - json.forEach((String key, dynamic v) { - map[key] = ModelList.listFromJson(v, emptyIsNull: emptyIsNull, growable: growable); + if (json?.isNotEmpty == true) { + json.forEach((key, value) { + map[key] = ModelList.listFromJson(value, emptyIsNull: emptyIsNull, growable: growable,); }); } return map; diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/model_return.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/model_return.dart index 50c58ca70f1..b4a37d9f633 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/model_return.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/model_return.dart @@ -47,12 +47,12 @@ class ModelReturn { static List listFromJson(List json, {bool emptyIsNull, bool growable,}) => json == null || json.isEmpty ? true == emptyIsNull ? null : [] - : json.map((v) => ModelReturn.fromJson(v)).toList(growable: true == growable); + : json.map((dynamic value) => ModelReturn.fromJson(value)).toList(growable: true == growable); static Map mapFromJson(Map json) { final map = {}; - if (json != null && json.isNotEmpty) { - json.forEach((String key, dynamic v) => map[key] = ModelReturn.fromJson(v)); + if (json?.isNotEmpty == true) { + json.forEach((key, value) => map[key] = ModelReturn.fromJson(value)); } return map; } @@ -60,9 +60,9 @@ class ModelReturn { // maps a json object with a list of ModelReturn-objects as value to a dart map static Map> mapListFromJson(Map json, {bool emptyIsNull, bool growable,}) { final map = >{}; - if (json != null && json.isNotEmpty) { - json.forEach((String key, dynamic v) { - map[key] = ModelReturn.listFromJson(v, emptyIsNull: emptyIsNull, growable: growable); + if (json?.isNotEmpty == true) { + json.forEach((key, value) { + map[key] = ModelReturn.listFromJson(value, emptyIsNull: emptyIsNull, growable: growable,); }); } return map; diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/name.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/name.dart index 264c1a8c04d..9068f61d639 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/name.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/name.dart @@ -72,12 +72,12 @@ class Name { static List listFromJson(List json, {bool emptyIsNull, bool growable,}) => json == null || json.isEmpty ? true == emptyIsNull ? null : [] - : json.map((v) => Name.fromJson(v)).toList(growable: true == growable); + : json.map((dynamic value) => Name.fromJson(value)).toList(growable: true == growable); static Map mapFromJson(Map json) { final map = {}; - if (json != null && json.isNotEmpty) { - json.forEach((String key, dynamic v) => map[key] = Name.fromJson(v)); + if (json?.isNotEmpty == true) { + json.forEach((key, value) => map[key] = Name.fromJson(value)); } return map; } @@ -85,9 +85,9 @@ class Name { // maps a json object with a list of Name-objects as value to a dart map static Map> mapListFromJson(Map json, {bool emptyIsNull, bool growable,}) { final map = >{}; - if (json != null && json.isNotEmpty) { - json.forEach((String key, dynamic v) { - map[key] = Name.listFromJson(v, emptyIsNull: emptyIsNull, growable: growable); + if (json?.isNotEmpty == true) { + json.forEach((key, value) { + map[key] = Name.listFromJson(value, emptyIsNull: emptyIsNull, growable: growable,); }); } return map; diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/nullable_class.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/nullable_class.dart index 0295e97b0d2..f1df88a935a 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/nullable_class.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/nullable_class.dart @@ -144,26 +144,20 @@ class NullableClass { arrayNullableProp: Object.listFromJson(json[r'array_nullable_prop']), arrayAndItemsNullableProp: Object.listFromJson(json[r'array_and_items_nullable_prop']), arrayItemsNullable: Object.listFromJson(json[r'array_items_nullable']), - objectNullableProp: json[r'object_nullable_prop'] == null - ? null - : Object.mapFromJson(json[r'object_nullable_prop']), - objectAndItemsNullableProp: json[r'object_and_items_nullable_prop'] == null - ? null - : Object.mapFromJson(json[r'object_and_items_nullable_prop']), - objectItemsNullable: json[r'object_items_nullable'] == null - ? null - : Object.mapFromJson(json[r'object_items_nullable']), + objectNullableProp: json[r'object_nullable_prop'] + objectAndItemsNullableProp: json[r'object_and_items_nullable_prop'] + objectItemsNullable: json[r'object_items_nullable'] ); static List listFromJson(List json, {bool emptyIsNull, bool growable,}) => json == null || json.isEmpty ? true == emptyIsNull ? null : [] - : json.map((v) => NullableClass.fromJson(v)).toList(growable: true == growable); + : json.map((dynamic value) => NullableClass.fromJson(value)).toList(growable: true == growable); static Map mapFromJson(Map json) { final map = {}; - if (json != null && json.isNotEmpty) { - json.forEach((String key, dynamic v) => map[key] = NullableClass.fromJson(v)); + if (json?.isNotEmpty == true) { + json.forEach((key, value) => map[key] = NullableClass.fromJson(value)); } return map; } @@ -171,9 +165,9 @@ class NullableClass { // maps a json object with a list of NullableClass-objects as value to a dart map static Map> mapListFromJson(Map json, {bool emptyIsNull, bool growable,}) { final map = >{}; - if (json != null && json.isNotEmpty) { - json.forEach((String key, dynamic v) { - map[key] = NullableClass.listFromJson(v, emptyIsNull: emptyIsNull, growable: growable); + if (json?.isNotEmpty == true) { + json.forEach((key, value) { + map[key] = NullableClass.listFromJson(value, emptyIsNull: emptyIsNull, growable: growable,); }); } return map; diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/number_only.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/number_only.dart index d710d3b50b2..16cc2514577 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/number_only.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/number_only.dart @@ -49,12 +49,12 @@ class NumberOnly { static List listFromJson(List json, {bool emptyIsNull, bool growable,}) => json == null || json.isEmpty ? true == emptyIsNull ? null : [] - : json.map((v) => NumberOnly.fromJson(v)).toList(growable: true == growable); + : json.map((dynamic value) => NumberOnly.fromJson(value)).toList(growable: true == growable); static Map mapFromJson(Map json) { final map = {}; - if (json != null && json.isNotEmpty) { - json.forEach((String key, dynamic v) => map[key] = NumberOnly.fromJson(v)); + if (json?.isNotEmpty == true) { + json.forEach((key, value) => map[key] = NumberOnly.fromJson(value)); } return map; } @@ -62,9 +62,9 @@ class NumberOnly { // maps a json object with a list of NumberOnly-objects as value to a dart map static Map> mapListFromJson(Map json, {bool emptyIsNull, bool growable,}) { final map = >{}; - if (json != null && json.isNotEmpty) { - json.forEach((String key, dynamic v) { - map[key] = NumberOnly.listFromJson(v, emptyIsNull: emptyIsNull, growable: growable); + if (json?.isNotEmpty == true) { + json.forEach((key, value) { + map[key] = NumberOnly.listFromJson(value, emptyIsNull: emptyIsNull, growable: growable,); }); } return map; diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/order.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/order.dart index a7b01582664..4cf8b636f47 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/order.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/order.dart @@ -95,12 +95,12 @@ class Order { static List listFromJson(List json, {bool emptyIsNull, bool growable,}) => json == null || json.isEmpty ? true == emptyIsNull ? null : [] - : json.map((v) => Order.fromJson(v)).toList(growable: true == growable); + : json.map((dynamic value) => Order.fromJson(value)).toList(growable: true == growable); static Map mapFromJson(Map json) { final map = {}; - if (json != null && json.isNotEmpty) { - json.forEach((String key, dynamic v) => map[key] = Order.fromJson(v)); + if (json?.isNotEmpty == true) { + json.forEach((key, value) => map[key] = Order.fromJson(value)); } return map; } @@ -108,9 +108,9 @@ class Order { // maps a json object with a list of Order-objects as value to a dart map static Map> mapListFromJson(Map json, {bool emptyIsNull, bool growable,}) { final map = >{}; - if (json != null && json.isNotEmpty) { - json.forEach((String key, dynamic v) { - map[key] = Order.listFromJson(v, emptyIsNull: emptyIsNull, growable: growable); + if (json?.isNotEmpty == true) { + json.forEach((key, value) { + map[key] = Order.listFromJson(value, emptyIsNull: emptyIsNull, growable: growable,); }); } return map; diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/outer_composite.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/outer_composite.dart index d2942660d23..c7aeb68f1ae 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/outer_composite.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/outer_composite.dart @@ -67,12 +67,12 @@ class OuterComposite { static List listFromJson(List json, {bool emptyIsNull, bool growable,}) => json == null || json.isEmpty ? true == emptyIsNull ? null : [] - : json.map((v) => OuterComposite.fromJson(v)).toList(growable: true == growable); + : json.map((dynamic value) => OuterComposite.fromJson(value)).toList(growable: true == growable); static Map mapFromJson(Map json) { final map = {}; - if (json != null && json.isNotEmpty) { - json.forEach((String key, dynamic v) => map[key] = OuterComposite.fromJson(v)); + if (json?.isNotEmpty == true) { + json.forEach((key, value) => map[key] = OuterComposite.fromJson(value)); } return map; } @@ -80,9 +80,9 @@ class OuterComposite { // maps a json object with a list of OuterComposite-objects as value to a dart map static Map> mapListFromJson(Map json, {bool emptyIsNull, bool growable,}) { final map = >{}; - if (json != null && json.isNotEmpty) { - json.forEach((String key, dynamic v) { - map[key] = OuterComposite.listFromJson(v, emptyIsNull: emptyIsNull, growable: growable); + if (json?.isNotEmpty == true) { + json.forEach((key, value) { + map[key] = OuterComposite.listFromJson(value, emptyIsNull: emptyIsNull, growable: growable,); }); } return map; diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/outer_object_with_enum_property.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/outer_object_with_enum_property.dart index 4d58d276284..accf401ed9a 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/outer_object_with_enum_property.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/outer_object_with_enum_property.dart @@ -45,12 +45,12 @@ class OuterObjectWithEnumProperty { static List listFromJson(List json, {bool emptyIsNull, bool growable,}) => json == null || json.isEmpty ? true == emptyIsNull ? null : [] - : json.map((v) => OuterObjectWithEnumProperty.fromJson(v)).toList(growable: true == growable); + : json.map((dynamic value) => OuterObjectWithEnumProperty.fromJson(value)).toList(growable: true == growable); static Map mapFromJson(Map json) { final map = {}; - if (json != null && json.isNotEmpty) { - json.forEach((String key, dynamic v) => map[key] = OuterObjectWithEnumProperty.fromJson(v)); + if (json?.isNotEmpty == true) { + json.forEach((key, value) => map[key] = OuterObjectWithEnumProperty.fromJson(value)); } return map; } @@ -58,9 +58,9 @@ class OuterObjectWithEnumProperty { // maps a json object with a list of OuterObjectWithEnumProperty-objects as value to a dart map static Map> mapListFromJson(Map json, {bool emptyIsNull, bool growable,}) { final map = >{}; - if (json != null && json.isNotEmpty) { - json.forEach((String key, dynamic v) { - map[key] = OuterObjectWithEnumProperty.listFromJson(v, emptyIsNull: emptyIsNull, growable: growable); + if (json?.isNotEmpty == true) { + json.forEach((key, value) { + map[key] = OuterObjectWithEnumProperty.listFromJson(value, emptyIsNull: emptyIsNull, growable: growable,); }); } return map; diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/pet.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/pet.dart index 47ef86dfcb2..3043edb921f 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/pet.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/pet.dart @@ -91,12 +91,12 @@ class Pet { static List listFromJson(List json, {bool emptyIsNull, bool growable,}) => json == null || json.isEmpty ? true == emptyIsNull ? null : [] - : json.map((v) => Pet.fromJson(v)).toList(growable: true == growable); + : json.map((dynamic value) => Pet.fromJson(value)).toList(growable: true == growable); static Map mapFromJson(Map json) { final map = {}; - if (json != null && json.isNotEmpty) { - json.forEach((String key, dynamic v) => map[key] = Pet.fromJson(v)); + if (json?.isNotEmpty == true) { + json.forEach((key, value) => map[key] = Pet.fromJson(value)); } return map; } @@ -104,9 +104,9 @@ class Pet { // maps a json object with a list of Pet-objects as value to a dart map static Map> mapListFromJson(Map json, {bool emptyIsNull, bool growable,}) { final map = >{}; - if (json != null && json.isNotEmpty) { - json.forEach((String key, dynamic v) { - map[key] = Pet.listFromJson(v, emptyIsNull: emptyIsNull, growable: growable); + if (json?.isNotEmpty == true) { + json.forEach((key, value) { + map[key] = Pet.listFromJson(value, emptyIsNull: emptyIsNull, growable: growable,); }); } return map; diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/read_only_first.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/read_only_first.dart index 3d8382c019e..b0eb02b6942 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/read_only_first.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/read_only_first.dart @@ -56,12 +56,12 @@ class ReadOnlyFirst { static List listFromJson(List json, {bool emptyIsNull, bool growable,}) => json == null || json.isEmpty ? true == emptyIsNull ? null : [] - : json.map((v) => ReadOnlyFirst.fromJson(v)).toList(growable: true == growable); + : json.map((dynamic value) => ReadOnlyFirst.fromJson(value)).toList(growable: true == growable); static Map mapFromJson(Map json) { final map = {}; - if (json != null && json.isNotEmpty) { - json.forEach((String key, dynamic v) => map[key] = ReadOnlyFirst.fromJson(v)); + if (json?.isNotEmpty == true) { + json.forEach((key, value) => map[key] = ReadOnlyFirst.fromJson(value)); } return map; } @@ -69,9 +69,9 @@ class ReadOnlyFirst { // maps a json object with a list of ReadOnlyFirst-objects as value to a dart map static Map> mapListFromJson(Map json, {bool emptyIsNull, bool growable,}) { final map = >{}; - if (json != null && json.isNotEmpty) { - json.forEach((String key, dynamic v) { - map[key] = ReadOnlyFirst.listFromJson(v, emptyIsNull: emptyIsNull, growable: growable); + if (json?.isNotEmpty == true) { + json.forEach((key, value) { + map[key] = ReadOnlyFirst.listFromJson(value, emptyIsNull: emptyIsNull, growable: growable,); }); } return map; diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/special_model_name.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/special_model_name.dart index 846ca82a7db..e43a6b267d2 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/special_model_name.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/special_model_name.dart @@ -47,12 +47,12 @@ class SpecialModelName { static List listFromJson(List json, {bool emptyIsNull, bool growable,}) => json == null || json.isEmpty ? true == emptyIsNull ? null : [] - : json.map((v) => SpecialModelName.fromJson(v)).toList(growable: true == growable); + : json.map((dynamic value) => SpecialModelName.fromJson(value)).toList(growable: true == growable); static Map mapFromJson(Map json) { final map = {}; - if (json != null && json.isNotEmpty) { - json.forEach((String key, dynamic v) => map[key] = SpecialModelName.fromJson(v)); + if (json?.isNotEmpty == true) { + json.forEach((key, value) => map[key] = SpecialModelName.fromJson(value)); } return map; } @@ -60,9 +60,9 @@ class SpecialModelName { // maps a json object with a list of SpecialModelName-objects as value to a dart map static Map> mapListFromJson(Map json, {bool emptyIsNull, bool growable,}) { final map = >{}; - if (json != null && json.isNotEmpty) { - json.forEach((String key, dynamic v) { - map[key] = SpecialModelName.listFromJson(v, emptyIsNull: emptyIsNull, growable: growable); + if (json?.isNotEmpty == true) { + json.forEach((key, value) { + map[key] = SpecialModelName.listFromJson(value, emptyIsNull: emptyIsNull, growable: growable,); }); } return map; diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/tag.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/tag.dart index 63132f08a3a..0cd372910b9 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/tag.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/tag.dart @@ -56,12 +56,12 @@ class Tag { static List listFromJson(List json, {bool emptyIsNull, bool growable,}) => json == null || json.isEmpty ? true == emptyIsNull ? null : [] - : json.map((v) => Tag.fromJson(v)).toList(growable: true == growable); + : json.map((dynamic value) => Tag.fromJson(value)).toList(growable: true == growable); static Map mapFromJson(Map json) { final map = {}; - if (json != null && json.isNotEmpty) { - json.forEach((String key, dynamic v) => map[key] = Tag.fromJson(v)); + if (json?.isNotEmpty == true) { + json.forEach((key, value) => map[key] = Tag.fromJson(value)); } return map; } @@ -69,9 +69,9 @@ class Tag { // maps a json object with a list of Tag-objects as value to a dart map static Map> mapListFromJson(Map json, {bool emptyIsNull, bool growable,}) { final map = >{}; - if (json != null && json.isNotEmpty) { - json.forEach((String key, dynamic v) { - map[key] = Tag.listFromJson(v, emptyIsNull: emptyIsNull, growable: growable); + if (json?.isNotEmpty == true) { + json.forEach((key, value) { + map[key] = Tag.listFromJson(value, emptyIsNull: emptyIsNull, growable: growable,); }); } return map; diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/user.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/user.dart index bb512af491f..0eb3716fceb 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/user.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/model/user.dart @@ -111,12 +111,12 @@ class User { static List listFromJson(List json, {bool emptyIsNull, bool growable,}) => json == null || json.isEmpty ? true == emptyIsNull ? null : [] - : json.map((v) => User.fromJson(v)).toList(growable: true == growable); + : json.map((dynamic value) => User.fromJson(value)).toList(growable: true == growable); static Map mapFromJson(Map json) { final map = {}; - if (json != null && json.isNotEmpty) { - json.forEach((String key, dynamic v) => map[key] = User.fromJson(v)); + if (json?.isNotEmpty == true) { + json.forEach((key, value) => map[key] = User.fromJson(value)); } return map; } @@ -124,9 +124,9 @@ class User { // maps a json object with a list of User-objects as value to a dart map static Map> mapListFromJson(Map json, {bool emptyIsNull, bool growable,}) { final map = >{}; - if (json != null && json.isNotEmpty) { - json.forEach((String key, dynamic v) { - map[key] = User.listFromJson(v, emptyIsNull: emptyIsNull, growable: growable); + if (json?.isNotEmpty == true) { + json.forEach((key, value) { + map[key] = User.listFromJson(value, emptyIsNull: emptyIsNull, growable: growable,); }); } return map; diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/pubspec.yaml b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/pubspec.yaml index 4d55880cd85..163b29ec3ec 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/pubspec.yaml +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/pubspec.yaml @@ -5,8 +5,6 @@ name: 'openapi' version: '1.0.0' description: 'OpenAPI API client' -authors: - - 'Author ' homepage: 'homepage' environment: sdk: '>=2.12.0 <3.0.0' diff --git a/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/.openapi-generator/FILES b/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/.openapi-generator/FILES index a9cd914811b..56e6b6ec96e 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/.openapi-generator/FILES +++ b/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/.openapi-generator/FILES @@ -1,6 +1,7 @@ .gitignore .travis.yml README.md +analysis_options.yaml build.yaml doc/AdditionalPropertiesClass.md doc/Animal.md diff --git a/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/.openapi-generator/VERSION b/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/.openapi-generator/VERSION +++ b/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/README.md b/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/README.md index fe39c2f2126..ec001c87cea 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/README.md +++ b/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/README.md @@ -67,6 +67,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* | [**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 | *FakeApi* | [**testClientModel**](doc//FakeApi.md#testclientmodel) | **PATCH** /fake | To test \"client\" model diff --git a/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/analysis_options.yaml b/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/analysis_options.yaml new file mode 100644 index 00000000000..83d5a10bd7b --- /dev/null +++ b/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/analysis_options.yaml @@ -0,0 +1,3 @@ +analyzer: + strong-mode: + implicit-casts: true diff --git a/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/doc/FakeApi.md b/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/doc/FakeApi.md index 8b7f63bf8bd..6d613003880 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/doc/FakeApi.md +++ b/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/doc/FakeApi.md @@ -16,6 +16,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 | +[**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 | [**testClientModel**](FakeApi.md#testclientmodel) | **PATCH** /fake | To test \"client\" model @@ -323,12 +324,54 @@ 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) +# **testBodyWithBinary** +> testBodyWithBinary(body) + + + +For this test, the body has to be a binary file. + +### Example +```dart +import 'package:openapi/api.dart'; + +final api_instance = FakeApi(); +final body = MultipartFile(); // MultipartFile | image to upload + +try { + api_instance.testBodyWithBinary(body); +} catch (e) { + print('Exception when calling FakeApi->testBodyWithBinary: $e\n'); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | **MultipartFile**| image to upload | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: image/png + - **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(fileSchemaTestClass) -For this test, the body for this request much reference a schema named `File`. +For this test, the body for this request must reference a schema named `File`. ### Example ```dart diff --git a/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/lib/api/another_fake_api.dart b/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/lib/api/another_fake_api.dart index b712431a035..f0115e6907b 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/lib/api/another_fake_api.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/lib/api/another_fake_api.dart @@ -43,17 +43,6 @@ class AnotherFakeApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = []; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, diff --git a/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/lib/api/default_api.dart b/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/lib/api/default_api.dart index 779bdec8b3a..182442cbd42 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/lib/api/default_api.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/lib/api/default_api.dart @@ -29,17 +29,6 @@ class DefaultApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = []; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, diff --git a/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/lib/api/fake_api.dart b/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/lib/api/fake_api.dart index edcd08cfa4a..30111f17ac2 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/lib/api/fake_api.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/lib/api/fake_api.dart @@ -31,17 +31,6 @@ class FakeApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = []; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -111,17 +100,6 @@ class FakeApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = ['http_signature_test']; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -177,17 +155,6 @@ class FakeApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = []; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -245,17 +212,6 @@ class FakeApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = []; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -313,17 +269,6 @@ class FakeApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = []; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -381,17 +326,6 @@ class FakeApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = []; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -452,17 +386,6 @@ class FakeApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = []; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -497,7 +420,59 @@ class FakeApi { return Future.value(null); } - /// For this test, the body for this request much reference a schema named `File`. + /// For this test, the body has to be a binary file. + /// + /// Note: This method returns the HTTP [Response]. + /// + /// Parameters: + /// + /// * [MultipartFile] body (required): + /// image to upload + Future testBodyWithBinaryWithHttpInfo(MultipartFile body) async { + // Verify required params are set. + if (body == null) { + throw ApiException(HttpStatus.badRequest, 'Missing required param: body'); + } + + final path = r'/fake/body-with-binary'; + + Object postBody = body; + + final queryParams = []; + final headerParams = {}; + final formParams = {}; + + final contentTypes = ['image/png']; + final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; + final authNames = []; + + + return await apiClient.invokeAPI( + path, + 'PUT', + queryParams, + postBody, + headerParams, + formParams, + nullableContentType, + authNames, + ); + } + + /// For this test, the body has to be a binary file. + /// + /// Parameters: + /// + /// * [MultipartFile] body (required): + /// image to upload + Future testBodyWithBinary(MultipartFile body) async { + final response = await testBodyWithBinaryWithHttpInfo(body); + if (response.statusCode >= HttpStatus.badRequest) { + throw ApiException(response.statusCode, await _decodeBodyBytes(response)); + } + } + + /// For this test, the body for this request must reference a schema named `File`. /// /// Note: This method returns the HTTP [Response]. /// @@ -522,17 +497,6 @@ class FakeApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = []; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -546,7 +510,7 @@ class FakeApi { ); } - /// For this test, the body for this request much reference a schema named `File`. + /// For this test, the body for this request must reference a schema named `File`. /// /// Parameters: /// @@ -587,17 +551,6 @@ class FakeApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = []; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -651,17 +604,6 @@ class FakeApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = []; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -774,112 +716,44 @@ class FakeApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = ['http_basic_test']; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (integer != null) { - hasFields = true; - mp.fields[r'integer'] = parameterToString(integer); - } - if (int32 != null) { - hasFields = true; - mp.fields[r'int32'] = parameterToString(int32); - } - if (int64 != null) { - hasFields = true; - mp.fields[r'int64'] = parameterToString(int64); - } - if (number != null) { - hasFields = true; - mp.fields[r'number'] = parameterToString(number); - } - if (float != null) { - hasFields = true; - mp.fields[r'float'] = parameterToString(float); - } - if (double_ != null) { - hasFields = true; - mp.fields[r'double'] = parameterToString(double_); - } - if (string != null) { - hasFields = true; - mp.fields[r'string'] = parameterToString(string); - } - if (patternWithoutDelimiter != null) { - hasFields = true; - mp.fields[r'pattern_without_delimiter'] = parameterToString(patternWithoutDelimiter); - } - if (byte != null) { - hasFields = true; - mp.fields[r'byte'] = parameterToString(byte); - } - if (binary != null) { - hasFields = true; - mp.fields[r'binary'] = binary.field; - mp.files.add(binary); - } - if (date != null) { - hasFields = true; - mp.fields[r'date'] = parameterToString(date); - } - if (dateTime != null) { - hasFields = true; - mp.fields[r'dateTime'] = parameterToString(dateTime); - } - if (password != null) { - hasFields = true; - mp.fields[r'password'] = parameterToString(password); - } - if (callback != null) { - hasFields = true; - mp.fields[r'callback'] = parameterToString(callback); - } - if (hasFields) { - postBody = mp; - } - } else { - if (integer != null) { - formParams[r'integer'] = parameterToString(integer); - } - if (int32 != null) { - formParams[r'int32'] = parameterToString(int32); - } - if (int64 != null) { - formParams[r'int64'] = parameterToString(int64); - } - if (number != null) { - formParams[r'number'] = parameterToString(number); - } - if (float != null) { - formParams[r'float'] = parameterToString(float); - } - if (double_ != null) { - formParams[r'double'] = parameterToString(double_); - } - if (string != null) { - formParams[r'string'] = parameterToString(string); - } - if (patternWithoutDelimiter != null) { - formParams[r'pattern_without_delimiter'] = parameterToString(patternWithoutDelimiter); - } - if (byte != null) { - formParams[r'byte'] = parameterToString(byte); - } - if (date != null) { - formParams[r'date'] = parameterToString(date); - } - if (dateTime != null) { - formParams[r'dateTime'] = parameterToString(dateTime); - } - if (password != null) { - formParams[r'password'] = parameterToString(password); - } - if (callback != null) { - formParams[r'callback'] = parameterToString(callback); - } + if (integer != null) { + formParams[r'integer'] = parameterToString(integer); + } + if (int32 != null) { + formParams[r'int32'] = parameterToString(int32); + } + if (int64 != null) { + formParams[r'int64'] = parameterToString(int64); + } + if (number != null) { + formParams[r'number'] = parameterToString(number); + } + if (float != null) { + formParams[r'float'] = parameterToString(float); + } + if (double_ != null) { + formParams[r'double'] = parameterToString(double_); + } + if (string != null) { + formParams[r'string'] = parameterToString(string); + } + if (patternWithoutDelimiter != null) { + formParams[r'pattern_without_delimiter'] = parameterToString(patternWithoutDelimiter); + } + if (byte != null) { + formParams[r'byte'] = parameterToString(byte); + } + if (date != null) { + formParams[r'date'] = parameterToString(date); + } + if (dateTime != null) { + formParams[r'dateTime'] = parameterToString(dateTime); + } + if (password != null) { + formParams[r'password'] = parameterToString(password); + } + if (callback != null) { + formParams[r'callback'] = parameterToString(callback); } return await apiClient.invokeAPI( @@ -1014,30 +888,11 @@ class FakeApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = []; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (enumFormStringArray != null) { - hasFields = true; - mp.fields[r'enum_form_string_array'] = parameterToString(enumFormStringArray); - } - if (enumFormString != null) { - hasFields = true; - mp.fields[r'enum_form_string'] = parameterToString(enumFormString); - } - if (hasFields) { - postBody = mp; - } - } else { - if (enumFormStringArray != null) { - formParams[r'enum_form_string_array'] = parameterToString(enumFormStringArray); - } - if (enumFormString != null) { - formParams[r'enum_form_string'] = parameterToString(enumFormString); - } + if (enumFormStringArray != null) { + formParams[r'enum_form_string_array'] = parameterToString(enumFormStringArray); + } + if (enumFormString != null) { + formParams[r'enum_form_string'] = parameterToString(enumFormString); } return await apiClient.invokeAPI( @@ -1151,17 +1006,6 @@ class FakeApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = ['bearer_test']; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -1231,17 +1075,6 @@ class FakeApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = []; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -1300,30 +1133,11 @@ class FakeApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = []; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (param != null) { - hasFields = true; - mp.fields[r'param'] = parameterToString(param); - } - if (param2 != null) { - hasFields = true; - mp.fields[r'param2'] = parameterToString(param2); - } - if (hasFields) { - postBody = mp; - } - } else { - if (param != null) { - formParams[r'param'] = parameterToString(param); - } - if (param2 != null) { - formParams[r'param2'] = parameterToString(param2); - } + if (param != null) { + formParams[r'param'] = parameterToString(param); + } + if (param2 != null) { + formParams[r'param2'] = parameterToString(param2); } return await apiClient.invokeAPI( @@ -1395,7 +1209,7 @@ class FakeApi { final headerParams = {}; final formParams = {}; - queryParams.addAll(_convertParametersForCollectionFormat('multi', 'pipe', pipe)); + queryParams.addAll(_convertParametersForCollectionFormat('pipes', 'pipe', pipe)); queryParams.addAll(_convertParametersForCollectionFormat('csv', 'ioutil', ioutil)); queryParams.addAll(_convertParametersForCollectionFormat('ssv', 'http', http)); queryParams.addAll(_convertParametersForCollectionFormat('csv', 'url', url)); @@ -1405,17 +1219,6 @@ class FakeApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = []; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, diff --git a/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/lib/api/fake_classname_tags123_api.dart b/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/lib/api/fake_classname_tags123_api.dart index 49f4ce7cde2..c9fc34d194c 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/lib/api/fake_classname_tags123_api.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/lib/api/fake_classname_tags123_api.dart @@ -43,17 +43,6 @@ class FakeClassnameTags123Api { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = ['api_key_query']; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, diff --git a/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/lib/api/pet_api.dart b/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/lib/api/pet_api.dart index cd2a65ab939..dec9efa15f7 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/lib/api/pet_api.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/lib/api/pet_api.dart @@ -41,17 +41,6 @@ class PetApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = ['petstore_auth']; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -111,17 +100,6 @@ class PetApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = ['petstore_auth']; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -180,17 +158,6 @@ class PetApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = ['petstore_auth']; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -259,17 +226,6 @@ class PetApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = ['petstore_auth']; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -337,17 +293,6 @@ class PetApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = ['api_key']; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -410,17 +355,6 @@ class PetApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = ['petstore_auth']; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -480,30 +414,11 @@ class PetApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = ['petstore_auth']; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (name != null) { - hasFields = true; - mp.fields[r'name'] = parameterToString(name); - } - if (status != null) { - hasFields = true; - mp.fields[r'status'] = parameterToString(status); - } - if (hasFields) { - postBody = mp; - } - } else { - if (name != null) { - formParams[r'name'] = parameterToString(name); - } - if (status != null) { - formParams[r'status'] = parameterToString(status); - } + if (name != null) { + formParams[r'name'] = parameterToString(name); + } + if (status != null) { + formParams[r'status'] = parameterToString(status); } return await apiClient.invokeAPI( @@ -570,28 +485,19 @@ class PetApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = ['petstore_auth']; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (additionalMetadata != null) { - hasFields = true; - mp.fields[r'additionalMetadata'] = parameterToString(additionalMetadata); - } - if (file != null) { - hasFields = true; - mp.fields[r'file'] = file.field; - mp.files.add(file); - } - if (hasFields) { - postBody = mp; - } - } else { - if (additionalMetadata != null) { - formParams[r'additionalMetadata'] = parameterToString(additionalMetadata); - } + bool hasFields = false; + final mp = MultipartRequest('POST', Uri.parse(path)); + if (additionalMetadata != null) { + hasFields = true; + mp.fields[r'additionalMetadata'] = parameterToString(additionalMetadata); + } + if (file != null) { + hasFields = true; + mp.fields[r'file'] = file.field; + mp.files.add(file); + } + if (hasFields) { + postBody = mp; } return await apiClient.invokeAPI( @@ -669,28 +575,19 @@ class PetApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = ['petstore_auth']; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (additionalMetadata != null) { - hasFields = true; - mp.fields[r'additionalMetadata'] = parameterToString(additionalMetadata); - } - if (requiredFile != null) { - hasFields = true; - mp.fields[r'requiredFile'] = requiredFile.field; - mp.files.add(requiredFile); - } - if (hasFields) { - postBody = mp; - } - } else { - if (additionalMetadata != null) { - formParams[r'additionalMetadata'] = parameterToString(additionalMetadata); - } + bool hasFields = false; + final mp = MultipartRequest('POST', Uri.parse(path)); + if (additionalMetadata != null) { + hasFields = true; + mp.fields[r'additionalMetadata'] = parameterToString(additionalMetadata); + } + if (requiredFile != null) { + hasFields = true; + mp.fields[r'requiredFile'] = requiredFile.field; + mp.files.add(requiredFile); + } + if (hasFields) { + postBody = mp; } return await apiClient.invokeAPI( diff --git a/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/lib/api/store_api.dart b/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/lib/api/store_api.dart index 9e262c18b98..f7a67632d33 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/lib/api/store_api.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/lib/api/store_api.dart @@ -44,17 +44,6 @@ class StoreApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = []; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -101,17 +90,6 @@ class StoreApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = ['api_key']; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -172,17 +150,6 @@ class StoreApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = []; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -245,17 +212,6 @@ class StoreApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = []; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, diff --git a/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/lib/api/user_api.dart b/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/lib/api/user_api.dart index 3291afc2670..13e62586ac9 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/lib/api/user_api.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/lib/api/user_api.dart @@ -43,17 +43,6 @@ class UserApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = []; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -108,17 +97,6 @@ class UserApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = []; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -171,17 +149,6 @@ class UserApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = []; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -237,17 +204,6 @@ class UserApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = []; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -303,17 +259,6 @@ class UserApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = []; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -383,17 +328,6 @@ class UserApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = []; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -447,17 +381,6 @@ class UserApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = []; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, @@ -514,17 +437,6 @@ class UserApi { final nullableContentType = contentTypes.isNotEmpty ? contentTypes[0] : null; final authNames = []; - if ( - nullableContentType != null && - nullableContentType.toLowerCase().startsWith('multipart/form-data') - ) { - bool hasFields = false; - final mp = MultipartRequest(null, null); - if (hasFields) { - postBody = mp; - } - } else { - } return await apiClient.invokeAPI( path, diff --git a/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/lib/api_client.dart b/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/lib/api_client.dart index 65c9ec57844..02f98fe17a4 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/lib/api_client.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/lib/api_client.dart @@ -61,7 +61,7 @@ class ApiClient { Future invokeAPI( String path, String method, - Iterable queryParams, + List queryParams, Object body, Map headerParams, Map formParams, @@ -156,13 +156,13 @@ class ApiClient { List queryParams, Map headerParams, ) { - authNames.forEach((authName) { + for(final authName in authNames) { final auth = _authentications[authName]; if (auth == null) { throw ArgumentError('Authentication undefined: $authName'); } auth.applyToParams(queryParams, headerParams); - }); + } } } diff --git a/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/lib/api_exception.dart b/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/lib/api_exception.dart index 1537c9769b2..86e2054bffe 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/lib/api_exception.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/lib/api_exception.dart @@ -19,6 +19,7 @@ class ApiException implements Exception { Exception innerException; StackTrace stackTrace; + @override String toString() { if (message == null) { return 'ApiException'; diff --git a/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/lib/api_helper.dart b/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/lib/api_helper.dart index 51db433eb30..e88f8cc2987 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/lib/api_helper.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/lib/api_helper.dart @@ -28,7 +28,7 @@ Iterable _convertParametersForCollectionFormat( final params = []; // preconditions - if (name != null && !name.isEmpty && value != null) { + if (name != null && name.isNotEmpty && value != null) { if (value is List) { // get the collection format, default: csv collectionFormat = (collectionFormat == null || collectionFormat.isEmpty) diff --git a/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/pubspec.yaml b/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/pubspec.yaml index 73931cb6b83..66b0d5a7acd 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/pubspec.yaml +++ b/samples/openapi3/client/petstore/dart2/petstore_json_serializable_client_lib_fake/pubspec.yaml @@ -5,8 +5,6 @@ name: 'openapi' version: '1.0.0' description: 'OpenAPI API client' -authors: - - 'Author ' homepage: 'homepage' environment: sdk: '>=2.12.0 <3.0.0' 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 5f68295fc19..e8415097f3a 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,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/openapi3/client/petstore/go/go-petstore/client.go b/samples/openapi3/client/petstore/go/go-petstore/client.go index 398927f7d7d..4902cfae215 100644 --- a/samples/openapi3/client/petstore/go/go-petstore/client.go +++ b/samples/openapi3/client/petstore/go/go-petstore/client.go @@ -18,6 +18,7 @@ import ( "errors" "fmt" "io" + "io/ioutil" "log" "mime/multipart" "net/http" @@ -387,6 +388,15 @@ func (c *APIClient) decode(v interface{}, b []byte, contentType string) (err err *s = string(b) return nil } + if f, ok := v.(**os.File); ok { + *f, err = ioutil.TempFile("", "HttpClientFile") + if err != nil { + return + } + _, err = (*f).Write(b) + _, err = (*f).Seek(0, io.SeekStart) + return + } if xmlCheck.MatchString(contentType) { if err = xml.Unmarshal(b, v); err != nil { return err 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 5f68295fc19..e8415097f3a 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,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x 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 5f68295fc19..e8415097f3a 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,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/openapi3/client/petstore/java/native/.openapi-generator/VERSION b/samples/openapi3/client/petstore/java/native/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/openapi3/client/petstore/java/native/.openapi-generator/VERSION +++ b/samples/openapi3/client/petstore/java/native/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/openapi3/client/petstore/java/native/build.gradle b/samples/openapi3/client/petstore/java/native/build.gradle index ee4c7276cf8..2979e384fef 100644 --- a/samples/openapi3/client/petstore/java/native/build.gradle +++ b/samples/openapi3/client/petstore/java/native/build.gradle @@ -22,6 +22,17 @@ apply plugin: 'maven' sourceCompatibility = JavaVersion.VERSION_11 targetCompatibility = JavaVersion.VERSION_11 +// Some text from the schema is copy pasted into the source files as UTF-8 +// but the default still seems to be to use platform encoding +tasks.withType(JavaCompile) { + configure(options) { + options.encoding = 'UTF-8' + } +} +javadoc { + options.encoding = 'UTF-8' +} + install { repositories.mavenInstaller { pom.artifactId = 'petstore-openapi3-native' @@ -53,7 +64,6 @@ ext { swagger_annotations_version = "1.5.22" jackson_version = "2.10.4" junit_version = "4.13.1" - ws_rs_version = "2.1.1" } dependencies { @@ -65,6 +75,5 @@ dependencies { implementation "com.fasterxml.jackson.datatype:jackson-datatype-jsr310:$jackson_version" implementation "org.openapitools:jackson-databind-nullable:0.2.1" implementation 'javax.annotation:javax.annotation-api:1.3.2' - implementation "javax.ws.rs:javax.ws.rs-api:$ws_rs_version" testImplementation "junit:junit:$junit_version" } diff --git a/samples/openapi3/client/petstore/java/native/pom.xml b/samples/openapi3/client/petstore/java/native/pom.xml index ed19e62e9ef..58e5bf25f54 100644 --- a/samples/openapi3/client/petstore/java/native/pom.xml +++ b/samples/openapi3/client/petstore/java/native/pom.xml @@ -200,13 +200,6 @@ provided - - - javax.ws.rs - javax.ws.rs-api - ${javax-ws-rs-api-version} - - junit @@ -224,7 +217,6 @@ 2.10.4 0.2.1 1.3.2 - 2.1.1 4.13.1 diff --git a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/JSON.java b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/JSON.java index 519cd35cc6a..04d3f7c1799 100644 --- a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/JSON.java +++ b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/JSON.java @@ -11,11 +11,9 @@ import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; -import javax.ws.rs.core.GenericType; -import javax.ws.rs.ext.ContextResolver; @javax.annotation.processing.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") -public class JSON implements ContextResolver { +public class JSON { private ObjectMapper mapper; public JSON() { @@ -41,11 +39,6 @@ public class JSON implements ContextResolver { mapper.setDateFormat(dateFormat); } - @Override - public ObjectMapper getContext(Class type) { - return mapper; - } - /** * Get the object mapper * @@ -178,10 +171,10 @@ public class JSON implements ContextResolver { visitedClasses.add(modelClass); // Traverse the oneOf/anyOf composed schemas. - Map descendants = modelDescendants.get(modelClass); + Map> descendants = modelDescendants.get(modelClass); if (descendants != null) { - for (GenericType childType : descendants.values()) { - if (isInstanceOf(childType.getRawType(), inst, visitedClasses)) { + for (Class childType : descendants.values()) { + if (isInstanceOf(childType, inst, visitedClasses)) { return true; } } @@ -192,12 +185,12 @@ public class JSON implements ContextResolver { /** * A map of discriminators for all model classes. */ - private static Map, ClassDiscriminatorMapping> modelDiscriminators = new HashMap, ClassDiscriminatorMapping>(); + private static Map, ClassDiscriminatorMapping> modelDiscriminators = new HashMap<>(); /** * A map of oneOf/anyOf descendants for each model class. */ - private static Map, Map> modelDescendants = new HashMap, Map>(); + private static Map, Map>> modelDescendants = new HashMap<>(); /** * Register a model class discriminator. @@ -217,7 +210,7 @@ public class JSON implements ContextResolver { * @param modelClass the model class * @param descendants a map of oneOf/anyOf descendants. */ - public static void registerDescendants(Class modelClass, Map descendants) { + public static void registerDescendants(Class modelClass, Map> descendants) { modelDescendants.put(modelClass, descendants); } diff --git a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/api/AnotherFakeApi.java b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/api/AnotherFakeApi.java index 1d87022e718..9e3aae36505 100644 --- a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/api/AnotherFakeApi.java +++ b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/api/AnotherFakeApi.java @@ -58,12 +58,17 @@ public class AnotherFakeApi { memberVarResponseInterceptor = apiClient.getResponseInterceptor(); } - protected ApiException createApiException(HttpResponse response, String msgPrefix) throws IOException { + protected ApiException getApiException(String operationId, HttpResponse response) throws IOException { String body = response.body() == null ? null : new String(response.body().readAllBytes()); - if (body != null) { - msgPrefix += ": " + body; + String message = formatExceptionMessage(operationId, response.statusCode(), body); + return new ApiException(response.statusCode(), message, response.headers(), body); + } + + private String formatExceptionMessage(String operationId, int statusCode, String body) { + if (body == null || body.isEmpty()) { + body = "[no body]"; } - return new ApiException(response.statusCode(), msgPrefix, response.headers(), body); + return operationId + " call failed with: " + statusCode + " - " + body; } /** @@ -95,7 +100,7 @@ public class AnotherFakeApi { memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw createApiException(localVarResponse, "call123testSpecialTags call received non-success response"); + throw getApiException("call123testSpecialTags", localVarResponse); } return new ApiResponse( localVarResponse.statusCode(), diff --git a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/api/DefaultApi.java b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/api/DefaultApi.java index fc06f1fc039..5dc086e5edb 100644 --- a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/api/DefaultApi.java +++ b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/api/DefaultApi.java @@ -58,12 +58,17 @@ public class DefaultApi { memberVarResponseInterceptor = apiClient.getResponseInterceptor(); } - protected ApiException createApiException(HttpResponse response, String msgPrefix) throws IOException { + protected ApiException getApiException(String operationId, HttpResponse response) throws IOException { String body = response.body() == null ? null : new String(response.body().readAllBytes()); - if (body != null) { - msgPrefix += ": " + body; + String message = formatExceptionMessage(operationId, response.statusCode(), body); + return new ApiException(response.statusCode(), message, response.headers(), body); + } + + private String formatExceptionMessage(String operationId, int statusCode, String body) { + if (body == null || body.isEmpty()) { + body = "[no body]"; } - return new ApiException(response.statusCode(), msgPrefix, response.headers(), body); + return operationId + " call failed with: " + statusCode + " - " + body; } /** @@ -93,7 +98,7 @@ public class DefaultApi { memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw createApiException(localVarResponse, "fooGet call received non-success response"); + throw getApiException("fooGet", localVarResponse); } return new ApiResponse( localVarResponse.statusCode(), diff --git a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/api/FakeApi.java b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/api/FakeApi.java index b5b0a141d33..996001b7aac 100644 --- a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/api/FakeApi.java +++ b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/api/FakeApi.java @@ -67,12 +67,17 @@ public class FakeApi { memberVarResponseInterceptor = apiClient.getResponseInterceptor(); } - protected ApiException createApiException(HttpResponse response, String msgPrefix) throws IOException { + protected ApiException getApiException(String operationId, HttpResponse response) throws IOException { String body = response.body() == null ? null : new String(response.body().readAllBytes()); - if (body != null) { - msgPrefix += ": " + body; + String message = formatExceptionMessage(operationId, response.statusCode(), body); + return new ApiException(response.statusCode(), message, response.headers(), body); + } + + private String formatExceptionMessage(String operationId, int statusCode, String body) { + if (body == null || body.isEmpty()) { + body = "[no body]"; } - return new ApiException(response.statusCode(), msgPrefix, response.headers(), body); + return operationId + " call failed with: " + statusCode + " - " + body; } /** @@ -102,7 +107,7 @@ public class FakeApi { memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw createApiException(localVarResponse, "fakeHealthGet call received non-success response"); + throw getApiException("fakeHealthGet", localVarResponse); } return new ApiResponse( localVarResponse.statusCode(), @@ -166,7 +171,7 @@ public class FakeApi { memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw createApiException(localVarResponse, "fakeOuterBooleanSerialize call received non-success response"); + throw getApiException("fakeOuterBooleanSerialize", localVarResponse); } return new ApiResponse( localVarResponse.statusCode(), @@ -236,7 +241,7 @@ public class FakeApi { memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw createApiException(localVarResponse, "fakeOuterCompositeSerialize call received non-success response"); + throw getApiException("fakeOuterCompositeSerialize", localVarResponse); } return new ApiResponse( localVarResponse.statusCode(), @@ -306,7 +311,7 @@ public class FakeApi { memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw createApiException(localVarResponse, "fakeOuterNumberSerialize call received non-success response"); + throw getApiException("fakeOuterNumberSerialize", localVarResponse); } return new ApiResponse( localVarResponse.statusCode(), @@ -376,7 +381,7 @@ public class FakeApi { memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw createApiException(localVarResponse, "fakeOuterStringSerialize call received non-success response"); + throw getApiException("fakeOuterStringSerialize", localVarResponse); } return new ApiResponse( localVarResponse.statusCode(), @@ -444,7 +449,7 @@ public class FakeApi { memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw createApiException(localVarResponse, "getArrayOfEnums call received non-success response"); + throw getApiException("getArrayOfEnums", localVarResponse); } return new ApiResponse>( localVarResponse.statusCode(), @@ -506,7 +511,7 @@ public class FakeApi { memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw createApiException(localVarResponse, "testBodyWithFileSchema call received non-success response"); + throw getApiException("testBodyWithFileSchema", localVarResponse); } return new ApiResponse( localVarResponse.statusCode(), @@ -580,7 +585,7 @@ public class FakeApi { memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw createApiException(localVarResponse, "testBodyWithQueryParams call received non-success response"); + throw getApiException("testBodyWithQueryParams", localVarResponse); } return new ApiResponse( localVarResponse.statusCode(), @@ -667,7 +672,7 @@ public class FakeApi { memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw createApiException(localVarResponse, "testClientModel call received non-success response"); + throw getApiException("testClientModel", localVarResponse); } return new ApiResponse( localVarResponse.statusCode(), @@ -765,7 +770,7 @@ public class FakeApi { memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw createApiException(localVarResponse, "testEndpointParameters call received non-success response"); + throw getApiException("testEndpointParameters", localVarResponse); } return new ApiResponse( localVarResponse.statusCode(), @@ -857,7 +862,7 @@ public class FakeApi { memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw createApiException(localVarResponse, "testEnumParameters call received non-success response"); + throw getApiException("testEnumParameters", localVarResponse); } return new ApiResponse( localVarResponse.statusCode(), @@ -980,7 +985,7 @@ public class FakeApi { memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw createApiException(localVarResponse, "testGroupParameters call received non-success response"); + throw getApiException("testGroupParameters", localVarResponse); } return new ApiResponse( localVarResponse.statusCode(), @@ -1149,7 +1154,7 @@ public class FakeApi { memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw createApiException(localVarResponse, "testInlineAdditionalProperties call received non-success response"); + throw getApiException("testInlineAdditionalProperties", localVarResponse); } return new ApiResponse( localVarResponse.statusCode(), @@ -1223,7 +1228,7 @@ public class FakeApi { memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw createApiException(localVarResponse, "testJsonFormData call received non-success response"); + throw getApiException("testJsonFormData", localVarResponse); } return new ApiResponse( localVarResponse.statusCode(), @@ -1301,7 +1306,7 @@ public class FakeApi { memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw createApiException(localVarResponse, "testQueryParameterCollectionFormat call received non-success response"); + throw getApiException("testQueryParameterCollectionFormat", localVarResponse); } return new ApiResponse( localVarResponse.statusCode(), diff --git a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/api/FakeClassnameTags123Api.java b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/api/FakeClassnameTags123Api.java index caeaf872f78..098b07e149e 100644 --- a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/api/FakeClassnameTags123Api.java +++ b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/api/FakeClassnameTags123Api.java @@ -58,12 +58,17 @@ public class FakeClassnameTags123Api { memberVarResponseInterceptor = apiClient.getResponseInterceptor(); } - protected ApiException createApiException(HttpResponse response, String msgPrefix) throws IOException { + protected ApiException getApiException(String operationId, HttpResponse response) throws IOException { String body = response.body() == null ? null : new String(response.body().readAllBytes()); - if (body != null) { - msgPrefix += ": " + body; + String message = formatExceptionMessage(operationId, response.statusCode(), body); + return new ApiException(response.statusCode(), message, response.headers(), body); + } + + private String formatExceptionMessage(String operationId, int statusCode, String body) { + if (body == null || body.isEmpty()) { + body = "[no body]"; } - return new ApiException(response.statusCode(), msgPrefix, response.headers(), body); + return operationId + " call failed with: " + statusCode + " - " + body; } /** @@ -95,7 +100,7 @@ public class FakeClassnameTags123Api { memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw createApiException(localVarResponse, "testClassname call received non-success response"); + throw getApiException("testClassname", localVarResponse); } return new ApiResponse( localVarResponse.statusCode(), diff --git a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/api/PetApi.java b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/api/PetApi.java index 530d75960d9..4f2bfe172fe 100644 --- a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/api/PetApi.java +++ b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/api/PetApi.java @@ -60,12 +60,17 @@ public class PetApi { memberVarResponseInterceptor = apiClient.getResponseInterceptor(); } - protected ApiException createApiException(HttpResponse response, String msgPrefix) throws IOException { + protected ApiException getApiException(String operationId, HttpResponse response) throws IOException { String body = response.body() == null ? null : new String(response.body().readAllBytes()); - if (body != null) { - msgPrefix += ": " + body; + String message = formatExceptionMessage(operationId, response.statusCode(), body); + return new ApiException(response.statusCode(), message, response.headers(), body); + } + + private String formatExceptionMessage(String operationId, int statusCode, String body) { + if (body == null || body.isEmpty()) { + body = "[no body]"; } - return new ApiException(response.statusCode(), msgPrefix, response.headers(), body); + return operationId + " call failed with: " + statusCode + " - " + body; } /** @@ -95,7 +100,7 @@ public class PetApi { memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw createApiException(localVarResponse, "addPet call received non-success response"); + throw getApiException("addPet", localVarResponse); } return new ApiResponse( localVarResponse.statusCode(), @@ -169,7 +174,7 @@ public class PetApi { memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw createApiException(localVarResponse, "deletePet call received non-success response"); + throw getApiException("deletePet", localVarResponse); } return new ApiResponse( localVarResponse.statusCode(), @@ -241,7 +246,7 @@ public class PetApi { memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw createApiException(localVarResponse, "findPetsByStatus call received non-success response"); + throw getApiException("findPetsByStatus", localVarResponse); } return new ApiResponse>( localVarResponse.statusCode(), @@ -322,7 +327,7 @@ public class PetApi { memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw createApiException(localVarResponse, "findPetsByTags call received non-success response"); + throw getApiException("findPetsByTags", localVarResponse); } return new ApiResponse>( localVarResponse.statusCode(), @@ -399,7 +404,7 @@ public class PetApi { memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw createApiException(localVarResponse, "getPetById call received non-success response"); + throw getApiException("getPetById", localVarResponse); } return new ApiResponse( localVarResponse.statusCode(), @@ -466,7 +471,7 @@ public class PetApi { memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw createApiException(localVarResponse, "updatePet call received non-success response"); + throw getApiException("updatePet", localVarResponse); } return new ApiResponse( localVarResponse.statusCode(), @@ -542,7 +547,7 @@ public class PetApi { memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw createApiException(localVarResponse, "updatePetWithForm call received non-success response"); + throw getApiException("updatePetWithForm", localVarResponse); } return new ApiResponse( localVarResponse.statusCode(), @@ -615,7 +620,7 @@ public class PetApi { memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw createApiException(localVarResponse, "uploadFile call received non-success response"); + throw getApiException("uploadFile", localVarResponse); } return new ApiResponse( localVarResponse.statusCode(), @@ -688,7 +693,7 @@ public class PetApi { memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw createApiException(localVarResponse, "uploadFileWithRequiredFile call received non-success response"); + throw getApiException("uploadFileWithRequiredFile", localVarResponse); } return new ApiResponse( localVarResponse.statusCode(), diff --git a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/api/StoreApi.java b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/api/StoreApi.java index c06efabb4a8..0bd1cd35ff4 100644 --- a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/api/StoreApi.java +++ b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/api/StoreApi.java @@ -58,12 +58,17 @@ public class StoreApi { memberVarResponseInterceptor = apiClient.getResponseInterceptor(); } - protected ApiException createApiException(HttpResponse response, String msgPrefix) throws IOException { + protected ApiException getApiException(String operationId, HttpResponse response) throws IOException { String body = response.body() == null ? null : new String(response.body().readAllBytes()); - if (body != null) { - msgPrefix += ": " + body; + String message = formatExceptionMessage(operationId, response.statusCode(), body); + return new ApiException(response.statusCode(), message, response.headers(), body); + } + + private String formatExceptionMessage(String operationId, int statusCode, String body) { + if (body == null || body.isEmpty()) { + body = "[no body]"; } - return new ApiException(response.statusCode(), msgPrefix, response.headers(), body); + return operationId + " call failed with: " + statusCode + " - " + body; } /** @@ -93,7 +98,7 @@ public class StoreApi { memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw createApiException(localVarResponse, "deleteOrder call received non-success response"); + throw getApiException("deleteOrder", localVarResponse); } return new ApiResponse( localVarResponse.statusCode(), @@ -160,7 +165,7 @@ public class StoreApi { memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw createApiException(localVarResponse, "getInventory call received non-success response"); + throw getApiException("getInventory", localVarResponse); } return new ApiResponse>( localVarResponse.statusCode(), @@ -224,7 +229,7 @@ public class StoreApi { memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw createApiException(localVarResponse, "getOrderById call received non-success response"); + throw getApiException("getOrderById", localVarResponse); } return new ApiResponse( localVarResponse.statusCode(), @@ -293,7 +298,7 @@ public class StoreApi { memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw createApiException(localVarResponse, "placeOrder call received non-success response"); + throw getApiException("placeOrder", localVarResponse); } return new ApiResponse( localVarResponse.statusCode(), diff --git a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/api/UserApi.java b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/api/UserApi.java index 3c1a68c9881..008303b316d 100644 --- a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/api/UserApi.java +++ b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/api/UserApi.java @@ -58,12 +58,17 @@ public class UserApi { memberVarResponseInterceptor = apiClient.getResponseInterceptor(); } - protected ApiException createApiException(HttpResponse response, String msgPrefix) throws IOException { + protected ApiException getApiException(String operationId, HttpResponse response) throws IOException { String body = response.body() == null ? null : new String(response.body().readAllBytes()); - if (body != null) { - msgPrefix += ": " + body; + String message = formatExceptionMessage(operationId, response.statusCode(), body); + return new ApiException(response.statusCode(), message, response.headers(), body); + } + + private String formatExceptionMessage(String operationId, int statusCode, String body) { + if (body == null || body.isEmpty()) { + body = "[no body]"; } - return new ApiException(response.statusCode(), msgPrefix, response.headers(), body); + return operationId + " call failed with: " + statusCode + " - " + body; } /** @@ -93,7 +98,7 @@ public class UserApi { memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw createApiException(localVarResponse, "createUser call received non-success response"); + throw getApiException("createUser", localVarResponse); } return new ApiResponse( localVarResponse.statusCode(), @@ -165,7 +170,7 @@ public class UserApi { memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw createApiException(localVarResponse, "createUsersWithArrayInput call received non-success response"); + throw getApiException("createUsersWithArrayInput", localVarResponse); } return new ApiResponse( localVarResponse.statusCode(), @@ -237,7 +242,7 @@ public class UserApi { memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw createApiException(localVarResponse, "createUsersWithListInput call received non-success response"); + throw getApiException("createUsersWithListInput", localVarResponse); } return new ApiResponse( localVarResponse.statusCode(), @@ -309,7 +314,7 @@ public class UserApi { memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw createApiException(localVarResponse, "deleteUser call received non-success response"); + throw getApiException("deleteUser", localVarResponse); } return new ApiResponse( localVarResponse.statusCode(), @@ -378,7 +383,7 @@ public class UserApi { memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw createApiException(localVarResponse, "getUserByName call received non-success response"); + throw getApiException("getUserByName", localVarResponse); } return new ApiResponse( localVarResponse.statusCode(), @@ -449,7 +454,7 @@ public class UserApi { memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw createApiException(localVarResponse, "loginUser call received non-success response"); + throw getApiException("loginUser", localVarResponse); } return new ApiResponse( localVarResponse.statusCode(), @@ -527,7 +532,7 @@ public class UserApi { memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw createApiException(localVarResponse, "logoutUser call received non-success response"); + throw getApiException("logoutUser", localVarResponse); } return new ApiResponse( localVarResponse.statusCode(), @@ -591,7 +596,7 @@ public class UserApi { memberVarResponseInterceptor.accept(localVarResponse); } if (localVarResponse.statusCode()/ 100 != 2) { - throw createApiException(localVarResponse, "updateUser call received non-success response"); + throw getApiException("updateUser", localVarResponse); } return new ApiResponse( localVarResponse.statusCode(), diff --git a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/AbstractOpenApiSchema.java b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/AbstractOpenApiSchema.java index 1736eb73c5a..882bf6fc3af 100644 --- a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/AbstractOpenApiSchema.java +++ b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/AbstractOpenApiSchema.java @@ -17,7 +17,6 @@ import org.openapitools.client.ApiException; import java.util.Objects; import java.lang.reflect.Type; import java.util.Map; -import javax.ws.rs.core.GenericType; import com.fasterxml.jackson.annotation.JsonValue; @@ -46,7 +45,7 @@ public abstract class AbstractOpenApiSchema { * * @return an instance of the actual schema/object */ - public abstract Map getSchemas(); + public abstract Map> getSchemas(); /** * Get the actual instance diff --git a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/Fruit.java b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/Fruit.java index cf6d211a85b..548e7ab3c36 100644 --- a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/Fruit.java +++ b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/Fruit.java @@ -31,8 +31,6 @@ import com.fasterxml.jackson.annotation.JsonPropertyOrder; import com.fasterxml.jackson.core.type.TypeReference; -import javax.ws.rs.core.GenericType; -import javax.ws.rs.core.Response; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; @@ -44,7 +42,6 @@ import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.JsonToken; -import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.JsonNode; @@ -163,7 +160,7 @@ public class Fruit extends AbstractOpenApiSchema { } // store a list of schema names defined in oneOf - public static final Map schemas = new HashMap(); + public static final Map> schemas = new HashMap<>(); public Fruit() { super("oneOf", Boolean.FALSE); @@ -180,15 +177,13 @@ public class Fruit extends AbstractOpenApiSchema { } static { - schemas.put("Apple", new GenericType() { - }); - schemas.put("Banana", new GenericType() { - }); + schemas.put("Apple", Apple.class); + schemas.put("Banana", Banana.class); JSON.registerDescendants(Fruit.class, Collections.unmodifiableMap(schemas)); } @Override - public Map getSchemas() { + public Map> getSchemas() { return Fruit.schemas; } diff --git a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/FruitReq.java b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/FruitReq.java index 714fdfacad2..c73123d08dd 100644 --- a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/FruitReq.java +++ b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/FruitReq.java @@ -31,8 +31,6 @@ import com.fasterxml.jackson.annotation.JsonPropertyOrder; import com.fasterxml.jackson.core.type.TypeReference; -import javax.ws.rs.core.GenericType; -import javax.ws.rs.core.Response; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; @@ -44,7 +42,6 @@ import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.JsonToken; -import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.JsonNode; @@ -165,7 +162,7 @@ public class FruitReq extends AbstractOpenApiSchema { } // store a list of schema names defined in oneOf - public static final Map schemas = new HashMap(); + public static final Map> schemas = new HashMap<>(); public FruitReq() { super("oneOf", Boolean.TRUE); @@ -182,15 +179,13 @@ public class FruitReq extends AbstractOpenApiSchema { } static { - schemas.put("AppleReq", new GenericType() { - }); - schemas.put("BananaReq", new GenericType() { - }); + schemas.put("AppleReq", AppleReq.class); + schemas.put("BananaReq", BananaReq.class); JSON.registerDescendants(FruitReq.class, Collections.unmodifiableMap(schemas)); } @Override - public Map getSchemas() { + public Map> getSchemas() { return FruitReq.schemas; } diff --git a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/GmFruit.java b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/GmFruit.java index cf55e466f13..c6c672512da 100644 --- a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/GmFruit.java +++ b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/GmFruit.java @@ -30,8 +30,6 @@ import org.openapitools.client.model.Banana; import com.fasterxml.jackson.annotation.JsonPropertyOrder; -import javax.ws.rs.core.GenericType; -import javax.ws.rs.core.Response; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; @@ -42,7 +40,6 @@ import java.util.HashSet; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.JsonNode; @@ -123,7 +120,7 @@ public class GmFruit extends AbstractOpenApiSchema { } // store a list of schema names defined in anyOf - public static final Map schemas = new HashMap(); + public static final Map> schemas = new HashMap>(); public GmFruit() { super("anyOf", Boolean.FALSE); @@ -140,15 +137,13 @@ public class GmFruit extends AbstractOpenApiSchema { } static { - schemas.put("Apple", new GenericType() { - }); - schemas.put("Banana", new GenericType() { - }); + schemas.put("Apple", Apple.class); + schemas.put("Banana", Banana.class); JSON.registerDescendants(GmFruit.class, Collections.unmodifiableMap(schemas)); } @Override - public Map getSchemas() { + public Map> getSchemas() { return GmFruit.schemas; } diff --git a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/Mammal.java b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/Mammal.java index 3d2522dae64..9d1e871feb9 100644 --- a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/Mammal.java +++ b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/Mammal.java @@ -33,8 +33,6 @@ import com.fasterxml.jackson.annotation.JsonPropertyOrder; import com.fasterxml.jackson.core.type.TypeReference; -import javax.ws.rs.core.GenericType; -import javax.ws.rs.core.Response; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; @@ -46,7 +44,6 @@ import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.JsonToken; -import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.JsonNode; @@ -211,7 +208,7 @@ public class Mammal extends AbstractOpenApiSchema { } // store a list of schema names defined in oneOf - public static final Map schemas = new HashMap(); + public static final Map> schemas = new HashMap<>(); public Mammal() { super("oneOf", Boolean.FALSE); @@ -233,12 +230,9 @@ public class Mammal extends AbstractOpenApiSchema { } static { - schemas.put("Pig", new GenericType() { - }); - schemas.put("Whale", new GenericType() { - }); - schemas.put("Zebra", new GenericType() { - }); + schemas.put("Pig", Pig.class); + schemas.put("Whale", Whale.class); + schemas.put("Zebra", Zebra.class); JSON.registerDescendants(Mammal.class, Collections.unmodifiableMap(schemas)); // Initialize and register the discriminator mappings. Map> mappings = new HashMap>(); @@ -250,7 +244,7 @@ public class Mammal extends AbstractOpenApiSchema { } @Override - public Map getSchemas() { + public Map> getSchemas() { return Mammal.schemas; } diff --git a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/NullableShape.java b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/NullableShape.java index f26f85dcbab..77d27e3e2c0 100644 --- a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/NullableShape.java +++ b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/NullableShape.java @@ -32,8 +32,6 @@ import com.fasterxml.jackson.annotation.JsonPropertyOrder; import com.fasterxml.jackson.core.type.TypeReference; -import javax.ws.rs.core.GenericType; -import javax.ws.rs.core.Response; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; @@ -45,7 +43,6 @@ import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.JsonToken; -import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.JsonNode; @@ -182,7 +179,7 @@ public class NullableShape extends AbstractOpenApiSchema { } // store a list of schema names defined in oneOf - public static final Map schemas = new HashMap(); + public static final Map> schemas = new HashMap<>(); public NullableShape() { super("oneOf", Boolean.TRUE); @@ -199,10 +196,8 @@ public class NullableShape extends AbstractOpenApiSchema { } static { - schemas.put("Quadrilateral", new GenericType() { - }); - schemas.put("Triangle", new GenericType() { - }); + schemas.put("Quadrilateral", Quadrilateral.class); + schemas.put("Triangle", Triangle.class); JSON.registerDescendants(NullableShape.class, Collections.unmodifiableMap(schemas)); // Initialize and register the discriminator mappings. Map> mappings = new HashMap>(); @@ -213,7 +208,7 @@ public class NullableShape extends AbstractOpenApiSchema { } @Override - public Map getSchemas() { + public Map> getSchemas() { return NullableShape.schemas; } diff --git a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/Pig.java b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/Pig.java index 3910494f419..e77218d922e 100644 --- a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/Pig.java +++ b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/Pig.java @@ -32,8 +32,6 @@ import com.fasterxml.jackson.annotation.JsonPropertyOrder; import com.fasterxml.jackson.core.type.TypeReference; -import javax.ws.rs.core.GenericType; -import javax.ws.rs.core.Response; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; @@ -45,7 +43,6 @@ import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.JsonToken; -import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.JsonNode; @@ -180,7 +177,7 @@ public class Pig extends AbstractOpenApiSchema { } // store a list of schema names defined in oneOf - public static final Map schemas = new HashMap(); + public static final Map> schemas = new HashMap<>(); public Pig() { super("oneOf", Boolean.FALSE); @@ -197,10 +194,8 @@ public class Pig extends AbstractOpenApiSchema { } static { - schemas.put("BasquePig", new GenericType() { - }); - schemas.put("DanishPig", new GenericType() { - }); + schemas.put("BasquePig", BasquePig.class); + schemas.put("DanishPig", DanishPig.class); JSON.registerDescendants(Pig.class, Collections.unmodifiableMap(schemas)); // Initialize and register the discriminator mappings. Map> mappings = new HashMap>(); @@ -211,7 +206,7 @@ public class Pig extends AbstractOpenApiSchema { } @Override - public Map getSchemas() { + public Map> getSchemas() { return Pig.schemas; } diff --git a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/Quadrilateral.java b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/Quadrilateral.java index 4898568a760..b2c184698db 100644 --- a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/Quadrilateral.java +++ b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/Quadrilateral.java @@ -32,8 +32,6 @@ import com.fasterxml.jackson.annotation.JsonPropertyOrder; import com.fasterxml.jackson.core.type.TypeReference; -import javax.ws.rs.core.GenericType; -import javax.ws.rs.core.Response; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; @@ -45,7 +43,6 @@ import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.JsonToken; -import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.JsonNode; @@ -180,7 +177,7 @@ public class Quadrilateral extends AbstractOpenApiSchema { } // store a list of schema names defined in oneOf - public static final Map schemas = new HashMap(); + public static final Map> schemas = new HashMap<>(); public Quadrilateral() { super("oneOf", Boolean.FALSE); @@ -197,10 +194,8 @@ public class Quadrilateral extends AbstractOpenApiSchema { } static { - schemas.put("ComplexQuadrilateral", new GenericType() { - }); - schemas.put("SimpleQuadrilateral", new GenericType() { - }); + schemas.put("ComplexQuadrilateral", ComplexQuadrilateral.class); + schemas.put("SimpleQuadrilateral", SimpleQuadrilateral.class); JSON.registerDescendants(Quadrilateral.class, Collections.unmodifiableMap(schemas)); // Initialize and register the discriminator mappings. Map> mappings = new HashMap>(); @@ -211,7 +206,7 @@ public class Quadrilateral extends AbstractOpenApiSchema { } @Override - public Map getSchemas() { + public Map> getSchemas() { return Quadrilateral.schemas; } diff --git a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/Shape.java b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/Shape.java index 2ed635f06d6..b29a366dad9 100644 --- a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/Shape.java +++ b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/Shape.java @@ -32,8 +32,6 @@ import com.fasterxml.jackson.annotation.JsonPropertyOrder; import com.fasterxml.jackson.core.type.TypeReference; -import javax.ws.rs.core.GenericType; -import javax.ws.rs.core.Response; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; @@ -45,7 +43,6 @@ import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.JsonToken; -import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.JsonNode; @@ -180,7 +177,7 @@ public class Shape extends AbstractOpenApiSchema { } // store a list of schema names defined in oneOf - public static final Map schemas = new HashMap(); + public static final Map> schemas = new HashMap<>(); public Shape() { super("oneOf", Boolean.FALSE); @@ -197,10 +194,8 @@ public class Shape extends AbstractOpenApiSchema { } static { - schemas.put("Quadrilateral", new GenericType() { - }); - schemas.put("Triangle", new GenericType() { - }); + schemas.put("Quadrilateral", Quadrilateral.class); + schemas.put("Triangle", Triangle.class); JSON.registerDescendants(Shape.class, Collections.unmodifiableMap(schemas)); // Initialize and register the discriminator mappings. Map> mappings = new HashMap>(); @@ -211,7 +206,7 @@ public class Shape extends AbstractOpenApiSchema { } @Override - public Map getSchemas() { + public Map> getSchemas() { return Shape.schemas; } diff --git a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/ShapeOrNull.java b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/ShapeOrNull.java index 732017cd9c5..05598727e13 100644 --- a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/ShapeOrNull.java +++ b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/ShapeOrNull.java @@ -32,8 +32,6 @@ import com.fasterxml.jackson.annotation.JsonPropertyOrder; import com.fasterxml.jackson.core.type.TypeReference; -import javax.ws.rs.core.GenericType; -import javax.ws.rs.core.Response; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; @@ -45,7 +43,6 @@ import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.JsonToken; -import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.JsonNode; @@ -182,7 +179,7 @@ public class ShapeOrNull extends AbstractOpenApiSchema { } // store a list of schema names defined in oneOf - public static final Map schemas = new HashMap(); + public static final Map> schemas = new HashMap<>(); public ShapeOrNull() { super("oneOf", Boolean.TRUE); @@ -199,10 +196,8 @@ public class ShapeOrNull extends AbstractOpenApiSchema { } static { - schemas.put("Quadrilateral", new GenericType() { - }); - schemas.put("Triangle", new GenericType() { - }); + schemas.put("Quadrilateral", Quadrilateral.class); + schemas.put("Triangle", Triangle.class); JSON.registerDescendants(ShapeOrNull.class, Collections.unmodifiableMap(schemas)); // Initialize and register the discriminator mappings. Map> mappings = new HashMap>(); @@ -213,7 +208,7 @@ public class ShapeOrNull extends AbstractOpenApiSchema { } @Override - public Map getSchemas() { + public Map> getSchemas() { return ShapeOrNull.schemas; } diff --git a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/Triangle.java b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/Triangle.java index 9638f2461f3..073b1c351f1 100644 --- a/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/Triangle.java +++ b/samples/openapi3/client/petstore/java/native/src/main/java/org/openapitools/client/model/Triangle.java @@ -33,8 +33,6 @@ import com.fasterxml.jackson.annotation.JsonPropertyOrder; import com.fasterxml.jackson.core.type.TypeReference; -import javax.ws.rs.core.GenericType; -import javax.ws.rs.core.Response; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; @@ -46,7 +44,6 @@ import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.JsonToken; -import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.JsonNode; @@ -211,7 +208,7 @@ public class Triangle extends AbstractOpenApiSchema { } // store a list of schema names defined in oneOf - public static final Map schemas = new HashMap(); + public static final Map> schemas = new HashMap<>(); public Triangle() { super("oneOf", Boolean.FALSE); @@ -233,12 +230,9 @@ public class Triangle extends AbstractOpenApiSchema { } static { - schemas.put("EquilateralTriangle", new GenericType() { - }); - schemas.put("IsoscelesTriangle", new GenericType() { - }); - schemas.put("ScaleneTriangle", new GenericType() { - }); + schemas.put("EquilateralTriangle", EquilateralTriangle.class); + schemas.put("IsoscelesTriangle", IsoscelesTriangle.class); + schemas.put("ScaleneTriangle", ScaleneTriangle.class); JSON.registerDescendants(Triangle.class, Collections.unmodifiableMap(schemas)); // Initialize and register the discriminator mappings. Map> mappings = new HashMap>(); @@ -250,7 +244,7 @@ public class Triangle extends AbstractOpenApiSchema { } @Override - public Map getSchemas() { + public Map> getSchemas() { return Triangle.schemas; } diff --git a/samples/openapi3/client/petstore/python-legacy/.openapi-generator/VERSION b/samples/openapi3/client/petstore/python-legacy/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100755 --- a/samples/openapi3/client/petstore/python-legacy/.openapi-generator/VERSION +++ b/samples/openapi3/client/petstore/python-legacy/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/openapi3/client/petstore/python-legacy/README.md b/samples/openapi3/client/petstore/python-legacy/README.md index 65ce00102b4..507b849f5b2 100755 --- a/samples/openapi3/client/petstore/python-legacy/README.md +++ b/samples/openapi3/client/petstore/python-legacy/README.md @@ -90,6 +90,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_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 diff --git a/samples/openapi3/client/petstore/python-legacy/docs/FakeApi.md b/samples/openapi3/client/petstore/python-legacy/docs/FakeApi.md index f7bbbecdce6..f958d8f71a0 100755 --- a/samples/openapi3/client/petstore/python-legacy/docs/FakeApi.md +++ b/samples/openapi3/client/petstore/python-legacy/docs/FakeApi.md @@ -11,6 +11,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_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 @@ -510,12 +511,72 @@ 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_with_binary** +> test_body_with_binary(body) + + + +For this test, the body has to be a binary file. + +### Example + +```python +from __future__ import print_function +import time +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() as api_client: + # Create an instance of the API class + api_instance = petstore_api.FakeApi(api_client) + body = '/path/to/file' # file | image to upload + + try: + api_instance.test_body_with_binary(body) + except ApiException as e: + print("Exception when calling FakeApi->test_body_with_binary: %s\n" % e) +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | **file**| image to upload | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: image/png + - **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_body_with_file_schema** > test_body_with_file_schema(file_schema_test_class) -For this test, the body for this request much reference a schema named `File`. +For this test, the body for this request must reference a schema named `File`. ### Example diff --git a/samples/openapi3/client/petstore/python-legacy/petstore_api/api/fake_api.py b/samples/openapi3/client/petstore/python-legacy/petstore_api/api/fake_api.py index d5dd027679e..f2bf00824f9 100755 --- a/samples/openapi3/client/petstore/python-legacy/petstore_api/api/fake_api.py +++ b/samples/openapi3/client/petstore/python-legacy/petstore_api/api/fake_api.py @@ -982,10 +982,139 @@ class FakeApi(object): collection_formats=collection_formats, _request_auth=local_var_params.get('_request_auth')) + def test_body_with_binary(self, body, **kwargs): # noqa: E501 + """test_body_with_binary # noqa: E501 + + 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: file + :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: None + """ + kwargs['_return_http_data_only'] = True + return self.test_body_with_binary_with_http_info(body, **kwargs) # noqa: E501 + + def test_body_with_binary_with_http_info(self, body, **kwargs): # noqa: E501 + """test_body_with_binary # noqa: E501 + + 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 body: image to upload (required) + :type body: file + :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 + :return: Returns the result object. + If the method is called asynchronously, + returns the request thread. + :rtype: None + """ + + local_var_params = locals() + + all_params = [ + 'body' + ] + all_params.extend( + [ + 'async_req', + '_return_http_data_only', + '_preload_content', + '_request_timeout', + '_request_auth' + ] + ) + + for key, val in six.iteritems(local_var_params['kwargs']): + if key not in all_params: + raise ApiTypeError( + "Got an unexpected keyword argument '%s'" + " to method test_body_with_binary" % key + ) + local_var_params[key] = val + del local_var_params['kwargs'] + + collection_formats = {} + + path_params = {} + + query_params = [] + + header_params = {} + + form_params = [] + local_var_files = {} + + body_params = None + if 'body' in local_var_params: + body_params = local_var_params['body'] + # HTTP header `Content-Type` + header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 + ['image/png']) # noqa: E501 + + # Authentication setting + auth_settings = [] # noqa: E501 + + response_types_map = {} + + return self.api_client.call_api( + '/fake/body-with-binary', 'PUT', + 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')) + def test_body_with_file_schema(self, file_schema_test_class, **kwargs): # noqa: E501 """test_body_with_file_schema # noqa: E501 - For this test, the body for this request much reference a schema named `File`. # noqa: E501 + 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 @@ -1015,7 +1144,7 @@ class FakeApi(object): def test_body_with_file_schema_with_http_info(self, file_schema_test_class, **kwargs): # noqa: E501 """test_body_with_file_schema # noqa: E501 - For this test, the body for this request much reference a schema named `File`. # noqa: E501 + 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 @@ -2422,7 +2551,7 @@ class FakeApi(object): query_params = [] if 'pipe' in local_var_params and local_var_params['pipe'] is not None: # noqa: E501 query_params.append(('pipe', local_var_params['pipe'])) # noqa: E501 - collection_formats['pipe'] = 'multi' # noqa: E501 + collection_formats['pipe'] = 'pipes' # noqa: E501 if 'ioutil' in local_var_params and local_var_params['ioutil'] is not None: # noqa: E501 query_params.append(('ioutil', local_var_params['ioutil'])) # noqa: E501 collection_formats['ioutil'] = 'csv' # noqa: E501 diff --git a/samples/openapi3/client/petstore/python/.openapi-generator/FILES b/samples/openapi3/client/petstore/python/.openapi-generator/FILES index 9e23967bd9a..bf96206001f 100644 --- a/samples/openapi3/client/petstore/python/.openapi-generator/FILES +++ b/samples/openapi3/client/petstore/python/.openapi-generator/FILES @@ -40,7 +40,7 @@ docs/EnumTest.md docs/EquilateralTriangle.md docs/FakeApi.md docs/FakeClassnameTags123Api.md -docs/FakeGetInlineAdditionalPropertiesPayloadArrayData.md +docs/FakePostInlineAdditionalPropertiesPayloadArrayData.md docs/File.md docs/FileSchemaTestClass.md docs/Foo.md @@ -150,7 +150,7 @@ petstore_api/model/enum_arrays.py petstore_api/model/enum_class.py petstore_api/model/enum_test.py petstore_api/model/equilateral_triangle.py -petstore_api/model/fake_get_inline_additional_properties_payload_array_data.py +petstore_api/model/fake_post_inline_additional_properties_payload_array_data.py petstore_api/model/file.py petstore_api/model/file_schema_test_class.py petstore_api/model/foo.py diff --git a/samples/openapi3/client/petstore/python/.openapi-generator/VERSION b/samples/openapi3/client/petstore/python/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/openapi3/client/petstore/python/.openapi-generator/VERSION +++ b/samples/openapi3/client/petstore/python/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/openapi3/client/petstore/python/README.md b/samples/openapi3/client/petstore/python/README.md index bf7ae031db4..beb64bb7e04 100644 --- a/samples/openapi3/client/petstore/python/README.md +++ b/samples/openapi3/client/petstore/python/README.md @@ -91,11 +91,11 @@ Class | Method | HTTP request | Description *FakeApi* | [**download_attachment**](docs/FakeApi.md#download_attachment) | **GET** /{fileName} | downloads a file using Content-Disposition *FakeApi* | [**enum_test**](docs/FakeApi.md#enum_test) | **POST** /fake/refs/enum-test | Object contains enum properties and array properties containing enums *FakeApi* | [**fake_health_get**](docs/FakeApi.md#fake_health_get) | **GET** /fake/health | Health check endpoint -*FakeApi* | [**get_inline_additional_properties_payload**](docs/FakeApi.md#get_inline_additional_properties_payload) | **GET** /fake/getInlineAdditionalPropertiesPayload | -*FakeApi* | [**get_inline_additional_properties_ref_payload**](docs/FakeApi.md#get_inline_additional_properties_ref_payload) | **GET** /fake/getInlineAdditionalPropertiesRefPayload | *FakeApi* | [**mammal**](docs/FakeApi.md#mammal) | **POST** /fake/refs/mammal | *FakeApi* | [**number_with_validations**](docs/FakeApi.md#number_with_validations) | **POST** /fake/refs/number | *FakeApi* | [**object_model_with_ref_props**](docs/FakeApi.md#object_model_with_ref_props) | **POST** /fake/refs/object_model_with_ref_props | +*FakeApi* | [**post_inline_additional_properties_payload**](docs/FakeApi.md#post_inline_additional_properties_payload) | **POST** /fake/postInlineAdditionalPropertiesPayload | +*FakeApi* | [**post_inline_additional_properties_ref_payload**](docs/FakeApi.md#post_inline_additional_properties_ref_payload) | **POST** /fake/postInlineAdditionalPropertiesRefPayload | *FakeApi* | [**string**](docs/FakeApi.md#string) | **POST** /fake/refs/string | *FakeApi* | [**string_enum**](docs/FakeApi.md#string_enum) | **POST** /fake/refs/enum | *FakeApi* | [**test_body_with_file_schema**](docs/FakeApi.md#test_body_with_file_schema) | **PUT** /fake/body-with-file-schema | @@ -168,7 +168,7 @@ Class | Method | HTTP request | Description - [EnumClass](docs/EnumClass.md) - [EnumTest](docs/EnumTest.md) - [EquilateralTriangle](docs/EquilateralTriangle.md) - - [FakeGetInlineAdditionalPropertiesPayloadArrayData](docs/FakeGetInlineAdditionalPropertiesPayloadArrayData.md) + - [FakePostInlineAdditionalPropertiesPayloadArrayData](docs/FakePostInlineAdditionalPropertiesPayloadArrayData.md) - [File](docs/File.md) - [FileSchemaTestClass](docs/FileSchemaTestClass.md) - [Foo](docs/Foo.md) diff --git a/samples/openapi3/client/petstore/python/docs/FakeApi.md b/samples/openapi3/client/petstore/python/docs/FakeApi.md index acc41cb4899..5802b45cb39 100644 --- a/samples/openapi3/client/petstore/python/docs/FakeApi.md +++ b/samples/openapi3/client/petstore/python/docs/FakeApi.md @@ -12,11 +12,11 @@ Method | HTTP request | Description [**download_attachment**](FakeApi.md#download_attachment) | **GET** /{fileName} | downloads a file using Content-Disposition [**enum_test**](FakeApi.md#enum_test) | **POST** /fake/refs/enum-test | Object contains enum properties and array properties containing enums [**fake_health_get**](FakeApi.md#fake_health_get) | **GET** /fake/health | Health check endpoint -[**get_inline_additional_properties_payload**](FakeApi.md#get_inline_additional_properties_payload) | **GET** /fake/getInlineAdditionalPropertiesPayload | -[**get_inline_additional_properties_ref_payload**](FakeApi.md#get_inline_additional_properties_ref_payload) | **GET** /fake/getInlineAdditionalPropertiesRefPayload | [**mammal**](FakeApi.md#mammal) | **POST** /fake/refs/mammal | [**number_with_validations**](FakeApi.md#number_with_validations) | **POST** /fake/refs/number | [**object_model_with_ref_props**](FakeApi.md#object_model_with_ref_props) | **POST** /fake/refs/object_model_with_ref_props | +[**post_inline_additional_properties_payload**](FakeApi.md#post_inline_additional_properties_payload) | **POST** /fake/postInlineAdditionalPropertiesPayload | +[**post_inline_additional_properties_ref_payload**](FakeApi.md#post_inline_additional_properties_ref_payload) | **POST** /fake/postInlineAdditionalPropertiesRefPayload | [**string**](FakeApi.md#string) | **POST** /fake/refs/string | [**string_enum**](FakeApi.md#string_enum) | **POST** /fake/refs/enum | [**test_body_with_file_schema**](FakeApi.md#test_body_with_file_schema) | **PUT** /fake/body-with-file-schema | @@ -564,148 +564,6 @@ 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) -# **get_inline_additional_properties_payload** -> InlineObject6 get_inline_additional_properties_payload() - - - -### Example - -```python -import time -import petstore_api -from petstore_api.api import fake_api -from petstore_api.model.inline_object6 import InlineObject6 -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() as api_client: - # Create an instance of the API class - api_instance = fake_api.FakeApi(api_client) - inline_object6 = InlineObject6( - array_data=[ - FakeGetInlineAdditionalPropertiesPayloadArrayData( - labels=[ - "labels_example", - ], - ), - ], - ) # InlineObject6 | (optional) - - # example passing only required values which don't have defaults set - # and optional values - try: - api_response = api_instance.get_inline_additional_properties_payload(inline_object6=inline_object6) - pprint(api_response) - except petstore_api.ApiException as e: - print("Exception when calling FakeApi->get_inline_additional_properties_payload: %s\n" % e) -``` - - -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **inline_object6** | [**InlineObject6**](InlineObject6.md)| | [optional] - -### Return type - -[**InlineObject6**](InlineObject6.md) - -### Authorization - -No authorization required - -### HTTP request headers - - - **Content-Type**: application/json - - **Accept**: application/json - - -### HTTP response details -| Status code | Description | Response headers | -|-------------|-------------|------------------| -**200** | InlineAdditionalPropertiesPayload | - | - -[[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) - -# **get_inline_additional_properties_ref_payload** -> InlineAdditionalPropertiesRefPayload get_inline_additional_properties_ref_payload() - - - -### Example - -```python -import time -import petstore_api -from petstore_api.api import fake_api -from petstore_api.model.inline_additional_properties_ref_payload import InlineAdditionalPropertiesRefPayload -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() as api_client: - # Create an instance of the API class - api_instance = fake_api.FakeApi(api_client) - inline_additional_properties_ref_payload = InlineAdditionalPropertiesRefPayload( - array_data=[ - FakeGetInlineAdditionalPropertiesPayloadArrayData( - labels=[ - "labels_example", - ], - ), - ], - ) # InlineAdditionalPropertiesRefPayload | (optional) - - # example passing only required values which don't have defaults set - # and optional values - try: - api_response = api_instance.get_inline_additional_properties_ref_payload(inline_additional_properties_ref_payload=inline_additional_properties_ref_payload) - pprint(api_response) - except petstore_api.ApiException as e: - print("Exception when calling FakeApi->get_inline_additional_properties_ref_payload: %s\n" % e) -``` - - -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **inline_additional_properties_ref_payload** | [**InlineAdditionalPropertiesRefPayload**](InlineAdditionalPropertiesRefPayload.md)| | [optional] - -### Return type - -[**InlineAdditionalPropertiesRefPayload**](InlineAdditionalPropertiesRefPayload.md) - -### Authorization - -No authorization required - -### HTTP request headers - - - **Content-Type**: application/json - - **Accept**: application/json - - -### HTTP response details -| Status code | Description | Response headers | -|-------------|-------------|------------------| -**200** | InlineAdditionalPropertiesRefPayload | - | - -[[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) - # **mammal** > Mammal mammal(mammal) @@ -908,6 +766,148 @@ 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) +# **post_inline_additional_properties_payload** +> InlineObject6 post_inline_additional_properties_payload() + + + +### Example + +```python +import time +import petstore_api +from petstore_api.api import fake_api +from petstore_api.model.inline_object6 import InlineObject6 +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() as api_client: + # Create an instance of the API class + api_instance = fake_api.FakeApi(api_client) + inline_object6 = InlineObject6( + array_data=[ + FakePostInlineAdditionalPropertiesPayloadArrayData( + labels=[ + "labels_example", + ], + ), + ], + ) # InlineObject6 | (optional) + + # example passing only required values which don't have defaults set + # and optional values + try: + api_response = api_instance.post_inline_additional_properties_payload(inline_object6=inline_object6) + pprint(api_response) + except petstore_api.ApiException as e: + print("Exception when calling FakeApi->post_inline_additional_properties_payload: %s\n" % e) +``` + + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **inline_object6** | [**InlineObject6**](InlineObject6.md)| | [optional] + +### Return type + +[**InlineObject6**](InlineObject6.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: application/json + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | InlineAdditionalPropertiesPayload | - | + +[[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) + +# **post_inline_additional_properties_ref_payload** +> InlineAdditionalPropertiesRefPayload post_inline_additional_properties_ref_payload() + + + +### Example + +```python +import time +import petstore_api +from petstore_api.api import fake_api +from petstore_api.model.inline_additional_properties_ref_payload import InlineAdditionalPropertiesRefPayload +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() as api_client: + # Create an instance of the API class + api_instance = fake_api.FakeApi(api_client) + inline_additional_properties_ref_payload = InlineAdditionalPropertiesRefPayload( + array_data=[ + FakePostInlineAdditionalPropertiesPayloadArrayData( + labels=[ + "labels_example", + ], + ), + ], + ) # InlineAdditionalPropertiesRefPayload | (optional) + + # example passing only required values which don't have defaults set + # and optional values + try: + api_response = api_instance.post_inline_additional_properties_ref_payload(inline_additional_properties_ref_payload=inline_additional_properties_ref_payload) + pprint(api_response) + except petstore_api.ApiException as e: + print("Exception when calling FakeApi->post_inline_additional_properties_ref_payload: %s\n" % e) +``` + + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **inline_additional_properties_ref_payload** | [**InlineAdditionalPropertiesRefPayload**](InlineAdditionalPropertiesRefPayload.md)| | [optional] + +### Return type + +[**InlineAdditionalPropertiesRefPayload**](InlineAdditionalPropertiesRefPayload.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: application/json + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | InlineAdditionalPropertiesRefPayload | - | + +[[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) + # **string** > str string() diff --git a/samples/openapi3/client/petstore/python/docs/FakeGetInlineAdditionalPropertiesPayloadArrayData.md b/samples/openapi3/client/petstore/python/docs/FakePostInlineAdditionalPropertiesPayloadArrayData.md similarity index 90% rename from samples/openapi3/client/petstore/python/docs/FakeGetInlineAdditionalPropertiesPayloadArrayData.md rename to samples/openapi3/client/petstore/python/docs/FakePostInlineAdditionalPropertiesPayloadArrayData.md index 6c3418d8c07..23ec35f5dcd 100644 --- a/samples/openapi3/client/petstore/python/docs/FakeGetInlineAdditionalPropertiesPayloadArrayData.md +++ b/samples/openapi3/client/petstore/python/docs/FakePostInlineAdditionalPropertiesPayloadArrayData.md @@ -1,4 +1,4 @@ -# FakeGetInlineAdditionalPropertiesPayloadArrayData +# FakePostInlineAdditionalPropertiesPayloadArrayData ## Properties diff --git a/samples/openapi3/client/petstore/python/docs/InlineAdditionalPropertiesRefPayload.md b/samples/openapi3/client/petstore/python/docs/InlineAdditionalPropertiesRefPayload.md index 5922fc61f1a..f99ed143d3f 100644 --- a/samples/openapi3/client/petstore/python/docs/InlineAdditionalPropertiesRefPayload.md +++ b/samples/openapi3/client/petstore/python/docs/InlineAdditionalPropertiesRefPayload.md @@ -5,7 +5,7 @@ this payload is used for verification that some model_to_dict issues are fixed ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**array_data** | [**[FakeGetInlineAdditionalPropertiesPayloadArrayData], none_type**](FakeGetInlineAdditionalPropertiesPayloadArrayData.md) | | [optional] +**array_data** | [**[FakePostInlineAdditionalPropertiesPayloadArrayData], none_type**](FakePostInlineAdditionalPropertiesPayloadArrayData.md) | | [optional] **any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [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/python/docs/InlineObject6.md b/samples/openapi3/client/petstore/python/docs/InlineObject6.md index fc83501c154..b4a7a55a2c7 100644 --- a/samples/openapi3/client/petstore/python/docs/InlineObject6.md +++ b/samples/openapi3/client/petstore/python/docs/InlineObject6.md @@ -5,7 +5,7 @@ this payload is used for verification that some model_to_dict issues are fixed ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**array_data** | [**[FakeGetInlineAdditionalPropertiesPayloadArrayData], none_type**](FakeGetInlineAdditionalPropertiesPayloadArrayData.md) | | [optional] +**array_data** | [**[FakePostInlineAdditionalPropertiesPayloadArrayData], none_type**](FakePostInlineAdditionalPropertiesPayloadArrayData.md) | | [optional] **any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [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/python/petstore_api/api/another_fake_api.py b/samples/openapi3/client/petstore/python/petstore_api/api/another_fake_api.py index 4e6f26e4e33..4072532f378 100644 --- 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 @@ -59,8 +59,8 @@ class AnotherFakeApi(object): _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. - _request_timeout (float/tuple): timeout setting for this request. If one - number provided, it will be total request timeout. It can also + _request_timeout (int/float/tuple): timeout setting for this request. If + one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking 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 070ae6b4f47..21f9ca13b05 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/api/default_api.py +++ b/samples/openapi3/client/petstore/python/petstore_api/api/default_api.py @@ -55,8 +55,8 @@ class DefaultApi(object): _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. - _request_timeout (float/tuple): timeout setting for this request. If one - number provided, it will be total request timeout. It can also + _request_timeout (int/float/tuple): timeout setting for this request. If + one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking 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 27a387e0570..37f1268be14 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/api/fake_api.py +++ b/samples/openapi3/client/petstore/python/petstore_api/api/fake_api.py @@ -71,8 +71,8 @@ class FakeApi(object): _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. - _request_timeout (float/tuple): timeout setting for this request. If one - number provided, it will be total request timeout. It can also + _request_timeout (int/float/tuple): timeout setting for this request. If + one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking @@ -183,8 +183,8 @@ class FakeApi(object): _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. - _request_timeout (float/tuple): timeout setting for this request. If one - number provided, it will be total request timeout. It can also + _request_timeout (int/float/tuple): timeout setting for this request. If + one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking @@ -294,8 +294,8 @@ class FakeApi(object): _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. - _request_timeout (float/tuple): timeout setting for this request. If one - number provided, it will be total request timeout. It can also + _request_timeout (int/float/tuple): timeout setting for this request. If + one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking @@ -406,8 +406,8 @@ class FakeApi(object): _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. - _request_timeout (float/tuple): timeout setting for this request. If one - number provided, it will be total request timeout. It can also + _request_timeout (int/float/tuple): timeout setting for this request. If + one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking @@ -518,8 +518,8 @@ class FakeApi(object): _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. - _request_timeout (float/tuple): timeout setting for this request. If one - number provided, it will be total request timeout. It can also + _request_timeout (int/float/tuple): timeout setting for this request. If + one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking @@ -631,8 +631,8 @@ class FakeApi(object): _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. - _request_timeout (float/tuple): timeout setting for this request. If one - number provided, it will be total request timeout. It can also + _request_timeout (int/float/tuple): timeout setting for this request. If + one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking @@ -750,8 +750,8 @@ class FakeApi(object): _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. - _request_timeout (float/tuple): timeout setting for this request. If one - number provided, it will be total request timeout. It can also + _request_timeout (int/float/tuple): timeout setting for this request. If + one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking @@ -860,8 +860,8 @@ class FakeApi(object): _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. - _request_timeout (float/tuple): timeout setting for this request. If one - number provided, it will be total request timeout. It can also + _request_timeout (int/float/tuple): timeout setting for this request. If + one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking @@ -945,228 +945,6 @@ class FakeApi(object): callable=__fake_health_get ) - def __get_inline_additional_properties_payload( - self, - **kwargs - ): - """get_inline_additional_properties_payload # 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_inline_additional_properties_payload(async_req=True) - >>> result = thread.get() - - - Keyword Args: - inline_object6 (InlineObject6): [optional] - _return_http_data_only (bool): response data without head status - code and headers. Default is True. - _preload_content (bool): if False, the urllib3.HTTPResponse object - will be returned without reading/decoding response data. - Default is True. - _request_timeout (float/tuple): timeout setting for this request. If one - number provided, it will be total request timeout. It can also - be a pair (tuple) of (connection, read) timeouts. - Default is None. - _check_input_type (bool): specifies if type checking - should be done one the data sent to the server. - Default is True. - _check_return_type (bool): specifies if type checking - should be done one the data received from the server. - Default is True. - _host_index (int/None): specifies the index of the server - that we want to use. - Default is read from the configuration. - async_req (bool): execute request asynchronously - - Returns: - InlineObject6 - If the method is called asynchronously, returns the request - thread. - """ - kwargs['async_req'] = kwargs.get( - 'async_req', False - ) - kwargs['_return_http_data_only'] = kwargs.get( - '_return_http_data_only', True - ) - kwargs['_preload_content'] = kwargs.get( - '_preload_content', True - ) - kwargs['_request_timeout'] = kwargs.get( - '_request_timeout', None - ) - kwargs['_check_input_type'] = kwargs.get( - '_check_input_type', True - ) - kwargs['_check_return_type'] = kwargs.get( - '_check_return_type', True - ) - kwargs['_host_index'] = kwargs.get('_host_index') - return self.call_with_http_info(**kwargs) - - self.get_inline_additional_properties_payload = _Endpoint( - settings={ - 'response_type': (InlineObject6,), - 'auth': [], - 'endpoint_path': '/fake/getInlineAdditionalPropertiesPayload', - 'operation_id': 'get_inline_additional_properties_payload', - 'http_method': 'GET', - 'servers': None, - }, - params_map={ - 'all': [ - 'inline_object6', - ], - 'required': [], - 'nullable': [ - ], - 'enum': [ - ], - 'validation': [ - ] - }, - root_map={ - 'validations': { - }, - 'allowed_values': { - }, - 'openapi_types': { - 'inline_object6': - (InlineObject6,), - }, - 'attribute_map': { - }, - 'location_map': { - 'inline_object6': 'body', - }, - 'collection_format_map': { - } - }, - headers_map={ - 'accept': [ - 'application/json' - ], - 'content_type': [ - 'application/json' - ] - }, - api_client=api_client, - callable=__get_inline_additional_properties_payload - ) - - def __get_inline_additional_properties_ref_payload( - self, - **kwargs - ): - """get_inline_additional_properties_ref_payload # 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_inline_additional_properties_ref_payload(async_req=True) - >>> result = thread.get() - - - Keyword Args: - inline_additional_properties_ref_payload (InlineAdditionalPropertiesRefPayload): [optional] - _return_http_data_only (bool): response data without head status - code and headers. Default is True. - _preload_content (bool): if False, the urllib3.HTTPResponse object - will be returned without reading/decoding response data. - Default is True. - _request_timeout (float/tuple): timeout setting for this request. If one - number provided, it will be total request timeout. It can also - be a pair (tuple) of (connection, read) timeouts. - Default is None. - _check_input_type (bool): specifies if type checking - should be done one the data sent to the server. - Default is True. - _check_return_type (bool): specifies if type checking - should be done one the data received from the server. - Default is True. - _host_index (int/None): specifies the index of the server - that we want to use. - Default is read from the configuration. - async_req (bool): execute request asynchronously - - Returns: - InlineAdditionalPropertiesRefPayload - If the method is called asynchronously, returns the request - thread. - """ - kwargs['async_req'] = kwargs.get( - 'async_req', False - ) - kwargs['_return_http_data_only'] = kwargs.get( - '_return_http_data_only', True - ) - kwargs['_preload_content'] = kwargs.get( - '_preload_content', True - ) - kwargs['_request_timeout'] = kwargs.get( - '_request_timeout', None - ) - kwargs['_check_input_type'] = kwargs.get( - '_check_input_type', True - ) - kwargs['_check_return_type'] = kwargs.get( - '_check_return_type', True - ) - kwargs['_host_index'] = kwargs.get('_host_index') - return self.call_with_http_info(**kwargs) - - self.get_inline_additional_properties_ref_payload = _Endpoint( - settings={ - 'response_type': (InlineAdditionalPropertiesRefPayload,), - 'auth': [], - 'endpoint_path': '/fake/getInlineAdditionalPropertiesRefPayload', - 'operation_id': 'get_inline_additional_properties_ref_payload', - 'http_method': 'GET', - 'servers': None, - }, - params_map={ - 'all': [ - 'inline_additional_properties_ref_payload', - ], - 'required': [], - 'nullable': [ - ], - 'enum': [ - ], - 'validation': [ - ] - }, - root_map={ - 'validations': { - }, - 'allowed_values': { - }, - 'openapi_types': { - 'inline_additional_properties_ref_payload': - (InlineAdditionalPropertiesRefPayload,), - }, - 'attribute_map': { - }, - 'location_map': { - 'inline_additional_properties_ref_payload': 'body', - }, - 'collection_format_map': { - } - }, - headers_map={ - 'accept': [ - 'application/json' - ], - 'content_type': [ - 'application/json' - ] - }, - api_client=api_client, - callable=__get_inline_additional_properties_ref_payload - ) - def __mammal( self, mammal, @@ -1190,8 +968,8 @@ class FakeApi(object): _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. - _request_timeout (float/tuple): timeout setting for this request. If one - number provided, it will be total request timeout. It can also + _request_timeout (int/float/tuple): timeout setting for this request. If + one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking @@ -1306,8 +1084,8 @@ class FakeApi(object): _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. - _request_timeout (float/tuple): timeout setting for this request. If one - number provided, it will be total request timeout. It can also + _request_timeout (int/float/tuple): timeout setting for this request. If + one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking @@ -1418,8 +1196,8 @@ class FakeApi(object): _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. - _request_timeout (float/tuple): timeout setting for this request. If one - number provided, it will be total request timeout. It can also + _request_timeout (int/float/tuple): timeout setting for this request. If + one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking @@ -1509,6 +1287,228 @@ class FakeApi(object): callable=__object_model_with_ref_props ) + def __post_inline_additional_properties_payload( + self, + **kwargs + ): + """post_inline_additional_properties_payload # noqa: E501 + + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + + >>> thread = api.post_inline_additional_properties_payload(async_req=True) + >>> result = thread.get() + + + Keyword Args: + inline_object6 (InlineObject6): [optional] + _return_http_data_only (bool): response data without head status + code and headers. Default is True. + _preload_content (bool): if False, the urllib3.HTTPResponse object + will be returned without reading/decoding response data. + Default is True. + _request_timeout (int/float/tuple): timeout setting for this request. If + one number provided, it will be total request timeout. It can also + be a pair (tuple) of (connection, read) timeouts. + Default is None. + _check_input_type (bool): specifies if type checking + should be done one the data sent to the server. + Default is True. + _check_return_type (bool): specifies if type checking + should be done one the data received from the server. + Default is True. + _host_index (int/None): specifies the index of the server + that we want to use. + Default is read from the configuration. + async_req (bool): execute request asynchronously + + Returns: + InlineObject6 + If the method is called asynchronously, returns the request + thread. + """ + kwargs['async_req'] = kwargs.get( + 'async_req', False + ) + kwargs['_return_http_data_only'] = kwargs.get( + '_return_http_data_only', True + ) + kwargs['_preload_content'] = kwargs.get( + '_preload_content', True + ) + kwargs['_request_timeout'] = kwargs.get( + '_request_timeout', None + ) + kwargs['_check_input_type'] = kwargs.get( + '_check_input_type', True + ) + kwargs['_check_return_type'] = kwargs.get( + '_check_return_type', True + ) + kwargs['_host_index'] = kwargs.get('_host_index') + return self.call_with_http_info(**kwargs) + + self.post_inline_additional_properties_payload = _Endpoint( + settings={ + 'response_type': (InlineObject6,), + 'auth': [], + 'endpoint_path': '/fake/postInlineAdditionalPropertiesPayload', + 'operation_id': 'post_inline_additional_properties_payload', + 'http_method': 'POST', + 'servers': None, + }, + params_map={ + 'all': [ + 'inline_object6', + ], + 'required': [], + 'nullable': [ + ], + 'enum': [ + ], + 'validation': [ + ] + }, + root_map={ + 'validations': { + }, + 'allowed_values': { + }, + 'openapi_types': { + 'inline_object6': + (InlineObject6,), + }, + 'attribute_map': { + }, + 'location_map': { + 'inline_object6': 'body', + }, + 'collection_format_map': { + } + }, + headers_map={ + 'accept': [ + 'application/json' + ], + 'content_type': [ + 'application/json' + ] + }, + api_client=api_client, + callable=__post_inline_additional_properties_payload + ) + + def __post_inline_additional_properties_ref_payload( + self, + **kwargs + ): + """post_inline_additional_properties_ref_payload # noqa: E501 + + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + + >>> thread = api.post_inline_additional_properties_ref_payload(async_req=True) + >>> result = thread.get() + + + Keyword Args: + inline_additional_properties_ref_payload (InlineAdditionalPropertiesRefPayload): [optional] + _return_http_data_only (bool): response data without head status + code and headers. Default is True. + _preload_content (bool): if False, the urllib3.HTTPResponse object + will be returned without reading/decoding response data. + Default is True. + _request_timeout (int/float/tuple): timeout setting for this request. If + one number provided, it will be total request timeout. It can also + be a pair (tuple) of (connection, read) timeouts. + Default is None. + _check_input_type (bool): specifies if type checking + should be done one the data sent to the server. + Default is True. + _check_return_type (bool): specifies if type checking + should be done one the data received from the server. + Default is True. + _host_index (int/None): specifies the index of the server + that we want to use. + Default is read from the configuration. + async_req (bool): execute request asynchronously + + Returns: + InlineAdditionalPropertiesRefPayload + If the method is called asynchronously, returns the request + thread. + """ + kwargs['async_req'] = kwargs.get( + 'async_req', False + ) + kwargs['_return_http_data_only'] = kwargs.get( + '_return_http_data_only', True + ) + kwargs['_preload_content'] = kwargs.get( + '_preload_content', True + ) + kwargs['_request_timeout'] = kwargs.get( + '_request_timeout', None + ) + kwargs['_check_input_type'] = kwargs.get( + '_check_input_type', True + ) + kwargs['_check_return_type'] = kwargs.get( + '_check_return_type', True + ) + kwargs['_host_index'] = kwargs.get('_host_index') + return self.call_with_http_info(**kwargs) + + self.post_inline_additional_properties_ref_payload = _Endpoint( + settings={ + 'response_type': (InlineAdditionalPropertiesRefPayload,), + 'auth': [], + 'endpoint_path': '/fake/postInlineAdditionalPropertiesRefPayload', + 'operation_id': 'post_inline_additional_properties_ref_payload', + 'http_method': 'POST', + 'servers': None, + }, + params_map={ + 'all': [ + 'inline_additional_properties_ref_payload', + ], + 'required': [], + 'nullable': [ + ], + 'enum': [ + ], + 'validation': [ + ] + }, + root_map={ + 'validations': { + }, + 'allowed_values': { + }, + 'openapi_types': { + 'inline_additional_properties_ref_payload': + (InlineAdditionalPropertiesRefPayload,), + }, + 'attribute_map': { + }, + 'location_map': { + 'inline_additional_properties_ref_payload': 'body', + }, + 'collection_format_map': { + } + }, + headers_map={ + 'accept': [ + 'application/json' + ], + 'content_type': [ + 'application/json' + ] + }, + api_client=api_client, + callable=__post_inline_additional_properties_ref_payload + ) + def __string( self, **kwargs @@ -1530,8 +1530,8 @@ class FakeApi(object): _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. - _request_timeout (float/tuple): timeout setting for this request. If one - number provided, it will be total request timeout. It can also + _request_timeout (int/float/tuple): timeout setting for this request. If + one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking @@ -1642,8 +1642,8 @@ class FakeApi(object): _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. - _request_timeout (float/tuple): timeout setting for this request. If one - number provided, it will be total request timeout. It can also + _request_timeout (int/float/tuple): timeout setting for this request. If + one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking @@ -1757,8 +1757,8 @@ class FakeApi(object): _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. - _request_timeout (float/tuple): timeout setting for this request. If one - number provided, it will be total request timeout. It can also + _request_timeout (int/float/tuple): timeout setting for this request. If + one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking @@ -1874,8 +1874,8 @@ class FakeApi(object): _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. - _request_timeout (float/tuple): timeout setting for this request. If one - number provided, it will be total request timeout. It can also + _request_timeout (int/float/tuple): timeout setting for this request. If + one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking @@ -1998,8 +1998,8 @@ class FakeApi(object): _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. - _request_timeout (float/tuple): timeout setting for this request. If one - number provided, it will be total request timeout. It can also + _request_timeout (int/float/tuple): timeout setting for this request. If + one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking @@ -2132,8 +2132,8 @@ class FakeApi(object): _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. - _request_timeout (float/tuple): timeout setting for this request. If one - number provided, it will be total request timeout. It can also + _request_timeout (int/float/tuple): timeout setting for this request. If + one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking @@ -2379,8 +2379,8 @@ class FakeApi(object): _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. - _request_timeout (float/tuple): timeout setting for this request. If one - number provided, it will be total request timeout. It can also + _request_timeout (int/float/tuple): timeout setting for this request. If + one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking @@ -2588,8 +2588,8 @@ class FakeApi(object): _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. - _request_timeout (float/tuple): timeout setting for this request. If one - number provided, it will be total request timeout. It can also + _request_timeout (int/float/tuple): timeout setting for this request. If + one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking @@ -2735,8 +2735,8 @@ class FakeApi(object): _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. - _request_timeout (float/tuple): timeout setting for this request. If one - number provided, it will be total request timeout. It can also + _request_timeout (int/float/tuple): timeout setting for this request. If + one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking @@ -2852,8 +2852,8 @@ class FakeApi(object): _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. - _request_timeout (float/tuple): timeout setting for this request. If one - number provided, it will be total request timeout. It can also + _request_timeout (int/float/tuple): timeout setting for this request. If + one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking @@ -2985,8 +2985,8 @@ class FakeApi(object): _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. - _request_timeout (float/tuple): timeout setting for this request. If one - number provided, it will be total request timeout. It can also + _request_timeout (int/float/tuple): timeout setting for this request. If + one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking @@ -3136,8 +3136,8 @@ class FakeApi(object): _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. - _request_timeout (float/tuple): timeout setting for this request. If one - number provided, it will be total request timeout. It can also + _request_timeout (int/float/tuple): timeout setting for this request. If + one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking @@ -3254,8 +3254,8 @@ class FakeApi(object): _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. - _request_timeout (float/tuple): timeout setting for this request. If one - number provided, it will be total request timeout. It can also + _request_timeout (int/float/tuple): timeout setting for this request. If + one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking @@ -3375,8 +3375,8 @@ class FakeApi(object): _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. - _request_timeout (float/tuple): timeout setting for this request. If one - number provided, it will be total request timeout. It can also + _request_timeout (int/float/tuple): timeout setting for this request. If + one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking 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 index 6e20a712d6f..dd702d316bf 100644 --- 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 @@ -59,8 +59,8 @@ class FakeClassnameTags123Api(object): _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. - _request_timeout (float/tuple): timeout setting for this request. If one - number provided, it will be total request timeout. It can also + _request_timeout (int/float/tuple): timeout setting for this request. If + one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking 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 7b637be215b..102c1f26def 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/api/pet_api.py +++ b/samples/openapi3/client/petstore/python/petstore_api/api/pet_api.py @@ -58,8 +58,8 @@ class PetApi(object): _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. - _request_timeout (float/tuple): timeout setting for this request. If one - number provided, it will be total request timeout. It can also + _request_timeout (int/float/tuple): timeout setting for this request. If + one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking @@ -187,8 +187,8 @@ class PetApi(object): _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. - _request_timeout (float/tuple): timeout setting for this request. If one - number provided, it will be total request timeout. It can also + _request_timeout (int/float/tuple): timeout setting for this request. If + one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking @@ -309,8 +309,8 @@ class PetApi(object): _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. - _request_timeout (float/tuple): timeout setting for this request. If one - number provided, it will be total request timeout. It can also + _request_timeout (int/float/tuple): timeout setting for this request. If + one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking @@ -438,8 +438,8 @@ class PetApi(object): _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. - _request_timeout (float/tuple): timeout setting for this request. If one - number provided, it will be total request timeout. It can also + _request_timeout (int/float/tuple): timeout setting for this request. If + one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking @@ -560,8 +560,8 @@ class PetApi(object): _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. - _request_timeout (float/tuple): timeout setting for this request. If one - number provided, it will be total request timeout. It can also + _request_timeout (int/float/tuple): timeout setting for this request. If + one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking @@ -679,8 +679,8 @@ class PetApi(object): _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. - _request_timeout (float/tuple): timeout setting for this request. If one - number provided, it will be total request timeout. It can also + _request_timeout (int/float/tuple): timeout setting for this request. If + one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking @@ -809,8 +809,8 @@ class PetApi(object): _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. - _request_timeout (float/tuple): timeout setting for this request. If one - number provided, it will be total request timeout. It can also + _request_timeout (int/float/tuple): timeout setting for this request. If + one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking 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 efbf40c1607..aa701fc3b15 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/api/store_api.py +++ b/samples/openapi3/client/petstore/python/petstore_api/api/store_api.py @@ -59,8 +59,8 @@ class StoreApi(object): _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. - _request_timeout (float/tuple): timeout setting for this request. If one - number provided, it will be total request timeout. It can also + _request_timeout (int/float/tuple): timeout setting for this request. If + one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking @@ -171,8 +171,8 @@ class StoreApi(object): _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. - _request_timeout (float/tuple): timeout setting for this request. If one - number provided, it will be total request timeout. It can also + _request_timeout (int/float/tuple): timeout setting for this request. If + one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking @@ -281,8 +281,8 @@ class StoreApi(object): _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. - _request_timeout (float/tuple): timeout setting for this request. If one - number provided, it will be total request timeout. It can also + _request_timeout (int/float/tuple): timeout setting for this request. If + one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking @@ -404,8 +404,8 @@ class StoreApi(object): _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. - _request_timeout (float/tuple): timeout setting for this request. If one - number provided, it will be total request timeout. It can also + _request_timeout (int/float/tuple): timeout setting for this request. If + one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking 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 9af3abfd19f..8c8b26e26f6 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/api/user_api.py +++ b/samples/openapi3/client/petstore/python/petstore_api/api/user_api.py @@ -59,8 +59,8 @@ class UserApi(object): _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. - _request_timeout (float/tuple): timeout setting for this request. If one - number provided, it will be total request timeout. It can also + _request_timeout (int/float/tuple): timeout setting for this request. If + one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking @@ -174,8 +174,8 @@ class UserApi(object): _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. - _request_timeout (float/tuple): timeout setting for this request. If one - number provided, it will be total request timeout. It can also + _request_timeout (int/float/tuple): timeout setting for this request. If + one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking @@ -289,8 +289,8 @@ class UserApi(object): _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. - _request_timeout (float/tuple): timeout setting for this request. If one - number provided, it will be total request timeout. It can also + _request_timeout (int/float/tuple): timeout setting for this request. If + one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking @@ -405,8 +405,8 @@ class UserApi(object): _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. - _request_timeout (float/tuple): timeout setting for this request. If one - number provided, it will be total request timeout. It can also + _request_timeout (int/float/tuple): timeout setting for this request. If + one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking @@ -519,8 +519,8 @@ class UserApi(object): _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. - _request_timeout (float/tuple): timeout setting for this request. If one - number provided, it will be total request timeout. It can also + _request_timeout (int/float/tuple): timeout setting for this request. If + one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking @@ -638,8 +638,8 @@ class UserApi(object): _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. - _request_timeout (float/tuple): timeout setting for this request. If one - number provided, it will be total request timeout. It can also + _request_timeout (int/float/tuple): timeout setting for this request. If + one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking @@ -760,8 +760,8 @@ class UserApi(object): _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. - _request_timeout (float/tuple): timeout setting for this request. If one - number provided, it will be total request timeout. It can also + _request_timeout (int/float/tuple): timeout setting for this request. If + one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking @@ -868,8 +868,8 @@ class UserApi(object): _preload_content (bool): if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. - _request_timeout (float/tuple): timeout setting for this request. If one - number provided, it will be total request timeout. It can also + _request_timeout (int/float/tuple): timeout setting for this request. If + one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. Default is None. _check_input_type (bool): specifies if type checking 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 2c5f087123e..af5d8729ad3 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/api_client.py +++ b/samples/openapi3/client/petstore/python/petstore_api/api_client.py @@ -129,7 +129,7 @@ class ApiClient(object): _return_http_data_only: typing.Optional[bool] = None, collection_formats: typing.Optional[typing.Dict[str, str]] = None, _preload_content: bool = True, - _request_timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + _request_timeout: typing.Optional[typing.Union[int, float, typing.Tuple]] = None, _host: typing.Optional[str] = None, _check_type: typing.Optional[bool] = None ): @@ -347,7 +347,7 @@ class ApiClient(object): _return_http_data_only: typing.Optional[bool] = None, collection_formats: typing.Optional[typing.Dict[str, str]] = None, _preload_content: bool = True, - _request_timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, + _request_timeout: typing.Optional[typing.Union[int, float, typing.Tuple]] = None, _host: typing.Optional[str] = None, _check_type: typing.Optional[bool] = None ): @@ -681,7 +681,7 @@ class Endpoint(object): 'async_req': (bool,), '_host_index': (none_type, int), '_preload_content': (bool,), - '_request_timeout': (none_type, int, (int,), [int]), + '_request_timeout': (none_type, float, (float,), [float], int, (int,), [int]), '_return_http_data_only': (bool,), '_check_input_type': (bool,), '_check_return_type': (bool,) diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/fake_get_inline_additional_properties_payload_array_data.py b/samples/openapi3/client/petstore/python/petstore_api/model/fake_post_inline_additional_properties_payload_array_data.py similarity index 97% rename from samples/openapi3/client/petstore/python/petstore_api/model/fake_get_inline_additional_properties_payload_array_data.py rename to samples/openapi3/client/petstore/python/petstore_api/model/fake_post_inline_additional_properties_payload_array_data.py index 71b921c921f..bf9761b084c 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/fake_get_inline_additional_properties_payload_array_data.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/fake_post_inline_additional_properties_payload_array_data.py @@ -30,7 +30,7 @@ from petstore_api.exceptions import ApiAttributeError -class FakeGetInlineAdditionalPropertiesPayloadArrayData(ModelNormal): +class FakePostInlineAdditionalPropertiesPayloadArrayData(ModelNormal): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech @@ -101,7 +101,7 @@ class FakeGetInlineAdditionalPropertiesPayloadArrayData(ModelNormal): @classmethod @convert_js_args_to_python_args def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 - """FakeGetInlineAdditionalPropertiesPayloadArrayData - a model defined in OpenAPI + """FakePostInlineAdditionalPropertiesPayloadArrayData - a model defined in OpenAPI Keyword Args: _check_type (bool): if True, values for parameters in openapi_types @@ -183,7 +183,7 @@ class FakeGetInlineAdditionalPropertiesPayloadArrayData(ModelNormal): @convert_js_args_to_python_args def __init__(self, *args, **kwargs): # noqa: E501 - """FakeGetInlineAdditionalPropertiesPayloadArrayData - a model defined in OpenAPI + """FakePostInlineAdditionalPropertiesPayloadArrayData - a model defined in OpenAPI Keyword Args: _check_type (bool): if True, values for parameters in openapi_types diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/inline_additional_properties_ref_payload.py b/samples/openapi3/client/petstore/python/petstore_api/model/inline_additional_properties_ref_payload.py index 4ba519ea0af..85d3fa5922f 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/inline_additional_properties_ref_payload.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/inline_additional_properties_ref_payload.py @@ -30,8 +30,8 @@ from petstore_api.exceptions import ApiAttributeError def lazy_import(): - from petstore_api.model.fake_get_inline_additional_properties_payload_array_data import FakeGetInlineAdditionalPropertiesPayloadArrayData - globals()['FakeGetInlineAdditionalPropertiesPayloadArrayData'] = FakeGetInlineAdditionalPropertiesPayloadArrayData + from petstore_api.model.fake_post_inline_additional_properties_payload_array_data import FakePostInlineAdditionalPropertiesPayloadArrayData + globals()['FakePostInlineAdditionalPropertiesPayloadArrayData'] = FakePostInlineAdditionalPropertiesPayloadArrayData class InlineAdditionalPropertiesRefPayload(ModelNormal): @@ -87,7 +87,7 @@ class InlineAdditionalPropertiesRefPayload(ModelNormal): """ lazy_import() return { - 'array_data': ([FakeGetInlineAdditionalPropertiesPayloadArrayData], none_type,), # noqa: E501 + 'array_data': ([FakePostInlineAdditionalPropertiesPayloadArrayData], none_type,), # noqa: E501 } @cached_property @@ -140,7 +140,7 @@ class InlineAdditionalPropertiesRefPayload(ModelNormal): Animal class but this time we won't travel through its discriminator because we passed in _visited_composed_classes = (Animal,) - array_data ([FakeGetInlineAdditionalPropertiesPayloadArrayData], none_type): [optional] # noqa: E501 + array_data ([FakePostInlineAdditionalPropertiesPayloadArrayData], none_type): [optional] # noqa: E501 """ _check_type = kwargs.pop('_check_type', True) @@ -222,7 +222,7 @@ class InlineAdditionalPropertiesRefPayload(ModelNormal): Animal class but this time we won't travel through its discriminator because we passed in _visited_composed_classes = (Animal,) - array_data ([FakeGetInlineAdditionalPropertiesPayloadArrayData], none_type): [optional] # noqa: E501 + array_data ([FakePostInlineAdditionalPropertiesPayloadArrayData], none_type): [optional] # noqa: E501 """ _check_type = kwargs.pop('_check_type', True) diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/inline_object6.py b/samples/openapi3/client/petstore/python/petstore_api/model/inline_object6.py index dbbd376e125..828d30aa076 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/inline_object6.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/inline_object6.py @@ -30,8 +30,8 @@ from petstore_api.exceptions import ApiAttributeError def lazy_import(): - from petstore_api.model.fake_get_inline_additional_properties_payload_array_data import FakeGetInlineAdditionalPropertiesPayloadArrayData - globals()['FakeGetInlineAdditionalPropertiesPayloadArrayData'] = FakeGetInlineAdditionalPropertiesPayloadArrayData + from petstore_api.model.fake_post_inline_additional_properties_payload_array_data import FakePostInlineAdditionalPropertiesPayloadArrayData + globals()['FakePostInlineAdditionalPropertiesPayloadArrayData'] = FakePostInlineAdditionalPropertiesPayloadArrayData class InlineObject6(ModelNormal): @@ -87,7 +87,7 @@ class InlineObject6(ModelNormal): """ lazy_import() return { - 'array_data': ([FakeGetInlineAdditionalPropertiesPayloadArrayData], none_type,), # noqa: E501 + 'array_data': ([FakePostInlineAdditionalPropertiesPayloadArrayData], none_type,), # noqa: E501 } @cached_property @@ -140,7 +140,7 @@ class InlineObject6(ModelNormal): Animal class but this time we won't travel through its discriminator because we passed in _visited_composed_classes = (Animal,) - array_data ([FakeGetInlineAdditionalPropertiesPayloadArrayData], none_type): [optional] # noqa: E501 + array_data ([FakePostInlineAdditionalPropertiesPayloadArrayData], none_type): [optional] # noqa: E501 """ _check_type = kwargs.pop('_check_type', True) @@ -222,7 +222,7 @@ class InlineObject6(ModelNormal): Animal class but this time we won't travel through its discriminator because we passed in _visited_composed_classes = (Animal,) - array_data ([FakeGetInlineAdditionalPropertiesPayloadArrayData], none_type): [optional] # noqa: E501 + array_data ([FakePostInlineAdditionalPropertiesPayloadArrayData], none_type): [optional] # noqa: E501 """ _check_type = kwargs.pop('_check_type', True) diff --git a/samples/openapi3/client/petstore/python/petstore_api/model_utils.py b/samples/openapi3/client/petstore/python/petstore_api/model_utils.py index 3913228d6b8..aa747a3f9a8 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model_utils.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model_utils.py @@ -47,7 +47,7 @@ def convert_js_args_to_python_args(fn): class cached_property(object): # this caches the result of the function call for fn with no inputs - # use this as a decorator on fuction methods that you want converted + # use this as a decorator on function methods that you want converted # into cached properties result_key = '_results' @@ -1632,12 +1632,20 @@ def model_to_dict(model_instance, serialize=True): model_instances = [model_instance] if model_instance._composed_schemas: model_instances.extend(model_instance._composed_instances) + seen_json_attribute_names = set() + used_fallback_python_attribute_names = set() + py_to_json_map = {} for model_instance in model_instances: for attr, value in model_instance._data_store.items(): if serialize: # we use get here because additional property key names do not # exist in attribute_map - attr = model_instance.attribute_map.get(attr, attr) + try: + attr = model_instance.attribute_map[attr] + py_to_json_map.update(model_instance.attribute_map) + seen_json_attribute_names.add(attr) + except KeyError: + used_fallback_python_attribute_names.add(attr) if isinstance(value, list): if not value: # empty list or None @@ -1665,6 +1673,16 @@ def model_to_dict(model_instance, serialize=True): result[attr] = model_to_dict(value, serialize=serialize) else: result[attr] = value + if serialize: + for python_key in used_fallback_python_attribute_names: + json_key = py_to_json_map.get(python_key) + if json_key is None: + continue + if python_key == json_key: + continue + json_key_assigned_no_need_for_python_key = json_key in seen_json_attribute_names + if json_key_assigned_no_need_for_python_key: + del result[python_key] return result 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 f18e33defce..9485a03d2f8 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/__init__.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/__init__.py @@ -43,7 +43,7 @@ from petstore_api.model.enum_arrays import EnumArrays from petstore_api.model.enum_class import EnumClass from petstore_api.model.enum_test import EnumTest from petstore_api.model.equilateral_triangle import EquilateralTriangle -from petstore_api.model.fake_get_inline_additional_properties_payload_array_data import FakeGetInlineAdditionalPropertiesPayloadArrayData +from petstore_api.model.fake_post_inline_additional_properties_payload_array_data import FakePostInlineAdditionalPropertiesPayloadArrayData from petstore_api.model.file import File from petstore_api.model.file_schema_test_class import FileSchemaTestClass from petstore_api.model.foo import Foo diff --git a/samples/openapi3/client/petstore/python/petstore_api/rest.py b/samples/openapi3/client/petstore/python/petstore_api/rest.py index a1d580fbe05..a38fcec1c84 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/rest.py +++ b/samples/openapi3/client/petstore/python/petstore_api/rest.py @@ -137,15 +137,15 @@ class RESTClientObject(object): timeout = urllib3.Timeout( connect=_request_timeout[0], read=_request_timeout[1]) - if 'Content-Type' not in headers: - headers['Content-Type'] = 'application/json' - try: # For `POST`, `PUT`, `PATCH`, `OPTIONS`, `DELETE` if method in ['POST', 'PUT', 'PATCH', 'OPTIONS', 'DELETE']: + # Only set a default Content-Type for POST, PUT, PATCH and OPTIONS requests + if (method != 'DELETE') and ('Content-Type' not in headers): + headers['Content-Type'] = 'application/json' if query_params: url += '?' + urlencode(query_params) - if re.search('json', headers['Content-Type'], re.IGNORECASE): + if ('Content-Type' not in headers) or (re.search('json', headers['Content-Type'], re.IGNORECASE)): request_body = None if body is not None: request_body = json.dumps(body) diff --git a/samples/openapi3/client/petstore/python/test/test_fake_get_inline_additional_properties_payload_array_data.py b/samples/openapi3/client/petstore/python/test/test_fake_post_inline_additional_properties_payload_array_data.py similarity index 52% rename from samples/openapi3/client/petstore/python/test/test_fake_get_inline_additional_properties_payload_array_data.py rename to samples/openapi3/client/petstore/python/test/test_fake_post_inline_additional_properties_payload_array_data.py index 2e95eb37dff..6b4be44e865 100644 --- a/samples/openapi3/client/petstore/python/test/test_fake_get_inline_additional_properties_payload_array_data.py +++ b/samples/openapi3/client/petstore/python/test/test_fake_post_inline_additional_properties_payload_array_data.py @@ -12,11 +12,11 @@ import sys import unittest import petstore_api -from petstore_api.model.fake_get_inline_additional_properties_payload_array_data import FakeGetInlineAdditionalPropertiesPayloadArrayData +from petstore_api.model.fake_post_inline_additional_properties_payload_array_data import FakePostInlineAdditionalPropertiesPayloadArrayData -class TestFakeGetInlineAdditionalPropertiesPayloadArrayData(unittest.TestCase): - """FakeGetInlineAdditionalPropertiesPayloadArrayData unit test stubs""" +class TestFakePostInlineAdditionalPropertiesPayloadArrayData(unittest.TestCase): + """FakePostInlineAdditionalPropertiesPayloadArrayData unit test stubs""" def setUp(self): pass @@ -24,10 +24,10 @@ class TestFakeGetInlineAdditionalPropertiesPayloadArrayData(unittest.TestCase): def tearDown(self): pass - def testFakeGetInlineAdditionalPropertiesPayloadArrayData(self): - """Test FakeGetInlineAdditionalPropertiesPayloadArrayData""" + def testFakePostInlineAdditionalPropertiesPayloadArrayData(self): + """Test FakePostInlineAdditionalPropertiesPayloadArrayData""" # FIXME: construct object with mandatory attributes with example values - # model = FakeGetInlineAdditionalPropertiesPayloadArrayData() # noqa: E501 + # model = FakePostInlineAdditionalPropertiesPayloadArrayData() # noqa: E501 pass diff --git a/samples/openapi3/client/petstore/python/test/test_inline_additional_properties_ref_payload.py b/samples/openapi3/client/petstore/python/test/test_inline_additional_properties_ref_payload.py index 709ee27adc8..7e8cf543335 100644 --- a/samples/openapi3/client/petstore/python/test/test_inline_additional_properties_ref_payload.py +++ b/samples/openapi3/client/petstore/python/test/test_inline_additional_properties_ref_payload.py @@ -12,8 +12,8 @@ import sys import unittest import petstore_api -from petstore_api.model.fake_get_inline_additional_properties_payload_array_data import FakeGetInlineAdditionalPropertiesPayloadArrayData -globals()['FakeGetInlineAdditionalPropertiesPayloadArrayData'] = FakeGetInlineAdditionalPropertiesPayloadArrayData +from petstore_api.model.fake_post_inline_additional_properties_payload_array_data import FakePostInlineAdditionalPropertiesPayloadArrayData +globals()['FakePostInlineAdditionalPropertiesPayloadArrayData'] = FakePostInlineAdditionalPropertiesPayloadArrayData from petstore_api.model.inline_additional_properties_ref_payload import InlineAdditionalPropertiesRefPayload diff --git a/samples/openapi3/client/petstore/python/test/test_inline_object6.py b/samples/openapi3/client/petstore/python/test/test_inline_object6.py index 463123d8e55..887e5689b9a 100644 --- a/samples/openapi3/client/petstore/python/test/test_inline_object6.py +++ b/samples/openapi3/client/petstore/python/test/test_inline_object6.py @@ -12,8 +12,8 @@ import sys import unittest import petstore_api -from petstore_api.model.fake_get_inline_additional_properties_payload_array_data import FakeGetInlineAdditionalPropertiesPayloadArrayData -globals()['FakeGetInlineAdditionalPropertiesPayloadArrayData'] = FakeGetInlineAdditionalPropertiesPayloadArrayData +from petstore_api.model.fake_post_inline_additional_properties_payload_array_data import FakePostInlineAdditionalPropertiesPayloadArrayData +globals()['FakePostInlineAdditionalPropertiesPayloadArrayData'] = FakePostInlineAdditionalPropertiesPayloadArrayData from petstore_api.model.inline_object6 import InlineObject6 diff --git a/samples/openapi3/client/petstore/python/tests_manual/test_fake_api.py b/samples/openapi3/client/petstore/python/tests_manual/test_fake_api.py index 8c0886e373b..954f1ce8e5c 100644 --- a/samples/openapi3/client/petstore/python/tests_manual/test_fake_api.py +++ b/samples/openapi3/client/petstore/python/tests_manual/test_fake_api.py @@ -19,7 +19,7 @@ from unittest.mock import patch import petstore_api from petstore_api.api.fake_api import FakeApi # noqa: E501 from petstore_api.rest import RESTClientObject, RESTResponse -from petstore_api.model_utils import file_type +from petstore_api.model_utils import file_type, model_to_dict HTTPResponse = namedtuple( 'urllib3_response_HTTPResponse', @@ -59,14 +59,15 @@ class TestFakeApi(unittest.TestCase): url, accept='application/json', http_method='POST', + content_type='application/json', **kwargs ): headers = { 'Accept': accept, 'User-Agent': 'OpenAPI-Generator/1.0.0/python', } - if 'content_type' in kwargs: - headers['Content-Type'] = kwargs['content_type'] + if content_type: + headers['Content-Type'] = content_type used_kwargs = dict( _preload_content=True, _request_timeout=None, @@ -77,12 +78,13 @@ class TestFakeApi(unittest.TestCase): used_kwargs['post_params'] = kwargs['post_params'] if 'body' in kwargs: used_kwargs['body'] = kwargs['body'] - else: - mock_method.assert_called_with( - http_method, - url, - **used_kwargs - ) + if 'post_params' not in used_kwargs: + used_kwargs['post_params'] = [] + mock_method.assert_called_with( + http_method, + url, + **used_kwargs + ) def test_array_model(self): """Test case for array_model @@ -101,7 +103,11 @@ class TestFakeApi(unittest.TestCase): mock_method.return_value = self.mock_response(json_data) response = endpoint(body=body) - self.assert_request_called_with(mock_method, 'http://petstore.swagger.io:80/v2/fake/refs/arraymodel', body=json_data) + self.assert_request_called_with( + mock_method, + 'http://petstore.swagger.io:80/v2/fake/refs/arraymodel', + body=json_data, + ) assert isinstance(response, animal_farm.AnimalFarm) assert response == body @@ -158,7 +164,10 @@ class TestFakeApi(unittest.TestCase): response = endpoint(enum_test=body) self.assert_request_called_with( - mock_method, 'http://petstore.swagger.io:80/v2/fake/refs/enum-test', body=json_value) + mock_method, + 'http://petstore.swagger.io:80/v2/fake/refs/enum-test', + body=json_value, + ) assert isinstance(response, EnumTest) assert response == body @@ -174,7 +183,10 @@ class TestFakeApi(unittest.TestCase): response = endpoint(enum_test=body) self.assert_request_called_with( - mock_method, 'http://petstore.swagger.io:80/v2/fake/refs/enum-test', body=json_value) + mock_method, + 'http://petstore.swagger.io:80/v2/fake/refs/enum-test', + body=json_value, + ) assert isinstance(response, EnumTest) assert response == body @@ -198,7 +210,11 @@ class TestFakeApi(unittest.TestCase): mock_method.return_value = self.mock_response(value_simple) response = endpoint(array_of_enums=body) - self.assert_request_called_with(mock_method, 'http://petstore.swagger.io:80/v2/fake/refs/array-of-enums', body=value_simple) + self.assert_request_called_with( + mock_method, + 'http://petstore.swagger.io:80/v2/fake/refs/array-of-enums', + body=value_simple, + ) assert isinstance(response, array_of_enums.ArrayOfEnums) assert response.value == value @@ -219,7 +235,11 @@ class TestFakeApi(unittest.TestCase): mock_method.return_value = self.mock_response(value) response = endpoint(body=body) - self.assert_request_called_with(mock_method, 'http://petstore.swagger.io:80/v2/fake/refs/number', body=value) + self.assert_request_called_with( + mock_method, + 'http://petstore.swagger.io:80/v2/fake/refs/number', + body=value, + ) assert isinstance(response, number_with_validations.NumberWithValidations) assert response.value == value @@ -262,7 +282,7 @@ class TestFakeApi(unittest.TestCase): self.assert_request_called_with( mock_method, 'http://petstore.swagger.io:80/v2/fake/refs/object_model_with_ref_props', - body=json_payload + body=json_payload, ) assert isinstance(response, expected_model.__class__) @@ -300,7 +320,7 @@ class TestFakeApi(unittest.TestCase): self.assert_request_called_with( mock_method, 'http://petstore.swagger.io:80/v2/fake/refs/composed_one_of_number_with_validations', - body=value_simple + body=value_simple, ) assert isinstance(response, body.__class__) @@ -321,7 +341,11 @@ class TestFakeApi(unittest.TestCase): mock_method.return_value = self.mock_response(value_simple) response = endpoint(body=body) - self.assert_request_called_with(mock_method, 'http://petstore.swagger.io:80/v2/fake/refs/string', body=value_simple) + self.assert_request_called_with( + mock_method, + 'http://petstore.swagger.io:80/v2/fake/refs/string', + body=value_simple, + ) assert isinstance(response, str) assert response == value_simple @@ -343,7 +367,11 @@ class TestFakeApi(unittest.TestCase): mock_method.return_value = self.mock_response(value) response = endpoint(body=body) - self.assert_request_called_with(mock_method, 'http://petstore.swagger.io:80/v2/fake/refs/enum', body=value) + self.assert_request_called_with( + mock_method, + 'http://petstore.swagger.io:80/v2/fake/refs/enum', + body=value, + ) assert isinstance(response, string_enum.StringEnum) assert response.value == value @@ -495,6 +523,7 @@ class TestFakeApi(unittest.TestCase): 'http://www.jtricks.com/download-text', http_method='GET', accept='text/plain', + content_type=None, ) self.assertTrue(isinstance(file_object, file_type)) self.assertFalse(file_object.closed) @@ -532,8 +561,11 @@ class TestFakeApi(unittest.TestCase): self.assert_request_called_with( mock_method, 'http://petstore.swagger.io:80/v2/fake/uploadDownloadFile', - body=expected_file_data, content_type='application/octet-stream' + body=expected_file_data, + content_type='application/octet-stream', + accept='application/octet-stream' ) + self.assertTrue(isinstance(downloaded_file, file_type)) self.assertFalse(downloaded_file.closed) self.assertEqual(downloaded_file.read(), expected_file_data) @@ -604,12 +636,12 @@ class TestFakeApi(unittest.TestCase): """ pass - def test_get_inline_additional_properties_ref_payload(self): - """Test case for getInlineAdditionlPropertiesRefPayload + def test_post_inline_additional_properties_ref_payload(self): + """Test case for postInlineAdditionlPropertiesRefPayload """ from petstore_api.model.inline_additional_properties_ref_payload import InlineAdditionalPropertiesRefPayload - from petstore_api.model.fake_get_inline_additional_properties_payload_array_data import FakeGetInlineAdditionalPropertiesPayloadArrayData - endpoint = self.api.get_inline_additional_properties_ref_payload + from petstore_api.model.fake_post_inline_additional_properties_payload_array_data import FakePostInlineAdditionalPropertiesPayloadArrayData + endpoint = self.api.post_inline_additional_properties_ref_payload assert endpoint.openapi_types['inline_additional_properties_ref_payload'] == (InlineAdditionalPropertiesRefPayload,) assert endpoint.settings['response_type'] == (InlineAdditionalPropertiesRefPayload,) @@ -617,7 +649,7 @@ class TestFakeApi(unittest.TestCase): from petstore_api.rest import RESTClientObject, RESTResponse with patch.object(RESTClientObject, 'request') as mock_method: expected_json_body = { - 'array_data': [ + 'arrayData': [ { 'labels': [ None, @@ -628,23 +660,27 @@ class TestFakeApi(unittest.TestCase): } inline_additional_properties_ref_payload = InlineAdditionalPropertiesRefPayload( array_data=[ - FakeGetInlineAdditionalPropertiesPayloadArrayData(labels=[None, 'foo']) + FakePostInlineAdditionalPropertiesPayloadArrayData(labels=[None, 'foo']) ] ) mock_method.return_value = self.mock_response(expected_json_body) response = endpoint(inline_additional_properties_ref_payload=inline_additional_properties_ref_payload) - self.assert_request_called_with(mock_method, 'http://petstore.swagger.io:80/v2/fake/refs/enum', body=expected_json_body) + self.assert_request_called_with( + mock_method, + 'http://petstore.swagger.io:80/v2/fake/postInlineAdditionalPropertiesRefPayload', + body=expected_json_body + ) assert isinstance(response, InlineAdditionalPropertiesRefPayload) - assert response.to_dict() == expected_json_body + assert model_to_dict(response) == expected_json_body - def test_get_inline_additional_properties_payload(self): - """Test case for getInlineAdditionlPropertiesPayload + def test_post_inline_additional_properties_payload(self): + """Test case for postInlineAdditionlPropertiesPayload """ from petstore_api.model.inline_object6 import InlineObject6 - from petstore_api.model.fake_get_inline_additional_properties_payload_array_data import FakeGetInlineAdditionalPropertiesPayloadArrayData - endpoint = self.api.get_inline_additional_properties_payload + from petstore_api.model.fake_post_inline_additional_properties_payload_array_data import FakePostInlineAdditionalPropertiesPayloadArrayData + endpoint = self.api.post_inline_additional_properties_payload assert endpoint.openapi_types['inline_object6'] == (InlineObject6,) assert endpoint.settings['response_type'] == (InlineObject6,) @@ -652,7 +688,7 @@ class TestFakeApi(unittest.TestCase): from petstore_api.rest import RESTClientObject, RESTResponse with patch.object(RESTClientObject, 'request') as mock_method: expected_json_body = { - 'array_data': [ + 'arrayData': [ { 'labels': [ None, @@ -663,16 +699,20 @@ class TestFakeApi(unittest.TestCase): } inline_object6 = InlineObject6( array_data=[ - FakeGetInlineAdditionalPropertiesPayloadArrayData(labels=[None, 'foo']) + FakePostInlineAdditionalPropertiesPayloadArrayData(labels=[None, 'foo']) ] ) mock_method.return_value = self.mock_response(expected_json_body) response = endpoint(inline_object6=inline_object6) - self.assert_request_called_with(mock_method, 'http://petstore.swagger.io:80/v2/fake/refs/enum', body=expected_json_body) + self.assert_request_called_with( + mock_method, + 'http://petstore.swagger.io:80/v2/fake/postInlineAdditionalPropertiesPayload', + body=expected_json_body + ) assert isinstance(response, InlineObject6) - assert response.to_dict() == expected_json_body + assert model_to_dict(response) == expected_json_body if __name__ == '__main__': unittest.main() 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 5f68295fc19..e8415097f3a 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,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/openapi3/client/petstore/typescript/builds/default/auth/auth.ts b/samples/openapi3/client/petstore/typescript/builds/default/auth/auth.ts index 9d59a0a2558..1f1d1ecac67 100644 --- a/samples/openapi3/client/petstore/typescript/builds/default/auth/auth.ts +++ b/samples/openapi3/client/petstore/typescript/builds/default/auth/auth.ts @@ -48,15 +48,19 @@ export class ApiKeyAuthentication implements SecurityAuthentication { * Applies oauth2 authentication to the request context. */ export class PetstoreAuthAuthentication implements SecurityAuthentication { - // TODO: How to handle oauth2 authentication! - public constructor() {} + /** + * Configures OAuth2 with the necessary properties + * + * @param accessToken: The access token to be used for every request + */ + public constructor(private accessToken: string) {} public getName(): string { return "petstore_auth"; } public applySecurityAuthentication(context: RequestContext) { - // TODO + context.setHeaderParam("Authorization", "Bearer " + this.accessToken); } } @@ -69,7 +73,7 @@ export type AuthMethods = { export type ApiKeyConfiguration = string; export type HttpBasicConfiguration = { "username": string, "password": string }; export type HttpBearerConfiguration = { tokenProvider: TokenProvider }; -export type OAuth2Configuration = string; +export type OAuth2Configuration = { accessToken: string }; export type AuthMethodsConfiguration = { "api_key"?: ApiKeyConfiguration, @@ -95,6 +99,7 @@ export function configureAuthMethods(config: AuthMethodsConfiguration | undefine if (config["petstore_auth"]) { authMethods["petstore_auth"] = new PetstoreAuthAuthentication( + config["petstore_auth"]["accessToken"] ); } 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 5f68295fc19..e8415097f3a 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,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/openapi3/client/petstore/typescript/builds/deno/auth/auth.ts b/samples/openapi3/client/petstore/typescript/builds/deno/auth/auth.ts index 0a02d2e58d2..e7609dabbec 100644 --- a/samples/openapi3/client/petstore/typescript/builds/deno/auth/auth.ts +++ b/samples/openapi3/client/petstore/typescript/builds/deno/auth/auth.ts @@ -46,15 +46,19 @@ export class ApiKeyAuthentication implements SecurityAuthentication { * Applies oauth2 authentication to the request context. */ export class PetstoreAuthAuthentication implements SecurityAuthentication { - // TODO: How to handle oauth2 authentication! - public constructor() {} + /** + * Configures OAuth2 with the necessary properties + * + * @param accessToken: The access token to be used for every request + */ + public constructor(private accessToken: string) {} public getName(): string { return "petstore_auth"; } public applySecurityAuthentication(context: RequestContext) { - // TODO + context.setHeaderParam("Authorization", "Bearer " + this.accessToken); } } @@ -67,7 +71,7 @@ export type AuthMethods = { export type ApiKeyConfiguration = string; export type HttpBasicConfiguration = { "username": string, "password": string }; export type HttpBearerConfiguration = { tokenProvider: TokenProvider }; -export type OAuth2Configuration = string; +export type OAuth2Configuration = { accessToken: string }; export type AuthMethodsConfiguration = { "api_key"?: ApiKeyConfiguration, @@ -93,6 +97,7 @@ export function configureAuthMethods(config: AuthMethodsConfiguration | undefine if (config["petstore_auth"]) { authMethods["petstore_auth"] = new PetstoreAuthAuthentication( + config["petstore_auth"]["accessToken"] ); } 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 5f68295fc19..e8415097f3a 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,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/openapi3/client/petstore/typescript/builds/inversify/auth/auth.ts b/samples/openapi3/client/petstore/typescript/builds/inversify/auth/auth.ts index 13e3b17fa82..f6ffebc4d7e 100644 --- a/samples/openapi3/client/petstore/typescript/builds/inversify/auth/auth.ts +++ b/samples/openapi3/client/petstore/typescript/builds/inversify/auth/auth.ts @@ -56,15 +56,19 @@ export class ApiKeyAuthentication implements SecurityAuthentication { */ @injectable() export class PetstoreAuthAuthentication implements SecurityAuthentication { - // TODO: How to handle oauth2 authentication! - public constructor() {} + /** + * Configures OAuth2 with the necessary properties + * + * @param accessToken: The access token to be used for every request + */ + public constructor(private accessToken: string) {} public getName(): string { return "petstore_auth"; } public applySecurityAuthentication(context: RequestContext) { - // TODO + context.setHeaderParam("Authorization", "Bearer " + this.accessToken); } } @@ -82,7 +86,7 @@ export const authMethodServices = { export type ApiKeyConfiguration = string; export type HttpBasicConfiguration = { "username": string, "password": string }; export type HttpBearerConfiguration = { tokenProvider: TokenProvider }; -export type OAuth2Configuration = string; +export type OAuth2Configuration = { accessToken: string }; export type AuthMethodsConfiguration = { "api_key"?: ApiKeyConfiguration, @@ -108,6 +112,7 @@ export function configureAuthMethods(config: AuthMethodsConfiguration | undefine if (config["petstore_auth"]) { authMethods["petstore_auth"] = new PetstoreAuthAuthentication( + config["petstore_auth"]["accessToken"] ); } 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 5f68295fc19..e8415097f3a 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,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/openapi3/client/petstore/typescript/builds/jquery/auth/auth.ts b/samples/openapi3/client/petstore/typescript/builds/jquery/auth/auth.ts index 2cdf0800f32..d8924a4216c 100644 --- a/samples/openapi3/client/petstore/typescript/builds/jquery/auth/auth.ts +++ b/samples/openapi3/client/petstore/typescript/builds/jquery/auth/auth.ts @@ -46,15 +46,19 @@ export class ApiKeyAuthentication implements SecurityAuthentication { * Applies oauth2 authentication to the request context. */ export class PetstoreAuthAuthentication implements SecurityAuthentication { - // TODO: How to handle oauth2 authentication! - public constructor() {} + /** + * Configures OAuth2 with the necessary properties + * + * @param accessToken: The access token to be used for every request + */ + public constructor(private accessToken: string) {} public getName(): string { return "petstore_auth"; } public applySecurityAuthentication(context: RequestContext) { - // TODO + context.setHeaderParam("Authorization", "Bearer " + this.accessToken); } } @@ -67,7 +71,7 @@ export type AuthMethods = { export type ApiKeyConfiguration = string; export type HttpBasicConfiguration = { "username": string, "password": string }; export type HttpBearerConfiguration = { tokenProvider: TokenProvider }; -export type OAuth2Configuration = string; +export type OAuth2Configuration = { accessToken: string }; export type AuthMethodsConfiguration = { "api_key"?: ApiKeyConfiguration, @@ -93,6 +97,7 @@ export function configureAuthMethods(config: AuthMethodsConfiguration | undefine if (config["petstore_auth"]) { authMethods["petstore_auth"] = new PetstoreAuthAuthentication( + config["petstore_auth"]["accessToken"] ); } 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 5f68295fc19..e8415097f3a 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,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/openapi3/client/petstore/typescript/builds/object_params/auth/auth.ts b/samples/openapi3/client/petstore/typescript/builds/object_params/auth/auth.ts index 9d59a0a2558..1f1d1ecac67 100644 --- a/samples/openapi3/client/petstore/typescript/builds/object_params/auth/auth.ts +++ b/samples/openapi3/client/petstore/typescript/builds/object_params/auth/auth.ts @@ -48,15 +48,19 @@ export class ApiKeyAuthentication implements SecurityAuthentication { * Applies oauth2 authentication to the request context. */ export class PetstoreAuthAuthentication implements SecurityAuthentication { - // TODO: How to handle oauth2 authentication! - public constructor() {} + /** + * Configures OAuth2 with the necessary properties + * + * @param accessToken: The access token to be used for every request + */ + public constructor(private accessToken: string) {} public getName(): string { return "petstore_auth"; } public applySecurityAuthentication(context: RequestContext) { - // TODO + context.setHeaderParam("Authorization", "Bearer " + this.accessToken); } } @@ -69,7 +73,7 @@ export type AuthMethods = { export type ApiKeyConfiguration = string; export type HttpBasicConfiguration = { "username": string, "password": string }; export type HttpBearerConfiguration = { tokenProvider: TokenProvider }; -export type OAuth2Configuration = string; +export type OAuth2Configuration = { accessToken: string }; export type AuthMethodsConfiguration = { "api_key"?: ApiKeyConfiguration, @@ -95,6 +99,7 @@ export function configureAuthMethods(config: AuthMethodsConfiguration | undefine if (config["petstore_auth"]) { authMethods["petstore_auth"] = new PetstoreAuthAuthentication( + config["petstore_auth"]["accessToken"] ); } diff --git a/samples/openapi3/server/petstore/php-mezzio-ph/.openapi-generator/FILES b/samples/openapi3/server/petstore/php-mezzio-ph/.openapi-generator/FILES deleted file mode 100644 index fd268242a0e..00000000000 --- a/samples/openapi3/server/petstore/php-mezzio-ph/.openapi-generator/FILES +++ /dev/null @@ -1,36 +0,0 @@ -.gitignore -README.md -application/config.yml -application/config/app.yml -application/config/data_transfer.yml -application/config/path_handler.yml -application/container.php -composer.json -public/index.php -src/App/DTO/ApiResponse.php -src/App/DTO/Category.php -src/App/DTO/FindPetsByStatusQueryData.php -src/App/DTO/FindPetsByTagsQueryData.php -src/App/DTO/InlineObject.php -src/App/DTO/InlineObject1.php -src/App/DTO/LoginUserQueryData.php -src/App/DTO/Order.php -src/App/DTO/Pet.php -src/App/DTO/Tag.php -src/App/DTO/User.php -src/App/Factory.php -src/App/Handler/Pet.php -src/App/Handler/PetFindByStatus.php -src/App/Handler/PetFindByTags.php -src/App/Handler/PetPetId.php -src/App/Handler/PetPetIdUploadImage.php -src/App/Handler/StoreInventory.php -src/App/Handler/StoreOrder.php -src/App/Handler/StoreOrderOrderId.php -src/App/Handler/User.php -src/App/Handler/UserCreateWithArray.php -src/App/Handler/UserCreateWithList.php -src/App/Handler/UserLogin.php -src/App/Handler/UserLogout.php -src/App/Handler/UserUsername.php -src/App/Middleware/InternalServerError.php diff --git a/samples/openapi3/server/petstore/php-mezzio-ph/.openapi-generator/VERSION b/samples/openapi3/server/petstore/php-mezzio-ph/.openapi-generator/VERSION deleted file mode 100644 index d99e7162d01..00000000000 --- a/samples/openapi3/server/petstore/php-mezzio-ph/.openapi-generator/VERSION +++ /dev/null @@ -1 +0,0 @@ -5.0.0-SNAPSHOT \ No newline at end of file diff --git a/samples/openapi3/server/petstore/php-mezzio-ph/composer.json b/samples/openapi3/server/petstore/php-mezzio-ph/composer.json deleted file mode 100644 index 54f8e97226c..00000000000 --- a/samples/openapi3/server/petstore/php-mezzio-ph/composer.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "name": "git_user_id/git_repo_id", - "description": "", - "license": "unlicense", - "version": "1.0.0", - "type": "project", - "require": { - "php": "^7.2", - "ext-yaml": "^2.0", - "mezzio/mezzio": "^3.2", - "laminas/laminas-diactoros": "^2.1", - "articus/path-handler": "^0.6", - "articus/data-transfer": "^0.4", - "articus/openapi-generator-common": "^0.1", - "doctrine/annotations": "^1.10", - "psr/simple-cache": "^1.0", - "laminas/laminas-config": "^3.4", - "laminas/laminas-stdlib": "^3.2", - "laminas/laminas-validator": "^2.13", - "nikic/fast-route": "^1.3" - }, - "autoload": { - "psr-4": { - "": "src/" - } - } -} \ No newline at end of file diff --git a/samples/openapi3/server/petstore/php-mezzio-ph/src/App/DTO/ApiResponse.php b/samples/openapi3/server/petstore/php-mezzio-ph/src/App/DTO/ApiResponse.php deleted file mode 100644 index a08cb2c9275..00000000000 --- a/samples/openapi3/server/petstore/php-mezzio-ph/src/App/DTO/ApiResponse.php +++ /dev/null @@ -1,31 +0,0 @@ -getAttribute("bodyData"); - throw new PHException\HttpCode(501, "Not implemented"); - } - /** - * Update an existing pet - * @PHA\Put() - * TODO check if consumer is valid, if it has correct priority and if it can be moved to class annotation - * @PHA\Consumer(name=PHConsumer\Json::class, mediaRange="application/json") - * TODO check if consumer is valid, if it has correct priority and if it can be moved to class annotation - * @PHA\Consumer(name=PHConsumer\Json::class, mediaRange="application/xml") - * @PHA\Attribute(name=PHAttribute\Transfer::class, options={"type":\App\DTO\Pet::class,"objectAttr":"bodyData"}) - * TODO check if producer is valid, if it has correct priority and if it can be moved to class annotation - * @PHA\Producer(name=PHProducer\Transfer::class, mediaType="application/xml") - * TODO check if producer is valid, if it has correct priority and if it can be moved to class annotation - * @PHA\Producer(name=PHProducer\Transfer::class, mediaType="application/json") - * @param ServerRequestInterface $request - * - * @throws PHException\HttpCode 501 if the method is not implemented - * - * @return \App\DTO\Pet - */ - public function updatePet(ServerRequestInterface $request): \App\DTO\Pet - { - //TODO implement method - /** @var \App\DTO\Pet $bodyData */ - $bodyData = $request->getAttribute("bodyData"); - throw new PHException\HttpCode(501, "Not implemented"); - } -} diff --git a/samples/openapi3/server/petstore/php-mezzio-ph/src/App/Handler/PetFindByStatus.php b/samples/openapi3/server/petstore/php-mezzio-ph/src/App/Handler/PetFindByStatus.php deleted file mode 100644 index c1c1ce75400..00000000000 --- a/samples/openapi3/server/petstore/php-mezzio-ph/src/App/Handler/PetFindByStatus.php +++ /dev/null @@ -1,44 +0,0 @@ -getAttribute("queryData"); - throw new PHException\HttpCode(501, "Not implemented"); - } -} diff --git a/samples/openapi3/server/petstore/php-mezzio-ph/src/App/Handler/PetFindByTags.php b/samples/openapi3/server/petstore/php-mezzio-ph/src/App/Handler/PetFindByTags.php deleted file mode 100644 index b722a310efb..00000000000 --- a/samples/openapi3/server/petstore/php-mezzio-ph/src/App/Handler/PetFindByTags.php +++ /dev/null @@ -1,44 +0,0 @@ -getAttribute("queryData"); - throw new PHException\HttpCode(501, "Not implemented"); - } -} diff --git a/samples/openapi3/server/petstore/php-mezzio-ph/src/App/Handler/StoreOrder.php b/samples/openapi3/server/petstore/php-mezzio-ph/src/App/Handler/StoreOrder.php deleted file mode 100644 index be6af69243a..00000000000 --- a/samples/openapi3/server/petstore/php-mezzio-ph/src/App/Handler/StoreOrder.php +++ /dev/null @@ -1,41 +0,0 @@ -getAttribute("bodyData"); - throw new PHException\HttpCode(501, "Not implemented"); - } -} diff --git a/samples/openapi3/server/petstore/php-mezzio-ph/src/App/Handler/UserLogin.php b/samples/openapi3/server/petstore/php-mezzio-ph/src/App/Handler/UserLogin.php deleted file mode 100644 index 577e7c3f562..00000000000 --- a/samples/openapi3/server/petstore/php-mezzio-ph/src/App/Handler/UserLogin.php +++ /dev/null @@ -1,43 +0,0 @@ -getAttribute("queryData"); - throw new PHException\HttpCode(501, "Not implemented"); - } -} diff --git a/samples/schema/petstore/ktorm/.openapi-generator/VERSION b/samples/schema/petstore/ktorm/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/schema/petstore/ktorm/.openapi-generator/VERSION +++ b/samples/schema/petstore/ktorm/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/schema/petstore/mysql/.openapi-generator/VERSION b/samples/schema/petstore/mysql/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/schema/petstore/mysql/.openapi-generator/VERSION +++ b/samples/schema/petstore/mysql/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/schema/petstore/wsdl-schema/.openapi-generator-ignore b/samples/schema/petstore/wsdl-schema/.openapi-generator-ignore new file mode 100644 index 00000000000..7484ee590a3 --- /dev/null +++ b/samples/schema/petstore/wsdl-schema/.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/schema/petstore/wsdl-schema/.openapi-generator/FILES b/samples/schema/petstore/wsdl-schema/.openapi-generator/FILES new file mode 100644 index 00000000000..94285c6e2aa --- /dev/null +++ b/samples/schema/petstore/wsdl-schema/.openapi-generator/FILES @@ -0,0 +1,2 @@ +jaxb-customization.xml +service.wsdl diff --git a/samples/schema/petstore/wsdl-schema/.openapi-generator/VERSION b/samples/schema/petstore/wsdl-schema/.openapi-generator/VERSION new file mode 100644 index 00000000000..4b448de535c --- /dev/null +++ b/samples/schema/petstore/wsdl-schema/.openapi-generator/VERSION @@ -0,0 +1 @@ +5.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/schema/petstore/wsdl-schema/jaxb-customization.xml b/samples/schema/petstore/wsdl-schema/jaxb-customization.xml new file mode 100644 index 00000000000..0ae533ccb5f --- /dev/null +++ b/samples/schema/petstore/wsdl-schema/jaxb-customization.xml @@ -0,0 +1,28 @@ + + + + true + false + + + + + + + + + + + + + + + + + + diff --git a/samples/schema/petstore/wsdl-schema/service.wsdl b/samples/schema/petstore/wsdl-schema/service.wsdl new file mode 100644 index 00000000000..68ce9752d72 --- /dev/null +++ b/samples/schema/petstore/wsdl-schema/service.wsdl @@ -0,0 +1,1158 @@ + + + + + + + + + Invalid input + + + + + + + Invalid ID supplied + + + + + Pet not found + + + + + + + Invalid status value + + + + + + + Invalid tag value + + + + + + + Invalid ID supplied + + + + + Pet not found + + + + + + + Invalid ID supplied + + + + + Pet not found + + + + + Validation exception + + + + + + + Invalid input + + + + + + + + + Invalid ID supplied + + + + + Order not found + + + + + + + + + Invalid ID supplied + + + + + Order not found + + + + + + + Invalid Order + + + + + + + + + + + + + Invalid username supplied + + + + + User not found + + + + + + + Invalid username supplied + + + + + User not found + + + + + + + Invalid username/password supplied + + + + + + + + + Invalid user supplied + + + + + User not found + + + + + + + + + + + + + + + + + + + + + + + + Order Status + + + + + + + + + + + + + + + pet status in the store + + + + + + + + + + + + + + + + + + + + + + User Status + + + + + + + Order Status + + + + + + + + + + pet status in the store + + + + + + + + + + + + + + + + + + + Pet object that needs to be added to the store + + + + + + + + + Pet id to delete + + + + + + + + + + Status values that need to be considered for filter + + + + + + + + + successful operation + + + + + + + + + Tags to filter by + + + + + + + + + successful operation + + + + + + + + + ID of pet to return + + + + + + + + + successful operation + + + + + + + + + Pet object that needs to be added to the store + + + + + + + + + ID of pet that needs to be updated + + + + + Updated name of the pet + + + + + Updated status of the pet + + + + + + + + + ID of pet to update + + + + + Additional data to pass to server + + + + + file to upload + + + + + + + + + successful operation + + + + + + + + + + ID of the order that needs to be deleted + + + + + + + + + + + + + + successful operation + + + + + + + + + + ID of pet that needs to be fetched + + + + + + + + + + + + + + successful operation + + + + + + + + + order placed for purchasing the pet + + + + + + + + + successful operation + + + + + + + + + Created user object + + + + + + + + + successful operation + + + + + + + + + List of user object + + + + + + + + + successful operation + + + + + + + + + List of user object + + + + + + + + + successful operation + + + + + + + + + The name that needs to be deleted + + + + + + + + + The name that needs to be fetched. Use user1 for testing. + + + + + + + + + successful operation + + + + + + + + + The user name for login + + + + + The password for login in clear text + + + + + + + + + successful operation + + + + + + + + + + successful operation + + + + + + + + + name that need to be updated + + + + + Updated user object + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Add a new pet to the store + + + Invalid input + + + + Deletes a pet + + + Invalid ID supplied + + + Pet not found + + + + Multiple status values can be provided with comma separated strings + + + successful operation + + + Invalid status value + + + + Muliple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + + + successful operation + + + Invalid tag value + + + + Returns a single pet + + + successful operation + + + Invalid ID supplied + + + Pet not found + + + + Update an existing pet + + + Invalid ID supplied + + + Pet not found + + + Validation exception + + + + Updates a pet in the store with form data + + + Invalid input + + + + uploads an image + + + successful operation + + + + For valid response try integer IDs with positive integer value. Negative or non-integer values will generate API errors + + + Invalid ID supplied + + + Order not found + + + + Returns a map of status codes to quantities + + + successful operation + + + + For valid response try integer IDs with value >= 1 and <= 10. Other values will generated exceptions + + + successful operation + + + Invalid ID supplied + + + Order not found + + + + Place an order for a pet + + + successful operation + + + Invalid Order + + + + This can only be done by the logged in user. + + + successful operation + + + + Creates list of users with given input array + + + successful operation + + + + Creates list of users with given input array + + + successful operation + + + + This can only be done by the logged in user. + + + Invalid username supplied + + + User not found + + + + Get user by user name + + + successful operation + + + Invalid username supplied + + + User not found + + + + Logs user into the system + + + successful operation + + + Invalid username/password supplied + + + + Logs out current logged in user session + + + successful operation + + + + This can only be done by the logged in user. + + + Invalid user supplied + + + User not found + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + + + + + \ 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 5f68295fc19..e8415097f3a 100644 --- a/samples/server/petstore/aspnetcore-3.0/.openapi-generator/VERSION +++ b/samples/server/petstore/aspnetcore-3.0/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/server/petstore/aspnetcore-3.1/.openapi-generator/VERSION b/samples/server/petstore/aspnetcore-3.1/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/server/petstore/aspnetcore-3.1/.openapi-generator/VERSION +++ b/samples/server/petstore/aspnetcore-3.1/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/server/petstore/aspnetcore-5.0/.openapi-generator/VERSION b/samples/server/petstore/aspnetcore-5.0/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/server/petstore/aspnetcore-5.0/.openapi-generator/VERSION +++ b/samples/server/petstore/aspnetcore-5.0/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/server/petstore/aspnetcore/.openapi-generator/VERSION b/samples/server/petstore/aspnetcore/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/server/petstore/aspnetcore/.openapi-generator/VERSION +++ b/samples/server/petstore/aspnetcore/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/server/petstore/cpp-pistache/.openapi-generator/VERSION b/samples/server/petstore/cpp-pistache/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/server/petstore/cpp-pistache/.openapi-generator/VERSION +++ b/samples/server/petstore/cpp-pistache/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/server/petstore/cpp-pistache/api/PetApi.cpp b/samples/server/petstore/cpp-pistache/api/PetApi.cpp index 7b3641599ee..a05048ec790 100644 --- a/samples/server/petstore/cpp-pistache/api/PetApi.cpp +++ b/samples/server/petstore/cpp-pistache/api/PetApi.cpp @@ -49,11 +49,13 @@ void PetApi::setupRoutes() { std::pair PetApi::handleParsingException(const std::exception& ex) const noexcept { try { - throw ex; + throw; } catch (nlohmann::detail::exception &e) { return std::make_pair(Pistache::Http::Code::Bad_Request, e.what()); } catch (org::openapitools::server::helpers::ValidationException &e) { return std::make_pair(Pistache::Http::Code::Bad_Request, e.what()); + } catch (std::exception &e) { + return std::make_pair(Pistache::Http::Code::Internal_Server_Error, e.what()) } } diff --git a/samples/server/petstore/cpp-pistache/api/PetApi.h b/samples/server/petstore/cpp-pistache/api/PetApi.h index f689a0675e1..3f790af02c1 100644 --- a/samples/server/petstore/cpp-pistache/api/PetApi.h +++ b/samples/server/petstore/cpp-pistache/api/PetApi.h @@ -58,13 +58,15 @@ private: /// /// Helper function to handle unexpected Exceptions during Parameter parsing and validation. - /// May be overriden to return custom error formats. + /// May be overriden to return custom error formats. This is called inside a catch block. + /// Important: When overriding, do not call `throw ex;`, but instead use `throw;`. /// virtual std::pair handleParsingException(const std::exception& ex) const noexcept; /// /// Helper function to handle unexpected Exceptions during processing of the request in handler functions. - /// May be overriden to return custom error formats. + /// May be overriden to return custom error formats. This is called inside a catch block. + /// Important: When overriding, do not call `throw ex;`, but instead use `throw;`. /// virtual std::pair handleOperationException(const std::exception& ex) const noexcept; diff --git a/samples/server/petstore/cpp-pistache/api/StoreApi.cpp b/samples/server/petstore/cpp-pistache/api/StoreApi.cpp index ea0c0e1793b..480bdcc0334 100644 --- a/samples/server/petstore/cpp-pistache/api/StoreApi.cpp +++ b/samples/server/petstore/cpp-pistache/api/StoreApi.cpp @@ -45,11 +45,13 @@ void StoreApi::setupRoutes() { std::pair StoreApi::handleParsingException(const std::exception& ex) const noexcept { try { - throw ex; + throw; } catch (nlohmann::detail::exception &e) { return std::make_pair(Pistache::Http::Code::Bad_Request, e.what()); } catch (org::openapitools::server::helpers::ValidationException &e) { return std::make_pair(Pistache::Http::Code::Bad_Request, e.what()); + } catch (std::exception &e) { + return std::make_pair(Pistache::Http::Code::Internal_Server_Error, e.what()) } } diff --git a/samples/server/petstore/cpp-pistache/api/StoreApi.h b/samples/server/petstore/cpp-pistache/api/StoreApi.h index 6eb22438747..e354a2710f3 100644 --- a/samples/server/petstore/cpp-pistache/api/StoreApi.h +++ b/samples/server/petstore/cpp-pistache/api/StoreApi.h @@ -54,13 +54,15 @@ private: /// /// Helper function to handle unexpected Exceptions during Parameter parsing and validation. - /// May be overriden to return custom error formats. + /// May be overriden to return custom error formats. This is called inside a catch block. + /// Important: When overriding, do not call `throw ex;`, but instead use `throw;`. /// virtual std::pair handleParsingException(const std::exception& ex) const noexcept; /// /// Helper function to handle unexpected Exceptions during processing of the request in handler functions. - /// May be overriden to return custom error formats. + /// May be overriden to return custom error formats. This is called inside a catch block. + /// Important: When overriding, do not call `throw ex;`, but instead use `throw;`. /// virtual std::pair handleOperationException(const std::exception& ex) const noexcept; diff --git a/samples/server/petstore/cpp-pistache/api/UserApi.cpp b/samples/server/petstore/cpp-pistache/api/UserApi.cpp index 94903581dc4..7b67dd0846e 100644 --- a/samples/server/petstore/cpp-pistache/api/UserApi.cpp +++ b/samples/server/petstore/cpp-pistache/api/UserApi.cpp @@ -49,11 +49,13 @@ void UserApi::setupRoutes() { std::pair UserApi::handleParsingException(const std::exception& ex) const noexcept { try { - throw ex; + throw; } catch (nlohmann::detail::exception &e) { return std::make_pair(Pistache::Http::Code::Bad_Request, e.what()); } catch (org::openapitools::server::helpers::ValidationException &e) { return std::make_pair(Pistache::Http::Code::Bad_Request, e.what()); + } catch (std::exception &e) { + return std::make_pair(Pistache::Http::Code::Internal_Server_Error, e.what()) } } diff --git a/samples/server/petstore/cpp-pistache/api/UserApi.h b/samples/server/petstore/cpp-pistache/api/UserApi.h index 003b6db4df4..fadf0b046c2 100644 --- a/samples/server/petstore/cpp-pistache/api/UserApi.h +++ b/samples/server/petstore/cpp-pistache/api/UserApi.h @@ -58,13 +58,15 @@ private: /// /// Helper function to handle unexpected Exceptions during Parameter parsing and validation. - /// May be overriden to return custom error formats. + /// May be overriden to return custom error formats. This is called inside a catch block. + /// Important: When overriding, do not call `throw ex;`, but instead use `throw;`. /// virtual std::pair handleParsingException(const std::exception& ex) const noexcept; /// /// Helper function to handle unexpected Exceptions during processing of the request in handler functions. - /// May be overriden to return custom error formats. + /// May be overriden to return custom error formats. This is called inside a catch block. + /// Important: When overriding, do not call `throw ex;`, but instead use `throw;`. /// virtual std::pair handleOperationException(const std::exception& ex) const noexcept; diff --git a/samples/server/petstore/cpp-pistache/model/ApiResponse.cpp b/samples/server/petstore/cpp-pistache/model/ApiResponse.cpp index 049f6c19d6d..4050e84f8d1 100644 --- a/samples/server/petstore/cpp-pistache/model/ApiResponse.cpp +++ b/samples/server/petstore/cpp-pistache/model/ApiResponse.cpp @@ -49,10 +49,7 @@ bool ApiResponse::validate(std::stringstream& msg, const std::string& pathPrefix bool success = true; const std::string _pathPrefix = pathPrefix.empty() ? "ApiResponse" : pathPrefix; - - - - + return success; } diff --git a/samples/server/petstore/cpp-pistache/model/ApiResponse.h b/samples/server/petstore/cpp-pistache/model/ApiResponse.h index d963b76650b..f9d9308ef0a 100644 --- a/samples/server/petstore/cpp-pistache/model/ApiResponse.h +++ b/samples/server/petstore/cpp-pistache/model/ApiResponse.h @@ -46,6 +46,12 @@ public: /// bool validate(std::stringstream& msg) const; + /// + /// Helper overload for validate. Used when one model stores another model and calls it's validate. + /// Not meant to be called outside that case. + /// + bool validate(std::stringstream& msg, const std::string& pathPrefix) const; + bool operator==(const ApiResponse& rhs) const; bool operator!=(const ApiResponse& rhs) const; @@ -83,9 +89,7 @@ protected: bool m_TypeIsSet; std::string m_Message; bool m_MessageIsSet; - - // Helper overload for validate. Used when one model stores another model and calls it's validate. - bool validate(std::stringstream& msg, const std::string& pathPrefix) const; + }; } // namespace org::openapitools::server::model diff --git a/samples/server/petstore/cpp-pistache/model/Category.cpp b/samples/server/petstore/cpp-pistache/model/Category.cpp index deb18ff9bb7..114adb15ee6 100644 --- a/samples/server/petstore/cpp-pistache/model/Category.cpp +++ b/samples/server/petstore/cpp-pistache/model/Category.cpp @@ -47,9 +47,7 @@ bool Category::validate(std::stringstream& msg, const std::string& pathPrefix) c bool success = true; const std::string _pathPrefix = pathPrefix.empty() ? "Category" : pathPrefix; - - - + return success; } diff --git a/samples/server/petstore/cpp-pistache/model/Category.h b/samples/server/petstore/cpp-pistache/model/Category.h index 1929ce33e92..eede5172427 100644 --- a/samples/server/petstore/cpp-pistache/model/Category.h +++ b/samples/server/petstore/cpp-pistache/model/Category.h @@ -46,6 +46,12 @@ public: /// bool validate(std::stringstream& msg) const; + /// + /// Helper overload for validate. Used when one model stores another model and calls it's validate. + /// Not meant to be called outside that case. + /// + bool validate(std::stringstream& msg, const std::string& pathPrefix) const; + bool operator==(const Category& rhs) const; bool operator!=(const Category& rhs) const; @@ -74,9 +80,7 @@ protected: bool m_IdIsSet; std::string m_Name; bool m_NameIsSet; - - // Helper overload for validate. Used when one model stores another model and calls it's validate. - bool validate(std::stringstream& msg, const std::string& pathPrefix) const; + }; } // namespace org::openapitools::server::model diff --git a/samples/server/petstore/cpp-pistache/model/Order.cpp b/samples/server/petstore/cpp-pistache/model/Order.cpp index 2d04f0ac637..33d08aad068 100644 --- a/samples/server/petstore/cpp-pistache/model/Order.cpp +++ b/samples/server/petstore/cpp-pistache/model/Order.cpp @@ -55,13 +55,7 @@ bool Order::validate(std::stringstream& msg, const std::string& pathPrefix) cons bool success = true; const std::string _pathPrefix = pathPrefix.empty() ? "Order" : pathPrefix; - - - - - - - + return success; } diff --git a/samples/server/petstore/cpp-pistache/model/Order.h b/samples/server/petstore/cpp-pistache/model/Order.h index 3d28e1eef6b..f725c509990 100644 --- a/samples/server/petstore/cpp-pistache/model/Order.h +++ b/samples/server/petstore/cpp-pistache/model/Order.h @@ -46,6 +46,12 @@ public: /// bool validate(std::stringstream& msg) const; + /// + /// Helper overload for validate. Used when one model stores another model and calls it's validate. + /// Not meant to be called outside that case. + /// + bool validate(std::stringstream& msg, const std::string& pathPrefix) const; + bool operator==(const Order& rhs) const; bool operator!=(const Order& rhs) const; @@ -110,9 +116,7 @@ protected: bool m_StatusIsSet; bool m_Complete; bool m_CompleteIsSet; - - // Helper overload for validate. Used when one model stores another model and calls it's validate. - bool validate(std::stringstream& msg, const std::string& pathPrefix) const; + }; } // namespace org::openapitools::server::model diff --git a/samples/server/petstore/cpp-pistache/model/Pet.cpp b/samples/server/petstore/cpp-pistache/model/Pet.cpp index 9c7ba886a44..51d97b41979 100644 --- a/samples/server/petstore/cpp-pistache/model/Pet.cpp +++ b/samples/server/petstore/cpp-pistache/model/Pet.cpp @@ -50,10 +50,7 @@ bool Pet::validate(std::stringstream& msg, const std::string& pathPrefix) const bool success = true; const std::string _pathPrefix = pathPrefix.empty() ? "Pet" : pathPrefix; - - - - + /* PhotoUrls */ { const std::vector& value = m_PhotoUrls; @@ -74,8 +71,7 @@ bool Pet::validate(std::stringstream& msg, const std::string& pathPrefix) const } } - - + if (tagsIsSet()) { const std::vector& value = m_Tags; @@ -96,9 +92,7 @@ bool Pet::validate(std::stringstream& msg, const std::string& pathPrefix) const } } - - - + return success; } diff --git a/samples/server/petstore/cpp-pistache/model/Pet.h b/samples/server/petstore/cpp-pistache/model/Pet.h index 1cd841a08fa..c3cee2e2b4d 100644 --- a/samples/server/petstore/cpp-pistache/model/Pet.h +++ b/samples/server/petstore/cpp-pistache/model/Pet.h @@ -49,6 +49,12 @@ public: /// bool validate(std::stringstream& msg) const; + /// + /// Helper overload for validate. Used when one model stores another model and calls it's validate. + /// Not meant to be called outside that case. + /// + bool validate(std::stringstream& msg, const std::string& pathPrefix) const; + bool operator==(const Pet& rhs) const; bool operator!=(const Pet& rhs) const; @@ -109,9 +115,7 @@ protected: bool m_TagsIsSet; std::string m_Status; bool m_StatusIsSet; - - // Helper overload for validate. Used when one model stores another model and calls it's validate. - bool validate(std::stringstream& msg, const std::string& pathPrefix) const; + }; } // namespace org::openapitools::server::model diff --git a/samples/server/petstore/cpp-pistache/model/Tag.cpp b/samples/server/petstore/cpp-pistache/model/Tag.cpp index 659565e4034..fecaccfc64c 100644 --- a/samples/server/petstore/cpp-pistache/model/Tag.cpp +++ b/samples/server/petstore/cpp-pistache/model/Tag.cpp @@ -47,9 +47,7 @@ bool Tag::validate(std::stringstream& msg, const std::string& pathPrefix) const bool success = true; const std::string _pathPrefix = pathPrefix.empty() ? "Tag" : pathPrefix; - - - + return success; } diff --git a/samples/server/petstore/cpp-pistache/model/Tag.h b/samples/server/petstore/cpp-pistache/model/Tag.h index ddebeadae43..822c760be7e 100644 --- a/samples/server/petstore/cpp-pistache/model/Tag.h +++ b/samples/server/petstore/cpp-pistache/model/Tag.h @@ -46,6 +46,12 @@ public: /// bool validate(std::stringstream& msg) const; + /// + /// Helper overload for validate. Used when one model stores another model and calls it's validate. + /// Not meant to be called outside that case. + /// + bool validate(std::stringstream& msg, const std::string& pathPrefix) const; + bool operator==(const Tag& rhs) const; bool operator!=(const Tag& rhs) const; @@ -74,9 +80,7 @@ protected: bool m_IdIsSet; std::string m_Name; bool m_NameIsSet; - - // Helper overload for validate. Used when one model stores another model and calls it's validate. - bool validate(std::stringstream& msg, const std::string& pathPrefix) const; + }; } // namespace org::openapitools::server::model diff --git a/samples/server/petstore/cpp-pistache/model/User.cpp b/samples/server/petstore/cpp-pistache/model/User.cpp index c997bf9734d..05f504ed30d 100644 --- a/samples/server/petstore/cpp-pistache/model/User.cpp +++ b/samples/server/petstore/cpp-pistache/model/User.cpp @@ -59,15 +59,7 @@ bool User::validate(std::stringstream& msg, const std::string& pathPrefix) const bool success = true; const std::string _pathPrefix = pathPrefix.empty() ? "User" : pathPrefix; - - - - - - - - - + return success; } diff --git a/samples/server/petstore/cpp-pistache/model/User.h b/samples/server/petstore/cpp-pistache/model/User.h index 02bd5f4230a..aebc4fe5a35 100644 --- a/samples/server/petstore/cpp-pistache/model/User.h +++ b/samples/server/petstore/cpp-pistache/model/User.h @@ -46,6 +46,12 @@ public: /// bool validate(std::stringstream& msg) const; + /// + /// Helper overload for validate. Used when one model stores another model and calls it's validate. + /// Not meant to be called outside that case. + /// + bool validate(std::stringstream& msg, const std::string& pathPrefix) const; + bool operator==(const User& rhs) const; bool operator!=(const User& rhs) const; @@ -128,9 +134,7 @@ protected: bool m_PhoneIsSet; int32_t m_UserStatus; bool m_UserStatusIsSet; - - // Helper overload for validate. Used when one model stores another model and calls it's validate. - bool validate(std::stringstream& msg, const std::string& pathPrefix) const; + }; } // namespace org::openapitools::server::model diff --git a/samples/server/petstore/cpp-qt-qhttpengine-server/.openapi-generator-ignore b/samples/server/petstore/cpp-qt-qhttpengine-server/.openapi-generator-ignore new file mode 100644 index 00000000000..7484ee590a3 --- /dev/null +++ b/samples/server/petstore/cpp-qt-qhttpengine-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/cpp-qt5-qhttpengine-server/.openapi-generator/FILES b/samples/server/petstore/cpp-qt-qhttpengine-server/.openapi-generator/FILES similarity index 100% rename from samples/server/petstore/cpp-qt5-qhttpengine-server/.openapi-generator/FILES rename to samples/server/petstore/cpp-qt-qhttpengine-server/.openapi-generator/FILES diff --git a/samples/server/petstore/cpp-qt-qhttpengine-server/.openapi-generator/VERSION b/samples/server/petstore/cpp-qt-qhttpengine-server/.openapi-generator/VERSION new file mode 100644 index 00000000000..4b448de535c --- /dev/null +++ b/samples/server/petstore/cpp-qt-qhttpengine-server/.openapi-generator/VERSION @@ -0,0 +1 @@ +5.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/cpp-qt5-qhttpengine-server/server/CMakeLists.txt b/samples/server/petstore/cpp-qt-qhttpengine-server/server/CMakeLists.txt similarity index 93% rename from samples/server/petstore/cpp-qt5-qhttpengine-server/server/CMakeLists.txt rename to samples/server/petstore/cpp-qt-qhttpengine-server/server/CMakeLists.txt index 54e6d36d73f..71b8bdb45f4 100644 --- a/samples/server/petstore/cpp-qt5-qhttpengine-server/server/CMakeLists.txt +++ b/samples/server/petstore/cpp-qt-qhttpengine-server/server/CMakeLists.txt @@ -1,5 +1,5 @@ cmake_minimum_required(VERSION 3.2 FATAL_ERROR) -project(cpp-qt5-qhttpengine-server) +project(cpp-qt-qhttpengine-server) include(ExternalProject) diff --git a/samples/server/petstore/cpp-qt5-qhttpengine-server/server/Dockerfile b/samples/server/petstore/cpp-qt-qhttpengine-server/server/Dockerfile similarity index 78% rename from samples/server/petstore/cpp-qt5-qhttpengine-server/server/Dockerfile rename to samples/server/petstore/cpp-qt-qhttpengine-server/server/Dockerfile index b0c591d10f6..9dfdd9ab478 100644 --- a/samples/server/petstore/cpp-qt5-qhttpengine-server/server/Dockerfile +++ b/samples/server/petstore/cpp-qt-qhttpengine-server/server/Dockerfile @@ -23,7 +23,7 @@ RUN apk add --update \ openssl WORKDIR /usr/server -COPY --from=build /usr/server/build/src/cpp-qt5-qhttpengine-server ./build/src/ +COPY --from=build /usr/server/build/src/cpp-qt-qhttpengine-server ./build/src/ COPY --from=build /usr/server/external/ ./external EXPOSE 8080/tcp -ENTRYPOINT ["/usr/server/build/src/cpp-qt5-qhttpengine-server"] \ No newline at end of file +ENTRYPOINT ["/usr/server/build/src/cpp-qt-qhttpengine-server"] diff --git a/samples/server/petstore/cpp-qt5-qhttpengine-server/server/LICENSE.txt b/samples/server/petstore/cpp-qt-qhttpengine-server/server/LICENSE.txt similarity index 100% rename from samples/server/petstore/cpp-qt5-qhttpengine-server/server/LICENSE.txt rename to samples/server/petstore/cpp-qt-qhttpengine-server/server/LICENSE.txt diff --git a/samples/server/petstore/cpp-qt5-qhttpengine-server/server/Makefile b/samples/server/petstore/cpp-qt-qhttpengine-server/server/Makefile similarity index 100% rename from samples/server/petstore/cpp-qt5-qhttpengine-server/server/Makefile rename to samples/server/petstore/cpp-qt-qhttpengine-server/server/Makefile diff --git a/samples/server/petstore/cpp-qt5-qhttpengine-server/server/README.MD b/samples/server/petstore/cpp-qt-qhttpengine-server/server/README.MD similarity index 88% rename from samples/server/petstore/cpp-qt5-qhttpengine-server/server/README.MD rename to samples/server/petstore/cpp-qt-qhttpengine-server/server/README.MD index 5225ebb24fd..8158062ef70 100644 --- a/samples/server/petstore/cpp-qt5-qhttpengine-server/server/README.MD +++ b/samples/server/petstore/cpp-qt-qhttpengine-server/server/README.MD @@ -1,6 +1,6 @@ -# C++ Qt5 Server +# C++ Qt Server -## Qt5 HTTP Server based on the Qhttpengine +## Qt HTTP Server based on the Qhttpengine 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. @@ -46,18 +46,18 @@ make To run the server ```shell -./build/src/cpp-qt5-qhttpengine-server & +./build/src/cpp-qt-qhttpengine-server & ``` To override the default port via the command line, provide the parameters `port` and `address` like below ```shell -cpp-qt5-qhttpengine-server --port 9080 --address 127.17.0.1 +cpp-qt-qhttpengine-server --port 9080 --address 127.17.0.1 ``` or ```shell -cpp-qt5-qhttpengine-server -p 9080 -a 127.17.0.1 +cpp-qt-qhttpengine-server -p 9080 -a 127.17.0.1 ``` #### Invoke an API @@ -76,13 +76,13 @@ If you dont have docker install [here](https://docs.docker.com/install) Add yourself to the docker group ```shell -docker build --network=host -t cpp-qt5-qhttpengine-server . +docker build --network=host -t cpp-qt-qhttpengine-server . ``` Running with docker ```shell -docker run --rm -it --name=server-container cpp-qt5-qhttpengine-server +docker run --rm -it --name=server-container cpp-qt-qhttpengine-server ``` #### Invoking an API diff --git a/samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/CMakeLists.txt b/samples/server/petstore/cpp-qt-qhttpengine-server/server/src/CMakeLists.txt similarity index 100% rename from samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/CMakeLists.txt rename to samples/server/petstore/cpp-qt-qhttpengine-server/server/src/CMakeLists.txt diff --git a/samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/handlers/OAIApiRouter.cpp b/samples/server/petstore/cpp-qt-qhttpengine-server/server/src/handlers/OAIApiRouter.cpp similarity index 100% rename from samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/handlers/OAIApiRouter.cpp rename to samples/server/petstore/cpp-qt-qhttpengine-server/server/src/handlers/OAIApiRouter.cpp diff --git a/samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/handlers/OAIApiRouter.h b/samples/server/petstore/cpp-qt-qhttpengine-server/server/src/handlers/OAIApiRouter.h similarity index 100% rename from samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/handlers/OAIApiRouter.h rename to samples/server/petstore/cpp-qt-qhttpengine-server/server/src/handlers/OAIApiRouter.h diff --git a/samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/handlers/OAIPetApiHandler.cpp b/samples/server/petstore/cpp-qt-qhttpengine-server/server/src/handlers/OAIPetApiHandler.cpp similarity index 100% rename from samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/handlers/OAIPetApiHandler.cpp rename to samples/server/petstore/cpp-qt-qhttpengine-server/server/src/handlers/OAIPetApiHandler.cpp diff --git a/samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/handlers/OAIPetApiHandler.h b/samples/server/petstore/cpp-qt-qhttpengine-server/server/src/handlers/OAIPetApiHandler.h similarity index 100% rename from samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/handlers/OAIPetApiHandler.h rename to samples/server/petstore/cpp-qt-qhttpengine-server/server/src/handlers/OAIPetApiHandler.h diff --git a/samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/handlers/OAIStoreApiHandler.cpp b/samples/server/petstore/cpp-qt-qhttpengine-server/server/src/handlers/OAIStoreApiHandler.cpp similarity index 100% rename from samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/handlers/OAIStoreApiHandler.cpp rename to samples/server/petstore/cpp-qt-qhttpengine-server/server/src/handlers/OAIStoreApiHandler.cpp diff --git a/samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/handlers/OAIStoreApiHandler.h b/samples/server/petstore/cpp-qt-qhttpengine-server/server/src/handlers/OAIStoreApiHandler.h similarity index 100% rename from samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/handlers/OAIStoreApiHandler.h rename to samples/server/petstore/cpp-qt-qhttpengine-server/server/src/handlers/OAIStoreApiHandler.h diff --git a/samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/handlers/OAIUserApiHandler.cpp b/samples/server/petstore/cpp-qt-qhttpengine-server/server/src/handlers/OAIUserApiHandler.cpp similarity index 100% rename from samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/handlers/OAIUserApiHandler.cpp rename to samples/server/petstore/cpp-qt-qhttpengine-server/server/src/handlers/OAIUserApiHandler.cpp diff --git a/samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/handlers/OAIUserApiHandler.h b/samples/server/petstore/cpp-qt-qhttpengine-server/server/src/handlers/OAIUserApiHandler.h similarity index 100% rename from samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/handlers/OAIUserApiHandler.h rename to samples/server/petstore/cpp-qt-qhttpengine-server/server/src/handlers/OAIUserApiHandler.h diff --git a/samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/main.cpp b/samples/server/petstore/cpp-qt-qhttpengine-server/server/src/main.cpp similarity index 100% rename from samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/main.cpp rename to samples/server/petstore/cpp-qt-qhttpengine-server/server/src/main.cpp diff --git a/samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/models/OAIApiResponse.cpp b/samples/server/petstore/cpp-qt-qhttpengine-server/server/src/models/OAIApiResponse.cpp similarity index 100% rename from samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/models/OAIApiResponse.cpp rename to samples/server/petstore/cpp-qt-qhttpengine-server/server/src/models/OAIApiResponse.cpp diff --git a/samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/models/OAIApiResponse.h b/samples/server/petstore/cpp-qt-qhttpengine-server/server/src/models/OAIApiResponse.h similarity index 100% rename from samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/models/OAIApiResponse.h rename to samples/server/petstore/cpp-qt-qhttpengine-server/server/src/models/OAIApiResponse.h diff --git a/samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/models/OAICategory.cpp b/samples/server/petstore/cpp-qt-qhttpengine-server/server/src/models/OAICategory.cpp similarity index 100% rename from samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/models/OAICategory.cpp rename to samples/server/petstore/cpp-qt-qhttpengine-server/server/src/models/OAICategory.cpp diff --git a/samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/models/OAICategory.h b/samples/server/petstore/cpp-qt-qhttpengine-server/server/src/models/OAICategory.h similarity index 100% rename from samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/models/OAICategory.h rename to samples/server/petstore/cpp-qt-qhttpengine-server/server/src/models/OAICategory.h diff --git a/samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/models/OAIEnum.h b/samples/server/petstore/cpp-qt-qhttpengine-server/server/src/models/OAIEnum.h similarity index 100% rename from samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/models/OAIEnum.h rename to samples/server/petstore/cpp-qt-qhttpengine-server/server/src/models/OAIEnum.h diff --git a/samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/models/OAIHelpers.cpp b/samples/server/petstore/cpp-qt-qhttpengine-server/server/src/models/OAIHelpers.cpp similarity index 100% rename from samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/models/OAIHelpers.cpp rename to samples/server/petstore/cpp-qt-qhttpengine-server/server/src/models/OAIHelpers.cpp diff --git a/samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/models/OAIHelpers.h b/samples/server/petstore/cpp-qt-qhttpengine-server/server/src/models/OAIHelpers.h similarity index 100% rename from samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/models/OAIHelpers.h rename to samples/server/petstore/cpp-qt-qhttpengine-server/server/src/models/OAIHelpers.h diff --git a/samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/models/OAIHttpFileElement.cpp b/samples/server/petstore/cpp-qt-qhttpengine-server/server/src/models/OAIHttpFileElement.cpp similarity index 100% rename from samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/models/OAIHttpFileElement.cpp rename to samples/server/petstore/cpp-qt-qhttpengine-server/server/src/models/OAIHttpFileElement.cpp diff --git a/samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/models/OAIHttpFileElement.h b/samples/server/petstore/cpp-qt-qhttpengine-server/server/src/models/OAIHttpFileElement.h similarity index 100% rename from samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/models/OAIHttpFileElement.h rename to samples/server/petstore/cpp-qt-qhttpengine-server/server/src/models/OAIHttpFileElement.h diff --git a/samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/models/OAIObject.h b/samples/server/petstore/cpp-qt-qhttpengine-server/server/src/models/OAIObject.h similarity index 100% rename from samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/models/OAIObject.h rename to samples/server/petstore/cpp-qt-qhttpengine-server/server/src/models/OAIObject.h diff --git a/samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/models/OAIOrder.cpp b/samples/server/petstore/cpp-qt-qhttpengine-server/server/src/models/OAIOrder.cpp similarity index 100% rename from samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/models/OAIOrder.cpp rename to samples/server/petstore/cpp-qt-qhttpengine-server/server/src/models/OAIOrder.cpp diff --git a/samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/models/OAIOrder.h b/samples/server/petstore/cpp-qt-qhttpengine-server/server/src/models/OAIOrder.h similarity index 100% rename from samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/models/OAIOrder.h rename to samples/server/petstore/cpp-qt-qhttpengine-server/server/src/models/OAIOrder.h diff --git a/samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/models/OAIPet.cpp b/samples/server/petstore/cpp-qt-qhttpengine-server/server/src/models/OAIPet.cpp similarity index 100% rename from samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/models/OAIPet.cpp rename to samples/server/petstore/cpp-qt-qhttpengine-server/server/src/models/OAIPet.cpp diff --git a/samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/models/OAIPet.h b/samples/server/petstore/cpp-qt-qhttpengine-server/server/src/models/OAIPet.h similarity index 100% rename from samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/models/OAIPet.h rename to samples/server/petstore/cpp-qt-qhttpengine-server/server/src/models/OAIPet.h diff --git a/samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/models/OAITag.cpp b/samples/server/petstore/cpp-qt-qhttpengine-server/server/src/models/OAITag.cpp similarity index 100% rename from samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/models/OAITag.cpp rename to samples/server/petstore/cpp-qt-qhttpengine-server/server/src/models/OAITag.cpp diff --git a/samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/models/OAITag.h b/samples/server/petstore/cpp-qt-qhttpengine-server/server/src/models/OAITag.h similarity index 100% rename from samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/models/OAITag.h rename to samples/server/petstore/cpp-qt-qhttpengine-server/server/src/models/OAITag.h diff --git a/samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/models/OAIUser.cpp b/samples/server/petstore/cpp-qt-qhttpengine-server/server/src/models/OAIUser.cpp similarity index 100% rename from samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/models/OAIUser.cpp rename to samples/server/petstore/cpp-qt-qhttpengine-server/server/src/models/OAIUser.cpp diff --git a/samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/models/OAIUser.h b/samples/server/petstore/cpp-qt-qhttpengine-server/server/src/models/OAIUser.h similarity index 100% rename from samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/models/OAIUser.h rename to samples/server/petstore/cpp-qt-qhttpengine-server/server/src/models/OAIUser.h diff --git a/samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/requests/OAIPetApiRequest.cpp b/samples/server/petstore/cpp-qt-qhttpengine-server/server/src/requests/OAIPetApiRequest.cpp similarity index 100% rename from samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/requests/OAIPetApiRequest.cpp rename to samples/server/petstore/cpp-qt-qhttpengine-server/server/src/requests/OAIPetApiRequest.cpp diff --git a/samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/requests/OAIPetApiRequest.h b/samples/server/petstore/cpp-qt-qhttpengine-server/server/src/requests/OAIPetApiRequest.h similarity index 100% rename from samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/requests/OAIPetApiRequest.h rename to samples/server/petstore/cpp-qt-qhttpengine-server/server/src/requests/OAIPetApiRequest.h diff --git a/samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/requests/OAIStoreApiRequest.cpp b/samples/server/petstore/cpp-qt-qhttpengine-server/server/src/requests/OAIStoreApiRequest.cpp similarity index 100% rename from samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/requests/OAIStoreApiRequest.cpp rename to samples/server/petstore/cpp-qt-qhttpengine-server/server/src/requests/OAIStoreApiRequest.cpp diff --git a/samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/requests/OAIStoreApiRequest.h b/samples/server/petstore/cpp-qt-qhttpengine-server/server/src/requests/OAIStoreApiRequest.h similarity index 100% rename from samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/requests/OAIStoreApiRequest.h rename to samples/server/petstore/cpp-qt-qhttpengine-server/server/src/requests/OAIStoreApiRequest.h diff --git a/samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/requests/OAIUserApiRequest.cpp b/samples/server/petstore/cpp-qt-qhttpengine-server/server/src/requests/OAIUserApiRequest.cpp similarity index 100% rename from samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/requests/OAIUserApiRequest.cpp rename to samples/server/petstore/cpp-qt-qhttpengine-server/server/src/requests/OAIUserApiRequest.cpp diff --git a/samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/requests/OAIUserApiRequest.h b/samples/server/petstore/cpp-qt-qhttpengine-server/server/src/requests/OAIUserApiRequest.h similarity index 100% rename from samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/requests/OAIUserApiRequest.h rename to samples/server/petstore/cpp-qt-qhttpengine-server/server/src/requests/OAIUserApiRequest.h diff --git a/samples/server/petstore/erlang-server/.openapi-generator/VERSION b/samples/server/petstore/erlang-server/.openapi-generator/VERSION index d509cc92aa8..4b448de535c 100644 --- a/samples/server/petstore/erlang-server/.openapi-generator/VERSION +++ b/samples/server/petstore/erlang-server/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.1-SNAPSHOT \ No newline at end of file +5.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/erlang-server/src/openapi_api.erl b/samples/server/petstore/erlang-server/src/openapi_api.erl index a1a6fa220ec..19e8f7b542c 100644 --- a/samples/server/petstore/erlang-server/src/openapi_api.erl +++ b/samples/server/petstore/erlang-server/src/openapi_api.erl @@ -349,7 +349,7 @@ request_param_info('LoginUser', 'username') -> source => qs_val , rules => [ {type, 'binary'}, - {pattern, "/^[a-zA-Z0-9]+[a-zA-Z0-9\\.\\-_]*[a-zA-Z0-9]+$/" }, + {pattern, "^[a-zA-Z0-9]+[a-zA-Z0-9\\.\\-_]*[a-zA-Z0-9]+$" }, required ] }; diff --git a/samples/server/petstore/erlang-server/src/openapi_logic_handler.erl b/samples/server/petstore/erlang-server/src/openapi_logic_handler.erl index 2c05ce24836..1a36f0a40f4 100644 --- a/samples/server/petstore/erlang-server/src/openapi_logic_handler.erl +++ b/samples/server/petstore/erlang-server/src/openapi_logic_handler.erl @@ -6,8 +6,7 @@ -type handler_response() ::{ Status :: cowboy:http_status(), Headers :: cowboy:http_headers(), - Body :: #{} -}. + Body :: jsx:json_term()}. -export_type([handler_response/0]). diff --git a/samples/server/petstore/erlang-server/src/openapi_pet_handler.erl b/samples/server/petstore/erlang-server/src/openapi_pet_handler.erl index 15bbb6432fd..a6cbaab177c 100644 --- a/samples/server/petstore/erlang-server/src/openapi_pet_handler.erl +++ b/samples/server/petstore/erlang-server/src/openapi_pet_handler.erl @@ -440,7 +440,7 @@ process_response(Response, Req0, State = #state{operation_id = OperationID}) -> {stop, Req, State} end. --spec handle_request_json(cowboy_req:req(), state()) -> {cowboy_req:resp_body(), cowboy_req:req(), state()}. +-spec handle_request_json(cowboy_req:req(), state()) -> processed_response(). handle_request_json( Req0, @@ -464,7 +464,7 @@ handle_request_json( Body, ValidatorState ), - PreparedBody = jsx:encode(Body), + PreparedBody = prepare_body(Code, Body), Response = {ok, {Code, Headers, PreparedBody}}, process_response(Response, Req1, State); {error, Reason, Req1} -> @@ -472,3 +472,10 @@ handle_request_json( end. validate_headers(_, Req) -> {true, Req}. + +prepare_body(204, Body) when map_size(Body) == 0; length(Body) == 0 -> + <<>>; +prepare_body(304, Body) when map_size(Body) == 0; length(Body) == 0 -> + <<>>; +prepare_body(_Code, Body) -> + jsx:encode(Body). diff --git a/samples/server/petstore/erlang-server/src/openapi_server.erl b/samples/server/petstore/erlang-server/src/openapi_server.erl index 45f6d1a39d5..02500173821 100644 --- a/samples/server/petstore/erlang-server/src/openapi_server.erl +++ b/samples/server/petstore/erlang-server/src/openapi_server.erl @@ -64,4 +64,4 @@ get_default_opts(LogicHandler) -> #{env => get_default_dispatch(LogicHandler)}. store_key(Key, Value, Opts) -> - lists:keystore(Key, 1, Opts, {Key, Value}). + maps:put(Key, Value, Opts). diff --git a/samples/server/petstore/erlang-server/src/openapi_store_handler.erl b/samples/server/petstore/erlang-server/src/openapi_store_handler.erl index 57921986531..98341c066c2 100644 --- a/samples/server/petstore/erlang-server/src/openapi_store_handler.erl +++ b/samples/server/petstore/erlang-server/src/openapi_store_handler.erl @@ -235,7 +235,7 @@ process_response(Response, Req0, State = #state{operation_id = OperationID}) -> {stop, Req, State} end. --spec handle_request_json(cowboy_req:req(), state()) -> {cowboy_req:resp_body(), cowboy_req:req(), state()}. +-spec handle_request_json(cowboy_req:req(), state()) -> processed_response(). handle_request_json( Req0, @@ -259,7 +259,7 @@ handle_request_json( Body, ValidatorState ), - PreparedBody = jsx:encode(Body), + PreparedBody = prepare_body(Code, Body), Response = {ok, {Code, Headers, PreparedBody}}, process_response(Response, Req1, State); {error, Reason, Req1} -> @@ -267,3 +267,10 @@ handle_request_json( end. validate_headers(_, Req) -> {true, Req}. + +prepare_body(204, Body) when map_size(Body) == 0; length(Body) == 0 -> + <<>>; +prepare_body(304, Body) when map_size(Body) == 0; length(Body) == 0 -> + <<>>; +prepare_body(_Code, Body) -> + jsx:encode(Body). diff --git a/samples/server/petstore/erlang-server/src/openapi_user_handler.erl b/samples/server/petstore/erlang-server/src/openapi_user_handler.erl index 4c71b5ebcfd..ad9f11d7300 100644 --- a/samples/server/petstore/erlang-server/src/openapi_user_handler.erl +++ b/samples/server/petstore/erlang-server/src/openapi_user_handler.erl @@ -402,7 +402,7 @@ process_response(Response, Req0, State = #state{operation_id = OperationID}) -> {stop, Req, State} end. --spec handle_request_json(cowboy_req:req(), state()) -> {cowboy_req:resp_body(), cowboy_req:req(), state()}. +-spec handle_request_json(cowboy_req:req(), state()) -> processed_response(). handle_request_json( Req0, @@ -426,7 +426,7 @@ handle_request_json( Body, ValidatorState ), - PreparedBody = jsx:encode(Body), + PreparedBody = prepare_body(Code, Body), Response = {ok, {Code, Headers, PreparedBody}}, process_response(Response, Req1, State); {error, Reason, Req1} -> @@ -434,3 +434,10 @@ handle_request_json( end. validate_headers(_, Req) -> {true, Req}. + +prepare_body(204, Body) when map_size(Body) == 0; length(Body) == 0 -> + <<>>; +prepare_body(304, Body) when map_size(Body) == 0; length(Body) == 0 -> + <<>>; +prepare_body(_Code, Body) -> + jsx:encode(Body). diff --git a/samples/server/petstore/go-api-server/.openapi-generator/VERSION b/samples/server/petstore/go-api-server/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/server/petstore/go-api-server/.openapi-generator/VERSION +++ b/samples/server/petstore/go-api-server/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/server/petstore/go-api-server/go/routers.go b/samples/server/petstore/go-api-server/go/routers.go index 7f41207fbde..2b34778c5a1 100644 --- a/samples/server/petstore/go-api-server/go/routers.go +++ b/samples/server/petstore/go-api-server/go/routers.go @@ -61,7 +61,15 @@ func NewRouter(routers ...Router) *mux.Router { // EncodeJSONResponse uses the json encoder to write an interface to the http response with an optional status code func EncodeJSONResponse(i interface{}, status *int, headers map[string][]string, w http.ResponseWriter) error { - w.Header().Set("Content-Type", "application/json; charset=UTF-8") + wHeader := w.Header() + if headers != nil { + for key, values := range headers { + for _, value := range values { + wHeader.Add(key, value) + } + } + } + wHeader.Set("Content-Type", "application/json; charset=UTF-8") if status != nil { w.WriteHeader(*status) } else { diff --git a/samples/server/petstore/go-chi-server/.openapi-generator-ignore b/samples/server/petstore/go-chi-server/.openapi-generator-ignore new file mode 100644 index 00000000000..7484ee590a3 --- /dev/null +++ b/samples/server/petstore/go-chi-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/go-chi-server/.openapi-generator/FILES b/samples/server/petstore/go-chi-server/.openapi-generator/FILES new file mode 100644 index 00000000000..9135763258f --- /dev/null +++ b/samples/server/petstore/go-chi-server/.openapi-generator/FILES @@ -0,0 +1,22 @@ +Dockerfile +README.md +api/openapi.yaml +go.mod +go/api.go +go/api_pet.go +go/api_pet_service.go +go/api_store.go +go/api_store_service.go +go/api_user.go +go/api_user_service.go +go/helpers.go +go/impl.go +go/logger.go +go/model_api_response.go +go/model_category.go +go/model_order.go +go/model_pet.go +go/model_tag.go +go/model_user.go +go/routers.go +main.go diff --git a/samples/server/petstore/go-chi-server/.openapi-generator/VERSION b/samples/server/petstore/go-chi-server/.openapi-generator/VERSION new file mode 100644 index 00000000000..4b448de535c --- /dev/null +++ b/samples/server/petstore/go-chi-server/.openapi-generator/VERSION @@ -0,0 +1 @@ +5.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/go-chi-server/Dockerfile b/samples/server/petstore/go-chi-server/Dockerfile new file mode 100644 index 00000000000..cfdfbaed080 --- /dev/null +++ b/samples/server/petstore/go-chi-server/Dockerfile @@ -0,0 +1,14 @@ +FROM golang:1.10 AS build +WORKDIR /go/src +COPY go ./go +COPY main.go . + +ENV CGO_ENABLED=0 +RUN go get -d -v ./... + +RUN go build -a -installsuffix cgo -o petstoreserver . + +FROM scratch AS runtime +COPY --from=build /go/src/petstoreserver ./ +EXPOSE 8080/tcp +ENTRYPOINT ["./petstoreserver"] diff --git a/samples/server/petstore/go-chi-server/README.md b/samples/server/petstore/go-chi-server/README.md new file mode 100644 index 00000000000..fbcf4ae661b --- /dev/null +++ b/samples/server/petstore/go-chi-server/README.md @@ -0,0 +1,35 @@ +# Go API Server for petstoreserver + +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 + + +### Running the server +To run the server, follow these simple steps: + +``` +go run main.go +``` + +To run the server in a docker container +``` +docker build --network=host -t petstoreserver . +``` + +Once image is built use +``` +docker run --rm -it petstoreserver +``` + + diff --git a/samples/server/petstore/go-chi-server/api/openapi.yaml b/samples/server/petstore/go-chi-server/api/openapi.yaml new file mode 100644 index 00000000000..26aaeac34b7 --- /dev/null +++ b/samples/server/petstore/go-chi-server/api/openapi.yaml @@ -0,0 +1,822 @@ +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 +- description: Access to Petstore orders + name: store +- description: Operations about user + name: user +paths: + /pet: + post: + 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 + put: + operationId: updatePet + 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 + "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 + /pet/findByStatus: + get: + description: Multiple status values can be provided with comma separated strings + operationId: findPetsByStatus + 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 + /pet/findByTags: + get: + deprecated: true + description: Multiple tags can be provided with comma separated strings. Use + tag1, tag2, tag3 for testing. + operationId: findPetsByTags + 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 + /pet/{petId}: + delete: + operationId: deletePet + 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 + get: + description: Returns a single pet + operationId: getPetById + 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 + post: + operationId: updatePetWithForm + 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/inline_object' + content: + application/x-www-form-urlencoded: + schema: + properties: + name: + description: Updated name of the pet + type: string + status: + description: Updated status of the pet + type: string + type: object + responses: + "405": + description: Invalid input + security: + - petstore_auth: + - write:pets + - read:pets + summary: Updates a pet in the store with form data + tags: + - pet + /pet/{petId}/uploadImage: + post: + operationId: uploadFile + 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/inline_object_1' + content: + multipart/form-data: + schema: + properties: + additionalMetadata: + description: Additional data to pass to server + type: string + file: + description: file to upload + format: binary + type: string + type: object + 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 + /store/inventory: + get: + description: Returns a map of status codes to quantities + operationId: getInventory + 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 + /store/order: + post: + operationId: placeOrder + 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 + /store/order/{orderId}: + delete: + description: For valid response try integer IDs with value < 1000. Anything + above 1000 or nonintegers will generate API errors + operationId: deleteOrder + 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 + get: + description: For valid response try integer IDs with value <= 5 or > 10. Other + values will generated exceptions + operationId: getOrderById + 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 + /user: + post: + description: This can only be done by the logged in user. + operationId: createUser + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/User' + description: Created user object + required: true + responses: + default: + description: successful operation + security: + - api_key: [] + summary: Create user + tags: + - user + /user/createWithArray: + post: + operationId: createUsersWithArrayInput + requestBody: + $ref: '#/components/requestBodies/UserArray' + responses: + default: + description: successful operation + security: + - api_key: [] + summary: Creates list of users with given input array + tags: + - user + /user/createWithList: + post: + operationId: createUsersWithListInput + requestBody: + $ref: '#/components/requestBodies/UserArray' + responses: + default: + description: successful operation + security: + - api_key: [] + summary: Creates list of users with given input array + tags: + - user + /user/login: + get: + operationId: loginUser + 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 `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 + schema: + format: int32 + type: integer + style: simple + X-Expires-After: + description: date in UTC when toekn 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 + /user/logout: + get: + operationId: logoutUser + responses: + default: + description: successful operation + security: + - api_key: [] + summary: Logs out current logged in user session + tags: + - user + /user/{username}: + delete: + description: This can only be done by the logged in user. + operationId: deleteUser + 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: + - api_key: [] + summary: Delete user + tags: + - user + get: + operationId: getUserByName + 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 + put: + description: This can only be done by the logged in user. + operationId: updateUser + 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: + - api_key: [] + summary: Updated user + tags: + - user +components: + requestBodies: + UserArray: + content: + application/json: + schema: + items: + $ref: '#/components/schemas/User' + type: array + 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 + inline_object: + content: + application/x-www-form-urlencoded: + schema: + $ref: '#/components/schemas/inline_object' + inline_object_1: + content: + multipart/form-data: + schema: + $ref: '#/components/schemas/inline_object_1' + 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 + type: integer + petId: + format: int64 + type: integer + quantity: + format: int32 + type: integer + shipDate: + format: date-time + type: string + status: + description: Order Status + enum: + - placed + - approved + - delivered + type: string + complete: + default: false + 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 + 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 + 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 + type: integer + username: + type: string + firstName: + type: string + lastName: + type: string + email: + type: string + password: + type: string + phone: + type: string + userStatus: + description: User Status + format: int32 + 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 + 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: + description: pet status in the store + enum: + - available + - pending + - sold + type: string + required: + - name + - photoUrls + title: a Pet + type: object + xml: + name: Pet + ApiResponse: + description: Describes the result of uploading an image resource + example: + code: 0 + type: type + message: message + properties: + code: + format: int32 + type: integer + type: + type: string + message: + type: string + title: An uploaded response + type: object + inline_object: + properties: + name: + description: Updated name of the pet + type: string + status: + description: Updated status of the pet + type: string + type: object + inline_object_1: + properties: + additionalMetadata: + description: Additional data to pass to server + type: string + file: + description: file to upload + format: binary + type: string + type: object + 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 + api_key: + in: header + name: api_key + type: apiKey diff --git a/samples/server/petstore/go-chi-server/go.mod b/samples/server/petstore/go-chi-server/go.mod new file mode 100644 index 00000000000..fa1221d2bed --- /dev/null +++ b/samples/server/petstore/go-chi-server/go.mod @@ -0,0 +1,5 @@ +module github.com/GIT_USER_ID/GIT_REPO_ID + +go 1.13 + +require github.com/go-chi/chi/v5 v5.0.3 diff --git a/samples/server/petstore/go-chi-server/go/api.go b/samples/server/petstore/go-chi-server/go/api.go new file mode 100644 index 00000000000..64321a00b2e --- /dev/null +++ b/samples/server/petstore/go-chi-server/go/api.go @@ -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. + * + * API version: 1.0.0 + * Generated by: OpenAPI Generator (https://openapi-generator.tech) + */ + +package petstoreserver + +import ( + "context" + "net/http" + "os" +) + + + +// PetApiRouter defines the required methods for binding the api requests to a responses for the PetApi +// The PetApiRouter implementation should parse necessary information from the http request, +// pass the data to a PetApiServicer to perform the required actions, then write the service results to the http response. +type PetApiRouter interface { + AddPet(http.ResponseWriter, *http.Request) + DeletePet(http.ResponseWriter, *http.Request) + FindPetsByStatus(http.ResponseWriter, *http.Request) + FindPetsByTags(http.ResponseWriter, *http.Request) + GetPetById(http.ResponseWriter, *http.Request) + UpdatePet(http.ResponseWriter, *http.Request) + UpdatePetWithForm(http.ResponseWriter, *http.Request) + UploadFile(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, +// pass the data to a StoreApiServicer to perform the required actions, then write the service results to the http response. +type StoreApiRouter interface { + DeleteOrder(http.ResponseWriter, *http.Request) + GetInventory(http.ResponseWriter, *http.Request) + GetOrderById(http.ResponseWriter, *http.Request) + PlaceOrder(http.ResponseWriter, *http.Request) +} +// UserApiRouter defines the required methods for binding the api requests to a responses for the UserApi +// The UserApiRouter implementation should parse necessary information from the http request, +// pass the data to a UserApiServicer to perform the required actions, then write the service results to the http response. +type UserApiRouter interface { + CreateUser(http.ResponseWriter, *http.Request) + CreateUsersWithArrayInput(http.ResponseWriter, *http.Request) + CreateUsersWithListInput(http.ResponseWriter, *http.Request) + DeleteUser(http.ResponseWriter, *http.Request) + GetUserByName(http.ResponseWriter, *http.Request) + LoginUser(http.ResponseWriter, *http.Request) + LogoutUser(http.ResponseWriter, *http.Request) + UpdateUser(http.ResponseWriter, *http.Request) +} + + +// PetApiServicer defines the api actions for the PetApi service +// This interface intended to stay up to date with the openapi yaml used to generate it, +// while the service implementation can ignored with the .openapi-generator-ignore file +// and updated with the logic required for the API. +type PetApiServicer interface { + AddPet(context.Context, Pet) (ImplResponse, error) + DeletePet(context.Context, int64, string) (ImplResponse, error) + FindPetsByStatus(context.Context, []string) (ImplResponse, error) + FindPetsByTags(context.Context, []string) (ImplResponse, error) + GetPetById(context.Context, int64) (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) +} + + +// StoreApiServicer defines the api actions for the StoreApi service +// This interface intended to stay up to date with the openapi yaml used to generate it, +// while the service implementation can ignored with the .openapi-generator-ignore file +// and updated with the logic required for the API. +type StoreApiServicer interface { + DeleteOrder(context.Context, string) (ImplResponse, error) + GetInventory(context.Context) (ImplResponse, error) + GetOrderById(context.Context, int64) (ImplResponse, error) + PlaceOrder(context.Context, Order) (ImplResponse, error) +} + + +// UserApiServicer defines the api actions for the UserApi service +// This interface intended to stay up to date with the openapi yaml used to generate it, +// while the service implementation can ignored with the .openapi-generator-ignore file +// and updated with the logic required for the API. +type UserApiServicer interface { + CreateUser(context.Context, User) (ImplResponse, error) + CreateUsersWithArrayInput(context.Context, []User) (ImplResponse, error) + CreateUsersWithListInput(context.Context, []User) (ImplResponse, error) + DeleteUser(context.Context, string) (ImplResponse, error) + GetUserByName(context.Context, string) (ImplResponse, error) + LoginUser(context.Context, string, string) (ImplResponse, error) + LogoutUser(context.Context) (ImplResponse, error) + UpdateUser(context.Context, string, User) (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 new file mode 100644 index 00000000000..6d964844301 --- /dev/null +++ b/samples/server/petstore/go-chi-server/go/api_pet.go @@ -0,0 +1,242 @@ +/* + * 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 ( + "encoding/json" + "net/http" + "strings" + + "github.com/go-chi/chi/v5" +) + +// A PetApiController binds http requests to an api service and writes the service results to the http response +type PetApiController struct { + service PetApiServicer +} + +// NewPetApiController creates a default api controller +func NewPetApiController(s PetApiServicer) Router { + return &PetApiController{service: s} +} + +// Routes returns all of the api route for the PetApiController +func (c *PetApiController) Routes() Routes { + return Routes{ + { + "AddPet", + strings.ToUpper("Post"), + "/v2/pet", + c.AddPet, + }, + { + "DeletePet", + strings.ToUpper("Delete"), + "/v2/pet/{petId}", + c.DeletePet, + }, + { + "FindPetsByStatus", + strings.ToUpper("Get"), + "/v2/pet/findByStatus", + c.FindPetsByStatus, + }, + { + "FindPetsByTags", + strings.ToUpper("Get"), + "/v2/pet/findByTags", + c.FindPetsByTags, + }, + { + "GetPetById", + strings.ToUpper("Get"), + "/v2/pet/{petId}", + c.GetPetById, + }, + { + "UpdatePet", + strings.ToUpper("Put"), + "/v2/pet", + c.UpdatePet, + }, + { + "UpdatePetWithForm", + strings.ToUpper("Post"), + "/v2/pet/{petId}", + c.UpdatePetWithForm, + }, + { + "UploadFile", + strings.ToUpper("Post"), + "/v2/pet/{petId}/uploadImage", + c.UploadFile, + }, + } +} + +// AddPet - Add a new pet to the store +func (c *PetApiController) AddPet(w http.ResponseWriter, r *http.Request) { + pet := &Pet{} + if err := json.NewDecoder(r.Body).Decode(&pet); err != nil { + w.WriteHeader(http.StatusBadRequest) + return + } + result, err := c.service.AddPet(r.Context(), *pet) + // If an error occurred, encode the error with the status code + if err != nil { + EncodeJSONResponse(err.Error(), &result.Code, result.Headers, w) + return + } + // If no error, encode the body and the result code + EncodeJSONResponse(result.Body, &result.Code, result.Headers, w) + +} + +// DeletePet - Deletes a pet +func (c *PetApiController) DeletePet(w http.ResponseWriter, r *http.Request) { + petId, err := parseInt64Parameter(chi.URLParam(r, "petId"), true) + if err != nil { + w.WriteHeader(http.StatusBadRequest) + return + } + + apiKey := r.Header.Get("api_key") + result, err := c.service.DeletePet(r.Context(), petId, apiKey) + // If an error occurred, encode the error with the status code + if err != nil { + EncodeJSONResponse(err.Error(), &result.Code, result.Headers, w) + 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() + status := strings.Split(query.Get("status"), ",") + result, err := c.service.FindPetsByStatus(r.Context(), status) + // If an error occurred, encode the error with the status code + if err != nil { + EncodeJSONResponse(err.Error(), &result.Code, result.Headers, w) + return + } + // If no error, encode the body and the result code + EncodeJSONResponse(result.Body, &result.Code, result.Headers, w) + +} + +// FindPetsByTags - Finds Pets by tags +func (c *PetApiController) FindPetsByTags(w http.ResponseWriter, r *http.Request) { + query := r.URL.Query() + tags := strings.Split(query.Get("tags"), ",") + result, err := c.service.FindPetsByTags(r.Context(), tags) + // If an error occurred, encode the error with the status code + if err != nil { + EncodeJSONResponse(err.Error(), &result.Code, result.Headers, w) + return + } + // If no error, encode the body and the result code + EncodeJSONResponse(result.Body, &result.Code, result.Headers, w) + +} + +// GetPetById - Find pet by ID +func (c *PetApiController) GetPetById(w http.ResponseWriter, r *http.Request) { + petId, err := parseInt64Parameter(chi.URLParam(r, "petId"), true) + if err != nil { + w.WriteHeader(http.StatusBadRequest) + return + } + + result, err := c.service.GetPetById(r.Context(), petId) + // If an error occurred, encode the error with the status code + if err != nil { + EncodeJSONResponse(err.Error(), &result.Code, result.Headers, w) + 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) { + pet := &Pet{} + if err := json.NewDecoder(r.Body).Decode(&pet); err != nil { + w.WriteHeader(http.StatusBadRequest) + return + } + result, err := c.service.UpdatePet(r.Context(), *pet) + // If an error occurred, encode the error with the status code + if err != nil { + EncodeJSONResponse(err.Error(), &result.Code, result.Headers, w) + return + } + // If no error, encode the body and the result code + EncodeJSONResponse(result.Body, &result.Code, result.Headers, w) + +} + +// UpdatePetWithForm - Updates a pet in the store with form data +func (c *PetApiController) UpdatePetWithForm(w http.ResponseWriter, r *http.Request) { + if err := r.ParseForm(); err != nil { + w.WriteHeader(http.StatusBadRequest) + return + } + petId, err := parseInt64Parameter(chi.URLParam(r, "petId"), true) + if err != nil { + w.WriteHeader(http.StatusBadRequest) + return + } + + name := r.FormValue("name") + status := r.FormValue("status") + result, err := c.service.UpdatePetWithForm(r.Context(), petId, name, status) + // If an error occurred, encode the error with the status code + if err != nil { + EncodeJSONResponse(err.Error(), &result.Code, result.Headers, w) + return + } + // If no error, encode the body and the result code + EncodeJSONResponse(result.Body, &result.Code, result.Headers, w) + +} + +// UploadFile - uploads an image +func (c *PetApiController) UploadFile(w http.ResponseWriter, r *http.Request) { + if err := r.ParseMultipartForm(32 << 20); err != nil { + w.WriteHeader(http.StatusBadRequest) + return + } + petId, err := parseInt64Parameter(chi.URLParam(r, "petId"), true) + if err != nil { + w.WriteHeader(http.StatusBadRequest) + return + } + + additionalMetadata := r.FormValue("additionalMetadata") + + file, err := ReadFormFileToTempFile(r, "file") + if err != nil { + w.WriteHeader(http.StatusBadRequest) + return + } + result, err := c.service.UploadFile(r.Context(), petId, additionalMetadata, file) + // If an error occurred, encode the error with the status code + if err != nil { + EncodeJSONResponse(err.Error(), &result.Code, result.Headers, w) + return + } + // If no error, encode the body and the result code + EncodeJSONResponse(result.Body, &result.Code, result.Headers, w) + +} 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 new file mode 100644 index 00000000000..d5f272f37a7 --- /dev/null +++ b/samples/server/petstore/go-chi-server/go/api_pet_service.go @@ -0,0 +1,141 @@ +/* + * 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 ( + "context" + "net/http" + "errors" + "os" +) + +// PetApiService is a service that implents the logic for the PetApiServicer +// This service should implement the business logic for every endpoint for the PetApi API. +// Include any external packages or services that will be required by this service. +type PetApiService struct { +} + +// NewPetApiService creates a default api service +func NewPetApiService() PetApiServicer { + return &PetApiService{} +} + +// AddPet - Add a new pet to the store +func (s *PetApiService) AddPet(ctx context.Context, pet Pet) (ImplResponse, error) { + // TODO - update AddPet 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(405, {}) or use other options such as http.Ok ... + //return Response(405, nil),nil + + return Response(http.StatusNotImplemented, nil), errors.New("AddPet method not implemented") +} + +// DeletePet - Deletes a pet +func (s *PetApiService) DeletePet(ctx context.Context, petId int64, apiKey string) (ImplResponse, error) { + // TODO - update DeletePet 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(400, {}) or use other options such as http.Ok ... + //return Response(400, nil),nil + + return Response(http.StatusNotImplemented, nil), errors.New("DeletePet method not implemented") +} + +// FindPetsByStatus - Finds Pets by status +func (s *PetApiService) FindPetsByStatus(ctx context.Context, status []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. + + //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("FindPetsByStatus method not implemented") +} + +// FindPetsByTags - Finds Pets by tags +func (s *PetApiService) FindPetsByTags(ctx context.Context, tags []string) (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. + + //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("FindPetsByTags method not implemented") +} + +// GetPetById - Find pet by ID +func (s *PetApiService) GetPetById(ctx context.Context, petId int64) (ImplResponse, error) { + // TODO - update GetPetById 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 + + //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("GetPetById 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. + // 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 + + //TODO: Uncomment the next line to return response Response(404, {}) or use other options such as http.Ok ... + //return Response(404, nil),nil + + //TODO: Uncomment the next line to return response Response(405, {}) or use other options such as http.Ok ... + //return Response(405, nil),nil + + return Response(http.StatusNotImplemented, nil), errors.New("UpdatePet method not implemented") +} + +// UpdatePetWithForm - Updates a pet in the store with form data +func (s *PetApiService) UpdatePetWithForm(ctx context.Context, petId int64, name string, status string) (ImplResponse, error) { + // TODO - update UpdatePetWithForm 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(405, {}) or use other options such as http.Ok ... + //return Response(405, nil),nil + + return Response(http.StatusNotImplemented, nil), errors.New("UpdatePetWithForm method not implemented") +} + +// UploadFile - uploads an image +func (s *PetApiService) UploadFile(ctx context.Context, petId int64, additionalMetadata 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. + + //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("UploadFile 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 new file mode 100644 index 00000000000..33b3b85494f --- /dev/null +++ b/samples/server/petstore/go-chi-server/go/api_store.go @@ -0,0 +1,123 @@ +/* + * 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 ( + "encoding/json" + "net/http" + "strings" + + "github.com/go-chi/chi/v5" +) + +// A StoreApiController binds http requests to an api service and writes the service results to the http response +type StoreApiController struct { + service StoreApiServicer +} + +// NewStoreApiController creates a default api controller +func NewStoreApiController(s StoreApiServicer) Router { + return &StoreApiController{service: s} +} + +// Routes returns all of the api route for the StoreApiController +func (c *StoreApiController) Routes() Routes { + return Routes{ + { + "DeleteOrder", + strings.ToUpper("Delete"), + "/v2/store/order/{orderId}", + c.DeleteOrder, + }, + { + "GetInventory", + strings.ToUpper("Get"), + "/v2/store/inventory", + c.GetInventory, + }, + { + "GetOrderById", + strings.ToUpper("Get"), + "/v2/store/order/{orderId}", + c.GetOrderById, + }, + { + "PlaceOrder", + strings.ToUpper("Post"), + "/v2/store/order", + c.PlaceOrder, + }, + } +} + +// DeleteOrder - Delete purchase order by ID +func (c *StoreApiController) DeleteOrder(w http.ResponseWriter, r *http.Request) { + orderId := chi.URLParam(r, "orderId") + + result, err := c.service.DeleteOrder(r.Context(), orderId) + // If an error occurred, encode the error with the status code + if err != nil { + EncodeJSONResponse(err.Error(), &result.Code, result.Headers, w) + return + } + // If no error, encode the body and the result code + EncodeJSONResponse(result.Body, &result.Code, result.Headers, w) + +} + +// GetInventory - Returns pet inventories by status +func (c *StoreApiController) GetInventory(w http.ResponseWriter, r *http.Request) { + result, err := c.service.GetInventory(r.Context()) + // If an error occurred, encode the error with the status code + if err != nil { + EncodeJSONResponse(err.Error(), &result.Code, result.Headers, w) + return + } + // If no error, encode the body and the result code + EncodeJSONResponse(result.Body, &result.Code, result.Headers, w) + +} + +// GetOrderById - Find purchase order by ID +func (c *StoreApiController) GetOrderById(w http.ResponseWriter, r *http.Request) { + orderId, err := parseInt64Parameter(chi.URLParam(r, "orderId"), true) + if err != nil { + w.WriteHeader(http.StatusBadRequest) + return + } + + result, err := c.service.GetOrderById(r.Context(), orderId) + // If an error occurred, encode the error with the status code + if err != nil { + EncodeJSONResponse(err.Error(), &result.Code, result.Headers, w) + return + } + // If no error, encode the body and the result code + EncodeJSONResponse(result.Body, &result.Code, result.Headers, w) + +} + +// PlaceOrder - Place an order for a pet +func (c *StoreApiController) PlaceOrder(w http.ResponseWriter, r *http.Request) { + order := &Order{} + if err := json.NewDecoder(r.Body).Decode(&order); err != nil { + w.WriteHeader(http.StatusBadRequest) + return + } + result, err := c.service.PlaceOrder(r.Context(), *order) + // If an error occurred, encode the error with the status code + if err != nil { + EncodeJSONResponse(err.Error(), &result.Code, result.Headers, w) + return + } + // If no error, encode the body and the result code + EncodeJSONResponse(result.Body, &result.Code, result.Headers, w) + +} diff --git a/samples/server/petstore/go-chi-server/go/api_store_service.go b/samples/server/petstore/go-chi-server/go/api_store_service.go new file mode 100644 index 00000000000..27da55939a3 --- /dev/null +++ b/samples/server/petstore/go-chi-server/go/api_store_service.go @@ -0,0 +1,84 @@ +/* + * 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 ( + "context" + "net/http" + "errors" +) + +// StoreApiService is a service that implents the logic for the StoreApiServicer +// This service should implement the business logic for every endpoint for the StoreApi API. +// Include any external packages or services that will be required by this service. +type StoreApiService struct { +} + +// NewStoreApiService creates a default api service +func NewStoreApiService() StoreApiServicer { + return &StoreApiService{} +} + +// DeleteOrder - Delete purchase order by ID +func (s *StoreApiService) DeleteOrder(ctx context.Context, orderId string) (ImplResponse, error) { + // TODO - update DeleteOrder with the required logic for this service method. + // Add api_store_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(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("DeleteOrder method not implemented") +} + +// GetInventory - Returns pet inventories by status +func (s *StoreApiService) GetInventory(ctx context.Context) (ImplResponse, error) { + // TODO - update GetInventory with the required logic for this service method. + // Add api_store_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, map[string]int32{}) or use other options such as http.Ok ... + //return Response(200, map[string]int32{}), nil + + return Response(http.StatusNotImplemented, nil), errors.New("GetInventory method not implemented") +} + +// GetOrderById - Find purchase order by ID +func (s *StoreApiService) GetOrderById(ctx context.Context, orderId int64) (ImplResponse, error) { + // TODO - update GetOrderById with the required logic for this service method. + // Add api_store_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, Order{}) or use other options such as http.Ok ... + //return Response(200, Order{}), 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("GetOrderById method not implemented") +} + +// PlaceOrder - Place an order for a pet +func (s *StoreApiService) PlaceOrder(ctx context.Context, order Order) (ImplResponse, error) { + // TODO - update PlaceOrder with the required logic for this service method. + // Add api_store_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, Order{}) or use other options such as http.Ok ... + //return Response(200, Order{}), 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("PlaceOrder method not implemented") +} + diff --git a/samples/server/petstore/go-chi-server/go/api_user.go b/samples/server/petstore/go-chi-server/go/api_user.go new file mode 100644 index 00000000000..46f6ae9d90f --- /dev/null +++ b/samples/server/petstore/go-chi-server/go/api_user.go @@ -0,0 +1,215 @@ +/* + * 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 ( + "encoding/json" + "net/http" + "strings" + + "github.com/go-chi/chi/v5" +) + +// A UserApiController binds http requests to an api service and writes the service results to the http response +type UserApiController struct { + service UserApiServicer +} + +// NewUserApiController creates a default api controller +func NewUserApiController(s UserApiServicer) Router { + return &UserApiController{service: s} +} + +// Routes returns all of the api route for the UserApiController +func (c *UserApiController) Routes() Routes { + return Routes{ + { + "CreateUser", + strings.ToUpper("Post"), + "/v2/user", + c.CreateUser, + }, + { + "CreateUsersWithArrayInput", + strings.ToUpper("Post"), + "/v2/user/createWithArray", + c.CreateUsersWithArrayInput, + }, + { + "CreateUsersWithListInput", + strings.ToUpper("Post"), + "/v2/user/createWithList", + c.CreateUsersWithListInput, + }, + { + "DeleteUser", + strings.ToUpper("Delete"), + "/v2/user/{username}", + c.DeleteUser, + }, + { + "GetUserByName", + strings.ToUpper("Get"), + "/v2/user/{username}", + c.GetUserByName, + }, + { + "LoginUser", + strings.ToUpper("Get"), + "/v2/user/login", + c.LoginUser, + }, + { + "LogoutUser", + strings.ToUpper("Get"), + "/v2/user/logout", + c.LogoutUser, + }, + { + "UpdateUser", + strings.ToUpper("Put"), + "/v2/user/{username}", + c.UpdateUser, + }, + } +} + +// CreateUser - Create user +func (c *UserApiController) CreateUser(w http.ResponseWriter, r *http.Request) { + user := &User{} + if err := json.NewDecoder(r.Body).Decode(&user); err != nil { + w.WriteHeader(http.StatusBadRequest) + return + } + result, err := c.service.CreateUser(r.Context(), *user) + // If an error occurred, encode the error with the status code + if err != nil { + EncodeJSONResponse(err.Error(), &result.Code, result.Headers, w) + return + } + // If no error, encode the body and the result code + EncodeJSONResponse(result.Body, &result.Code, result.Headers, w) + +} + +// CreateUsersWithArrayInput - Creates list of users with given input array +func (c *UserApiController) CreateUsersWithArrayInput(w http.ResponseWriter, r *http.Request) { + user := &[]User{} + if err := json.NewDecoder(r.Body).Decode(&user); err != nil { + w.WriteHeader(http.StatusBadRequest) + return + } + result, err := c.service.CreateUsersWithArrayInput(r.Context(), *user) + // If an error occurred, encode the error with the status code + if err != nil { + EncodeJSONResponse(err.Error(), &result.Code, result.Headers, w) + return + } + // If no error, encode the body and the result code + EncodeJSONResponse(result.Body, &result.Code, result.Headers, w) + +} + +// CreateUsersWithListInput - Creates list of users with given input array +func (c *UserApiController) CreateUsersWithListInput(w http.ResponseWriter, r *http.Request) { + user := &[]User{} + if err := json.NewDecoder(r.Body).Decode(&user); err != nil { + w.WriteHeader(http.StatusBadRequest) + return + } + result, err := c.service.CreateUsersWithListInput(r.Context(), *user) + // If an error occurred, encode the error with the status code + if err != nil { + EncodeJSONResponse(err.Error(), &result.Code, result.Headers, w) + return + } + // If no error, encode the body and the result code + EncodeJSONResponse(result.Body, &result.Code, result.Headers, w) + +} + +// DeleteUser - Delete user +func (c *UserApiController) DeleteUser(w http.ResponseWriter, r *http.Request) { + username := chi.URLParam(r, "username") + + result, err := c.service.DeleteUser(r.Context(), username) + // If an error occurred, encode the error with the status code + if err != nil { + EncodeJSONResponse(err.Error(), &result.Code, result.Headers, w) + return + } + // If no error, encode the body and the result code + EncodeJSONResponse(result.Body, &result.Code, result.Headers, w) + +} + +// GetUserByName - Get user by user name +func (c *UserApiController) GetUserByName(w http.ResponseWriter, r *http.Request) { + username := chi.URLParam(r, "username") + + result, err := c.service.GetUserByName(r.Context(), username) + // If an error occurred, encode the error with the status code + if err != nil { + EncodeJSONResponse(err.Error(), &result.Code, result.Headers, w) + return + } + // If no error, encode the body and the result code + EncodeJSONResponse(result.Body, &result.Code, result.Headers, w) + +} + +// LoginUser - Logs user into the system +func (c *UserApiController) LoginUser(w http.ResponseWriter, r *http.Request) { + query := r.URL.Query() + username := query.Get("username") + password := query.Get("password") + result, err := c.service.LoginUser(r.Context(), username, password) + // If an error occurred, encode the error with the status code + if err != nil { + EncodeJSONResponse(err.Error(), &result.Code, result.Headers, w) + return + } + // If no error, encode the body and the result code + EncodeJSONResponse(result.Body, &result.Code, result.Headers, w) + +} + +// LogoutUser - Logs out current logged in user session +func (c *UserApiController) LogoutUser(w http.ResponseWriter, r *http.Request) { + result, err := c.service.LogoutUser(r.Context()) + // If an error occurred, encode the error with the status code + if err != nil { + EncodeJSONResponse(err.Error(), &result.Code, result.Headers, w) + return + } + // If no error, encode the body and the result code + EncodeJSONResponse(result.Body, &result.Code, result.Headers, w) + +} + +// UpdateUser - Updated user +func (c *UserApiController) UpdateUser(w http.ResponseWriter, r *http.Request) { + username := chi.URLParam(r, "username") + + user := &User{} + if err := json.NewDecoder(r.Body).Decode(&user); err != nil { + w.WriteHeader(http.StatusBadRequest) + return + } + result, err := c.service.UpdateUser(r.Context(), username, *user) + // If an error occurred, encode the error with the status code + if err != nil { + EncodeJSONResponse(err.Error(), &result.Code, result.Headers, w) + return + } + // If no error, encode the body and the result code + EncodeJSONResponse(result.Body, &result.Code, result.Headers, w) + +} diff --git a/samples/server/petstore/go-chi-server/go/api_user_service.go b/samples/server/petstore/go-chi-server/go/api_user_service.go new file mode 100644 index 00000000000..c14d96ab368 --- /dev/null +++ b/samples/server/petstore/go-chi-server/go/api_user_service.go @@ -0,0 +1,131 @@ +/* + * 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 ( + "context" + "net/http" + "errors" +) + +// UserApiService is a service that implents the logic for the UserApiServicer +// This service should implement the business logic for every endpoint for the UserApi API. +// Include any external packages or services that will be required by this service. +type UserApiService struct { +} + +// NewUserApiService creates a default api service +func NewUserApiService() UserApiServicer { + return &UserApiService{} +} + +// CreateUser - Create user +func (s *UserApiService) CreateUser(ctx context.Context, user User) (ImplResponse, error) { + // TODO - update CreateUser with the required logic for this service method. + // Add api_user_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(0, {}) or use other options such as http.Ok ... + //return Response(0, nil),nil + + return Response(http.StatusNotImplemented, nil), errors.New("CreateUser method not implemented") +} + +// CreateUsersWithArrayInput - Creates list of users with given input array +func (s *UserApiService) CreateUsersWithArrayInput(ctx context.Context, user []User) (ImplResponse, error) { + // TODO - update CreateUsersWithArrayInput with the required logic for this service method. + // Add api_user_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(0, {}) or use other options such as http.Ok ... + //return Response(0, nil),nil + + return Response(http.StatusNotImplemented, nil), errors.New("CreateUsersWithArrayInput method not implemented") +} + +// CreateUsersWithListInput - Creates list of users with given input array +func (s *UserApiService) CreateUsersWithListInput(ctx context.Context, user []User) (ImplResponse, error) { + // TODO - update CreateUsersWithListInput with the required logic for this service method. + // Add api_user_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(0, {}) or use other options such as http.Ok ... + //return Response(0, nil),nil + + return Response(http.StatusNotImplemented, nil), errors.New("CreateUsersWithListInput method not implemented") +} + +// DeleteUser - Delete user +func (s *UserApiService) DeleteUser(ctx context.Context, username string) (ImplResponse, error) { + // TODO - update DeleteUser with the required logic for this service method. + // Add api_user_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(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("DeleteUser method not implemented") +} + +// GetUserByName - Get user by user name +func (s *UserApiService) GetUserByName(ctx context.Context, username string) (ImplResponse, error) { + // TODO - update GetUserByName with the required logic for this service method. + // Add api_user_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, User{}) or use other options such as http.Ok ... + //return Response(200, User{}), 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("GetUserByName method not implemented") +} + +// LoginUser - Logs user into the system +func (s *UserApiService) LoginUser(ctx context.Context, username string, password string) (ImplResponse, error) { + // TODO - update LoginUser with the required logic for this service method. + // Add api_user_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, string{}) or use other options such as http.Ok ... + //return Response(200, string{}), 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("LoginUser method not implemented") +} + +// LogoutUser - Logs out current logged in user session +func (s *UserApiService) LogoutUser(ctx context.Context) (ImplResponse, error) { + // TODO - update LogoutUser with the required logic for this service method. + // Add api_user_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(0, {}) or use other options such as http.Ok ... + //return Response(0, nil),nil + + return Response(http.StatusNotImplemented, nil), errors.New("LogoutUser method not implemented") +} + +// UpdateUser - Updated user +func (s *UserApiService) UpdateUser(ctx context.Context, username string, user User) (ImplResponse, error) { + // TODO - update UpdateUser with the required logic for this service method. + // Add api_user_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(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("UpdateUser method not implemented") +} + diff --git a/samples/server/petstore/go-chi-server/go/helpers.go b/samples/server/petstore/go-chi-server/go/helpers.go new file mode 100644 index 00000000000..179ee893f7f --- /dev/null +++ b/samples/server/petstore/go-chi-server/go/helpers.go @@ -0,0 +1,28 @@ +/* + * 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 + +//Response return a ImplResponse struct filled +func Response(code int, body interface{}) ImplResponse { + return ImplResponse { + Code: code, + Headers: nil, + Body: body, + } +} + +//ResponseWithHeaders return a ImplResponse struct filled, including headers +func ResponseWithHeaders(code int, headers map[string][]string, body interface{}) ImplResponse { + return ImplResponse { + Code: code, + Headers: headers, + Body: body, + } +} diff --git a/samples/server/petstore/go-chi-server/go/impl.go b/samples/server/petstore/go-chi-server/go/impl.go new file mode 100644 index 00000000000..1da96f41252 --- /dev/null +++ b/samples/server/petstore/go-chi-server/go/impl.go @@ -0,0 +1,17 @@ +/* + * 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 + +//Implementation response defines an error code with the associated body +type ImplResponse struct { + Code int + Headers map[string][]string + Body interface{} +} diff --git a/samples/server/petstore/go-chi-server/go/logger.go b/samples/server/petstore/go-chi-server/go/logger.go new file mode 100644 index 00000000000..08cc0ea3f1d --- /dev/null +++ b/samples/server/petstore/go-chi-server/go/logger.go @@ -0,0 +1,32 @@ +/* + * 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 ( + "log" + "net/http" + "time" +) + +func Logger(inner http.Handler, name string) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + start := time.Now() + + inner.ServeHTTP(w, r) + + log.Printf( + "%s %s %s %s", + r.Method, + r.RequestURI, + name, + time.Since(start), + ) + }) +} diff --git a/samples/server/petstore/go-chi-server/go/model_api_response.go b/samples/server/petstore/go-chi-server/go/model_api_response.go new file mode 100644 index 00000000000..2379e169080 --- /dev/null +++ b/samples/server/petstore/go-chi-server/go/model_api_response.go @@ -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. + * + * API version: 1.0.0 + * Generated by: OpenAPI Generator (https://openapi-generator.tech) + */ + +package petstoreserver + +// ApiResponse - Describes the result of uploading an image resource +type ApiResponse struct { + + Code int32 `json:"code,omitempty"` + + Type string `json:"type,omitempty"` + + Message string `json:"message,omitempty"` +} diff --git a/samples/server/petstore/go-chi-server/go/model_category.go b/samples/server/petstore/go-chi-server/go/model_category.go new file mode 100644 index 00000000000..5e6f9d247fa --- /dev/null +++ b/samples/server/petstore/go-chi-server/go/model_category.go @@ -0,0 +1,18 @@ +/* + * 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 + +// Category - A category for a pet +type Category struct { + + Id int64 `json:"id,omitempty"` + + Name string `json:"name,omitempty"` +} diff --git a/samples/server/petstore/go-chi-server/go/model_order.go b/samples/server/petstore/go-chi-server/go/model_order.go new file mode 100644 index 00000000000..a9d8dbb7957 --- /dev/null +++ b/samples/server/petstore/go-chi-server/go/model_order.go @@ -0,0 +1,31 @@ +/* + * 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 ( + "time" +) + +// Order - An order for a pets from the pet store +type Order struct { + + Id int64 `json:"id,omitempty"` + + PetId int64 `json:"petId,omitempty"` + + Quantity int32 `json:"quantity,omitempty"` + + ShipDate time.Time `json:"shipDate,omitempty"` + + // Order Status + Status string `json:"status,omitempty"` + + Complete bool `json:"complete,omitempty"` +} diff --git a/samples/server/petstore/go-chi-server/go/model_pet.go b/samples/server/petstore/go-chi-server/go/model_pet.go new file mode 100644 index 00000000000..fb206487ab0 --- /dev/null +++ b/samples/server/petstore/go-chi-server/go/model_pet.go @@ -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. + * + * API version: 1.0.0 + * Generated by: OpenAPI Generator (https://openapi-generator.tech) + */ + +package petstoreserver + +// 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 + Status string `json:"status,omitempty"` +} diff --git a/samples/server/petstore/go-chi-server/go/model_tag.go b/samples/server/petstore/go-chi-server/go/model_tag.go new file mode 100644 index 00000000000..2fb07fb32c4 --- /dev/null +++ b/samples/server/petstore/go-chi-server/go/model_tag.go @@ -0,0 +1,18 @@ +/* + * 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 + +// Tag - A tag for a pet +type Tag struct { + + Id int64 `json:"id,omitempty"` + + Name string `json:"name,omitempty"` +} diff --git a/samples/server/petstore/go-chi-server/go/model_user.go b/samples/server/petstore/go-chi-server/go/model_user.go new file mode 100644 index 00000000000..8f40d0ac04c --- /dev/null +++ b/samples/server/petstore/go-chi-server/go/model_user.go @@ -0,0 +1,31 @@ +/* + * 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 + +// User - A User who is purchasing from the pet store +type User struct { + + Id int64 `json:"id,omitempty"` + + Username string `json:"username,omitempty"` + + FirstName string `json:"firstName,omitempty"` + + LastName string `json:"lastName,omitempty"` + + Email string `json:"email,omitempty"` + + Password string `json:"password,omitempty"` + + Phone string `json:"phone,omitempty"` + + // User Status + UserStatus int32 `json:"userStatus,omitempty"` +} diff --git a/samples/server/petstore/go-chi-server/go/routers.go b/samples/server/petstore/go-chi-server/go/routers.go new file mode 100644 index 00000000000..3213d5dde23 --- /dev/null +++ b/samples/server/petstore/go-chi-server/go/routers.go @@ -0,0 +1,221 @@ +/* + * 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 ( + "encoding/json" + "errors" + "github.com/go-chi/chi/v5" + "github.com/go-chi/chi/v5/middleware" + "io/ioutil" + "mime/multipart" + "net/http" + "os" + "strconv" + "strings" +) + +// A Route defines the parameters for an api endpoint +type Route struct { + Name string + Method string + Pattern string + HandlerFunc http.HandlerFunc +} + +// Routes are a collection of defined api endpoints +type Routes []Route + +// Router defines the required methods for retrieving api routes +type Router interface { + Routes() Routes +} + +const errMsgRequiredMissing = "required parameter is missing" + +// NewRouter creates a new router for any number of api routers +func NewRouter(routers ...Router) chi.Router { + router := chi.NewRouter() + router.Use(middleware.Logger) + for _, api := range routers { + for _, route := range api.Routes() { + var handler http.Handler + handler = route.HandlerFunc + router.Method(route.Method, route.Pattern, handler) + } + } + + return router +} + +// EncodeJSONResponse uses the json encoder to write an interface to the http response with an optional status code +func EncodeJSONResponse(i interface{}, status *int, headers map[string][]string, w http.ResponseWriter) error { + wHeader := w.Header() + if headers != nil { + for key, values := range headers { + for _, value := range values { + wHeader.Add(key, value) + } + } + } + wHeader.Set("Content-Type", "application/json; charset=UTF-8") + if status != nil { + w.WriteHeader(*status) + } else { + w.WriteHeader(http.StatusOK) + } + + return json.NewEncoder(w).Encode(i) +} + +// ReadFormFileToTempFile reads file data from a request form and writes it to a temporary file +func ReadFormFileToTempFile(r *http.Request, key string) (*os.File, error) { + _, fileHeader, err := r.FormFile(key) + if err != nil { + return nil, err + } + + return readFileHeaderToTempFile(fileHeader) +} + +// ReadFormFilesToTempFiles reads files array data from a request form and writes it to a temporary files +func ReadFormFilesToTempFiles(r *http.Request, key string) ([]*os.File, error) { + if err := r.ParseMultipartForm(32 << 20); err != nil { + return nil, err + } + + files := make([]*os.File, 0, len(r.MultipartForm.File[key])) + + for _, fileHeader := range r.MultipartForm.File[key] { + file, err := readFileHeaderToTempFile(fileHeader) + if err != nil { + return nil, err + } + + files = append(files, file) + } + + return files, nil +} + +// readFileHeaderToTempFile reads multipart.FileHeader and writes it to a temporary file +func readFileHeaderToTempFile(fileHeader *multipart.FileHeader) (*os.File, error) { + formFile, err := fileHeader.Open() + if err != nil { + return nil, err + } + + defer formFile.Close() + + fileBytes, err := ioutil.ReadAll(formFile) + if err != nil { + return nil, err + } + + file, err := ioutil.TempFile("", fileHeader.Filename) + if err != nil { + return nil, err + } + + defer file.Close() + + file.Write(fileBytes) + + return file, nil +} + +// parseInt64Parameter parses a string parameter to an int64. +func parseInt64Parameter(param string, required bool) (int64, error) { + if param == "" { + if required { + return 0, errors.New(errMsgRequiredMissing) + } + + return 0, nil + } + + return strconv.ParseInt(param, 10, 64) +} + +// parseInt32Parameter parses a string parameter to an int32. +func parseInt32Parameter(param string, required bool) (int32, error) { + if param == "" { + if required { + return 0, errors.New(errMsgRequiredMissing) + } + + return 0, nil + } + + val, err := strconv.ParseInt(param, 10, 32) + if err != nil { + return -1, err + } + + return int32(val), nil +} + +// parseBoolParameter parses a string parameter to a bool +func parseBoolParameter(param string) (bool, error) { + val, err := strconv.ParseBool(param) + if err != nil { + return false, err + } + + return bool(val), nil +} + +// parseInt64ArrayParameter parses a string parameter containing array of values to []int64. +func parseInt64ArrayParameter(param, delim string, required bool) ([]int64, error) { + if param == "" { + if required { + return nil, errors.New(errMsgRequiredMissing) + } + + return nil, nil + } + + str := strings.Split(param, delim) + ints := make([]int64, len(str)) + + for i, s := range str { + if v, err := strconv.ParseInt(s, 10, 64); err != nil { + return nil, err + } else { + ints[i] = v + } + } + + return ints, nil +} + +// parseInt32ArrayParameter parses a string parameter containing array of values to []int32. +func parseInt32ArrayParameter(param, delim string, required bool) ([]int32, error) { + if param == "" { + if required { + return nil, errors.New(errMsgRequiredMissing) + } + + return nil, nil + } + + str := strings.Split(param, delim) + ints := make([]int32, len(str)) + + for i, s := range str { + if v, err := strconv.ParseInt(s, 10, 32); err != nil { + return nil, err + } else { + ints[i] = int32(v) + } + } + + return ints, nil +} \ No newline at end of file diff --git a/samples/server/petstore/go-chi-server/main.go b/samples/server/petstore/go-chi-server/main.go new file mode 100644 index 00000000000..ddc5258297c --- /dev/null +++ b/samples/server/petstore/go-chi-server/main.go @@ -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. + * + * API version: 1.0.0 + * Generated by: OpenAPI Generator (https://openapi-generator.tech) + */ + +package main + +import ( + "log" + "net/http" + + petstoreserver "github.com/GIT_USER_ID/GIT_REPO_ID/go" +) + +func main() { + log.Printf("Server started") + + PetApiService := petstoreserver.NewPetApiService() + PetApiController := petstoreserver.NewPetApiController(PetApiService) + + StoreApiService := petstoreserver.NewStoreApiService() + StoreApiController := petstoreserver.NewStoreApiController(StoreApiService) + + UserApiService := petstoreserver.NewUserApiService() + UserApiController := petstoreserver.NewUserApiController(UserApiService) + + router := petstoreserver.NewRouter(PetApiController, StoreApiController, UserApiController) + + log.Fatal(http.ListenAndServe(":8080", router)) +} diff --git a/samples/server/petstore/go-echo-server/.openapi-generator/VERSION b/samples/server/petstore/go-echo-server/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/server/petstore/go-echo-server/.openapi-generator/VERSION +++ b/samples/server/petstore/go-echo-server/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/server/petstore/go-echo-server/pom.xml b/samples/server/petstore/go-echo-server/pom.xml index df4dbbf4702..5e7f03d3842 100644 --- a/samples/server/petstore/go-echo-server/pom.xml +++ b/samples/server/petstore/go-echo-server/pom.xml @@ -35,7 +35,6 @@ go - go mod download 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 5f68295fc19..e8415097f3a 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,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x 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 0a1432a6269..d0fbe840a1b 100644 --- a/samples/server/petstore/go-gin-api-server/go/routers.go +++ b/samples/server/petstore/go-gin-api-server/go/routers.go @@ -41,6 +41,8 @@ func NewRouter() *gin.Engine { router.POST(route.Pattern, route.HandlerFunc) case http.MethodPut: router.PUT(route.Pattern, route.HandlerFunc) + case http.MethodPatch: + router.PATCH(route.Pattern, route.HandlerFunc) case http.MethodDelete: router.DELETE(route.Pattern, route.HandlerFunc) } diff --git a/samples/server/petstore/haskell-servant/.openapi-generator/FILES b/samples/server/petstore/haskell-servant/.openapi-generator/FILES new file mode 100644 index 00000000000..405513c6811 --- /dev/null +++ b/samples/server/petstore/haskell-servant/.openapi-generator/FILES @@ -0,0 +1,6 @@ +README.md +Setup.hs +lib/OpenAPIPetstore/API.hs +lib/OpenAPIPetstore/Types.hs +openapi-petstore.cabal +stack.yaml diff --git a/samples/server/petstore/haskell-servant/.openapi-generator/VERSION b/samples/server/petstore/haskell-servant/.openapi-generator/VERSION index d99e7162d01..4b448de535c 100644 --- a/samples/server/petstore/haskell-servant/.openapi-generator/VERSION +++ b/samples/server/petstore/haskell-servant/.openapi-generator/VERSION @@ -1 +1 @@ -5.0.0-SNAPSHOT \ No newline at end of file +5.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/haskell-servant/lib/OpenAPIPetstore/API.hs b/samples/server/petstore/haskell-servant/lib/OpenAPIPetstore/API.hs index a70eb607c7a..751713adc78 100644 --- a/samples/server/petstore/haskell-servant/lib/OpenAPIPetstore/API.hs +++ b/samples/server/petstore/haskell-servant/lib/OpenAPIPetstore/API.hs @@ -14,8 +14,8 @@ -fno-warn-unused-binds -fno-warn-unused-imports -freduction-depth=328 #-} module OpenAPIPetstore.API - -- * Client and Server - ( Config(..) + ( -- * Client and Server + Config(..) , OpenAPIPetstoreBackend(..) , createOpenAPIPetstoreClient , runOpenAPIPetstoreServer @@ -137,26 +137,26 @@ formatSeparatedQueryList char = T.intercalate (T.singleton char) . map toQueryPa -- | Servant type-level API, generated from the OpenAPI spec for OpenAPIPetstore. type OpenAPIPetstoreAPI - = "pet" :> ReqBody '[JSON] Pet :> Verb 'POST 200 '[JSON] () -- 'addPet' route - :<|> "pet" :> Capture "petId" Integer :> Header "api_key" Text :> Verb 'DELETE 200 '[JSON] () -- 'deletePet' route + = "pet" :> ReqBody '[JSON] Pet :> Verb 'POST 200 '[JSON] NoContent -- 'addPet' route + :<|> "pet" :> Capture "petId" Integer :> Header "api_key" Text :> Verb 'DELETE 200 '[JSON] NoContent -- 'deletePet' route :<|> "pet" :> "findByStatus" :> QueryParam "status" (QueryList 'CommaSeparated (Text)) :> Verb 'GET 200 '[JSON] [Pet] -- 'findPetsByStatus' route :<|> "pet" :> "findByTags" :> QueryParam "tags" (QueryList 'CommaSeparated (Text)) :> Verb 'GET 200 '[JSON] [Pet] -- 'findPetsByTags' route :<|> "pet" :> Capture "petId" Integer :> Verb 'GET 200 '[JSON] Pet -- 'getPetById' route - :<|> "pet" :> ReqBody '[JSON] Pet :> Verb 'PUT 200 '[JSON] () -- 'updatePet' route - :<|> "pet" :> Capture "petId" Integer :> ReqBody '[FormUrlEncoded] FormUpdatePetWithForm :> Verb 'POST 200 '[JSON] () -- 'updatePetWithForm' route + :<|> "pet" :> ReqBody '[JSON] Pet :> Verb 'PUT 200 '[JSON] NoContent -- 'updatePet' route + :<|> "pet" :> Capture "petId" Integer :> ReqBody '[FormUrlEncoded] FormUpdatePetWithForm :> Verb 'POST 200 '[JSON] NoContent -- 'updatePetWithForm' route :<|> "pet" :> Capture "petId" Integer :> "uploadImage" :> ReqBody '[FormUrlEncoded] FormUploadFile :> Verb 'POST 200 '[JSON] ApiResponse -- 'uploadFile' route - :<|> "store" :> "order" :> Capture "orderId" Text :> Verb 'DELETE 200 '[JSON] () -- 'deleteOrder' route + :<|> "store" :> "order" :> Capture "orderId" Text :> Verb 'DELETE 200 '[JSON] NoContent -- 'deleteOrder' route :<|> "store" :> "inventory" :> Verb 'GET 200 '[JSON] ((Map.Map String Int)) -- 'getInventory' route :<|> "store" :> "order" :> Capture "orderId" Integer :> Verb 'GET 200 '[JSON] Order -- 'getOrderById' route :<|> "store" :> "order" :> ReqBody '[JSON] Order :> Verb 'POST 200 '[JSON] Order -- 'placeOrder' route - :<|> "user" :> ReqBody '[JSON] User :> Verb 'POST 200 '[JSON] () -- 'createUser' route - :<|> "user" :> "createWithArray" :> ReqBody '[JSON] [User] :> Verb 'POST 200 '[JSON] () -- 'createUsersWithArrayInput' route - :<|> "user" :> "createWithList" :> ReqBody '[JSON] [User] :> Verb 'POST 200 '[JSON] () -- 'createUsersWithListInput' route - :<|> "user" :> Capture "username" Text :> Verb 'DELETE 200 '[JSON] () -- 'deleteUser' route + :<|> "user" :> ReqBody '[JSON] User :> Verb 'POST 200 '[JSON] NoContent -- 'createUser' route + :<|> "user" :> "createWithArray" :> ReqBody '[JSON] [User] :> Verb 'POST 200 '[JSON] NoContent -- 'createUsersWithArrayInput' route + :<|> "user" :> "createWithList" :> ReqBody '[JSON] [User] :> Verb 'POST 200 '[JSON] NoContent -- 'createUsersWithListInput' route + :<|> "user" :> Capture "username" Text :> Verb 'DELETE 200 '[JSON] NoContent -- 'deleteUser' route :<|> "user" :> Capture "username" Text :> Verb 'GET 200 '[JSON] User -- 'getUserByName' route :<|> "user" :> "login" :> QueryParam "username" Text :> QueryParam "password" Text :> Verb 'GET 200 '[JSON] Text -- 'loginUser' route - :<|> "user" :> "logout" :> Verb 'GET 200 '[JSON] () -- 'logoutUser' route - :<|> "user" :> Capture "username" Text :> ReqBody '[JSON] User :> Verb 'PUT 200 '[JSON] () -- 'updateUser' route + :<|> "user" :> "logout" :> Verb 'GET 200 '[JSON] NoContent -- 'logoutUser' route + :<|> "user" :> Capture "username" Text :> ReqBody '[JSON] User :> Verb 'PUT 200 '[JSON] NoContent -- 'updateUser' route :<|> Raw @@ -177,26 +177,26 @@ newtype OpenAPIPetstoreClientError = OpenAPIPetstoreClientError ClientError -- is a backend that executes actions by sending HTTP requests (see @createOpenAPIPetstoreClient@). Alternatively, provided -- a backend, the API can be served using @runOpenAPIPetstoreMiddlewareServer@. data OpenAPIPetstoreBackend m = OpenAPIPetstoreBackend - { addPet :: Pet -> m (){- ^ -} - , deletePet :: Integer -> Maybe Text -> m (){- ^ -} + { addPet :: Pet -> m NoContent{- ^ -} + , deletePet :: Integer -> Maybe Text -> m NoContent{- ^ -} , findPetsByStatus :: Maybe [Text] -> m [Pet]{- ^ Multiple status values can be provided with comma separated strings -} , findPetsByTags :: Maybe [Text] -> m [Pet]{- ^ Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. -} , getPetById :: Integer -> m Pet{- ^ Returns a single pet -} - , updatePet :: Pet -> m (){- ^ -} - , updatePetWithForm :: Integer -> FormUpdatePetWithForm -> m (){- ^ -} + , updatePet :: Pet -> m NoContent{- ^ -} + , updatePetWithForm :: Integer -> FormUpdatePetWithForm -> m NoContent{- ^ -} , uploadFile :: Integer -> FormUploadFile -> m ApiResponse{- ^ -} - , deleteOrder :: Text -> m (){- ^ For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors -} + , deleteOrder :: Text -> m NoContent{- ^ For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors -} , getInventory :: m ((Map.Map String Int)){- ^ Returns a map of status codes to quantities -} , getOrderById :: Integer -> m Order{- ^ For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions -} , placeOrder :: Order -> m Order{- ^ -} - , createUser :: User -> m (){- ^ This can only be done by the logged in user. -} - , createUsersWithArrayInput :: [User] -> m (){- ^ -} - , createUsersWithListInput :: [User] -> m (){- ^ -} - , deleteUser :: Text -> m (){- ^ This can only be done by the logged in user. -} + , createUser :: User -> m NoContent{- ^ This can only be done by the logged in user. -} + , createUsersWithArrayInput :: [User] -> m NoContent{- ^ -} + , createUsersWithListInput :: [User] -> m NoContent{- ^ -} + , deleteUser :: Text -> m NoContent{- ^ This can only be done by the logged in user. -} , getUserByName :: Text -> m User{- ^ -} , loginUser :: Maybe Text -> Maybe Text -> m Text{- ^ -} - , logoutUser :: m (){- ^ -} - , updateUser :: Text -> User -> m (){- ^ This can only be done by the logged in user. -} + , logoutUser :: m NoContent{- ^ -} + , updateUser :: Text -> User -> m NoContent{- ^ This can only be done by the logged in user. -} } newtype OpenAPIPetstoreClient a = OpenAPIPetstoreClient diff --git a/samples/server/petstore/haskell-servant/lib/OpenAPIPetstore/Types.hs b/samples/server/petstore/haskell-servant/lib/OpenAPIPetstore/Types.hs index d4f84e4288f..855f7062f23 100644 --- a/samples/server/petstore/haskell-servant/lib/OpenAPIPetstore/Types.hs +++ b/samples/server/petstore/haskell-servant/lib/OpenAPIPetstore/Types.hs @@ -194,6 +194,7 @@ removeFieldLabelPrefix forParsing prefix = , ("~", "'Tilde") , ("?", "'Question_Mark") , (">=", "'Greater_Than_Or_Equal_To") + , ("~=", "'Tilde_Equal") ] mkCharReplacement (replaceStr, searchStr) = T.unpack . replacer (T.pack searchStr) (T.pack replaceStr) . T.pack replacer = diff --git a/samples/server/petstore/java-msf4j/.openapi-generator/VERSION b/samples/server/petstore/java-msf4j/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/server/petstore/java-msf4j/.openapi-generator/VERSION +++ b/samples/server/petstore/java-msf4j/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x 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 5f68295fc19..e8415097f3a 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,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x 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 5f68295fc19..e8415097f3a 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,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x 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 5f68295fc19..e8415097f3a 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,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x 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 5f68295fc19..e8415097f3a 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,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x 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 5f68295fc19..e8415097f3a 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,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x 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 5f68295fc19..e8415097f3a 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,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x 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 5f68295fc19..e8415097f3a 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,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x 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 5f68295fc19..e8415097f3a 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,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x 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 5f68295fc19..e8415097f3a 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,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x 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 5f68295fc19..e8415097f3a 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,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/server/petstore/java-play-framework/.openapi-generator/VERSION b/samples/server/petstore/java-play-framework/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/server/petstore/java-play-framework/.openapi-generator/VERSION +++ b/samples/server/petstore/java-play-framework/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/server/petstore/java-undertow/.openapi-generator/VERSION b/samples/server/petstore/java-undertow/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/server/petstore/java-undertow/.openapi-generator/VERSION +++ b/samples/server/petstore/java-undertow/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/server/petstore/java-undertow/pom.xml b/samples/server/petstore/java-undertow/pom.xml index 2382e40a66e..53ccffba47d 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.1.7 + 1.2.0 4.13 2.1.0-beta.124 1.4.0.Final diff --git a/samples/server/petstore/java-undertow/src/main/java/org/openapitools/handler/PathHandlerInterface.java b/samples/server/petstore/java-undertow/src/main/java/org/openapitools/handler/PathHandlerInterface.java index 41b91a89132..362ae244118 100644 --- a/samples/server/petstore/java-undertow/src/main/java/org/openapitools/handler/PathHandlerInterface.java +++ b/samples/server/petstore/java-undertow/src/main/java/org/openapitools/handler/PathHandlerInterface.java @@ -539,10 +539,10 @@ public interface PathHandlerInterface { *

    Response headers: [CodegenProperty{openApiType='integer', baseName='X-Rate-Limit', complexType='null', getter='getxRateLimit', setter='setxRateLimit', description='calls per hour allowed by the user', dataType='Integer', datatypeWithEnum='Integer', dataFormat='int32', name='xRateLimit', min='null', max='null', defaultValue='null', defaultValueWithParam=' = data.X-Rate-Limit;', baseType='Integer', containerType='null', title='null', unescapedDescription='calls per hour allowed by the user', maxLength=null, minLength=null, pattern='null', example='null', jsonSchema='{ "type" : "integer", "format" : "int32" -}', minimum='null', maximum='null', exclusiveMinimum=false, exclusiveMaximum=false, required=false, deprecated=false, hasMoreNonReadOnly=false, isPrimitiveType=true, isModel=false, isContainer=false, isString=false, isNumeric=true, isInteger=true, isLong=false, isNumber=false, isFloat=false, isDouble=false, isDecimal=false, isByteArray=false, isBinary=false, isFile=false, isBoolean=false, isDate=false, isDateTime=false, isUuid=false, isUri=false, isEmail=false, isFreeFormObject=false, isArray=false, isMap=false, isEnum=false, isReadOnly=false, isWriteOnly=false, isNullable=false, isSelfReference=false, isCircularReference=false, isDiscriminator=false, _enum=null, allowableValues=null, items=null, additionalProperties=null, vars=[], requiredVars=[], mostInnerItems=null, vendorExtensions={}, hasValidation=false, isInherited=false, discriminatorValue='null', nameInCamelCase='XRateLimit', nameInSnakeCase='X_RATE_LIMIT', enumName='null', maxItems=null, minItems=null, maxProperties=null, minProperties=null, uniqueItems=false, multipleOf=null, isXmlAttribute=false, xmlPrefix='null', xmlName='null', xmlNamespace='null', isXmlWrapped=false, isNull=false, getAdditionalPropertiesIsAnyType=false, getHasVars=false, getHasRequired=false}, CodegenProperty{openApiType='string', baseName='X-Expires-After', complexType='Date', getter='getxExpiresAfter', setter='setxExpiresAfter', description='date in UTC when toekn expires', dataType='Date', datatypeWithEnum='Date', dataFormat='date-time', name='xExpiresAfter', min='null', max='null', defaultValue='null', defaultValueWithParam=' = data.X-Expires-After;', baseType='Date', containerType='null', title='null', unescapedDescription='date in UTC when toekn expires', maxLength=null, minLength=null, pattern='null', example='null', jsonSchema='{ +}', minimum='null', maximum='null', exclusiveMinimum=false, exclusiveMaximum=false, required=false, deprecated=false, hasMoreNonReadOnly=false, isPrimitiveType=true, isModel=false, isContainer=false, isString=false, isNumeric=true, isInteger=true, isShort=true, isLong=false, isUnboundedInteger=false, isNumber=false, isFloat=false, isDouble=false, isDecimal=false, isByteArray=false, isBinary=false, isFile=false, isBoolean=false, isDate=false, isDateTime=false, isUuid=false, isUri=false, isEmail=false, isFreeFormObject=false, isArray=false, isMap=false, isEnum=false, isReadOnly=false, isWriteOnly=false, isNullable=false, isSelfReference=false, isCircularReference=false, isDiscriminator=false, _enum=null, allowableValues=null, items=null, additionalProperties=null, vars=[], requiredVars=[], mostInnerItems=null, vendorExtensions={}, hasValidation=false, isInherited=false, discriminatorValue='null', nameInCamelCase='XRateLimit', nameInSnakeCase='X_RATE_LIMIT', enumName='null', maxItems=null, minItems=null, maxProperties=null, minProperties=null, uniqueItems=false, multipleOf=null, isXmlAttribute=false, xmlPrefix='null', xmlName='null', xmlNamespace='null', isXmlWrapped=false, isNull=false, getAdditionalPropertiesIsAnyType=false, getHasVars=false, getHasRequired=false}, CodegenProperty{openApiType='string', baseName='X-Expires-After', complexType='Date', getter='getxExpiresAfter', setter='setxExpiresAfter', description='date in UTC when toekn expires', dataType='Date', datatypeWithEnum='Date', dataFormat='date-time', name='xExpiresAfter', min='null', max='null', defaultValue='null', defaultValueWithParam=' = data.X-Expires-After;', baseType='Date', containerType='null', title='null', unescapedDescription='date in UTC when toekn expires', maxLength=null, minLength=null, pattern='null', example='null', jsonSchema='{ "type" : "string", "format" : "date-time" -}', minimum='null', maximum='null', exclusiveMinimum=false, exclusiveMaximum=false, required=false, deprecated=false, hasMoreNonReadOnly=false, isPrimitiveType=false, isModel=false, isContainer=false, isString=false, isNumeric=false, isInteger=false, isLong=false, isNumber=false, isFloat=false, isDouble=false, isDecimal=false, isByteArray=false, isBinary=false, isFile=false, isBoolean=false, isDate=false, isDateTime=true, isUuid=false, isUri=false, isEmail=false, isFreeFormObject=false, isArray=false, isMap=false, isEnum=false, isReadOnly=false, isWriteOnly=false, isNullable=false, isSelfReference=false, isCircularReference=false, isDiscriminator=false, _enum=null, allowableValues=null, items=null, additionalProperties=null, vars=[], requiredVars=[], mostInnerItems=null, vendorExtensions={}, hasValidation=false, isInherited=false, discriminatorValue='null', nameInCamelCase='XExpiresAfter', nameInSnakeCase='X_EXPIRES_AFTER', enumName='null', maxItems=null, minItems=null, maxProperties=null, minProperties=null, uniqueItems=false, multipleOf=null, isXmlAttribute=false, xmlPrefix='null', xmlName='null', xmlNamespace='null', isXmlWrapped=false, isNull=false, getAdditionalPropertiesIsAnyType=false, getHasVars=false, getHasRequired=false}]

    +}', minimum='null', maximum='null', exclusiveMinimum=false, exclusiveMaximum=false, required=false, deprecated=false, hasMoreNonReadOnly=false, isPrimitiveType=false, isModel=false, isContainer=false, isString=false, isNumeric=false, isInteger=false, isShort=false, isLong=false, isUnboundedInteger=false, isNumber=false, isFloat=false, isDouble=false, isDecimal=false, isByteArray=false, isBinary=false, isFile=false, isBoolean=false, isDate=false, isDateTime=true, isUuid=false, isUri=false, isEmail=false, isFreeFormObject=false, isArray=false, isMap=false, isEnum=false, isReadOnly=false, isWriteOnly=false, isNullable=false, isSelfReference=false, isCircularReference=false, isDiscriminator=false, _enum=null, allowableValues=null, items=null, additionalProperties=null, vars=[], requiredVars=[], mostInnerItems=null, vendorExtensions={}, hasValidation=false, isInherited=false, discriminatorValue='null', nameInCamelCase='XExpiresAfter', nameInSnakeCase='X_EXPIRES_AFTER', enumName='null', maxItems=null, minItems=null, maxProperties=null, minProperties=null, uniqueItems=false, multipleOf=null, isXmlAttribute=false, xmlPrefix='null', xmlName='null', xmlNamespace='null', isXmlWrapped=false, isNull=false, getAdditionalPropertiesIsAnyType=false, getHasVars=false, getHasRequired=false}]

    * *

    Produces: [{mediaType=application/xml}, {mediaType=application/json}]

    *

    Returns: {@link String}

    diff --git a/samples/server/petstore/java-vertx-web/.openapi-generator/VERSION b/samples/server/petstore/java-vertx-web/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/server/petstore/java-vertx-web/.openapi-generator/VERSION +++ b/samples/server/petstore/java-vertx-web/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x 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 5f68295fc19..e8415097f3a 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,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x 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 7a0ffeda6b4..6e3398ecdf8 100644 --- a/samples/server/petstore/jaxrs-cxf-annotated-base-path/pom.xml +++ b/samples/server/petstore/jaxrs-cxf-annotated-base-path/pom.xml @@ -200,7 +200,7 @@ 1.5.22 9.2.9.v20150224 4.13 - 1.1.7 + 1.2.0 2.5 1.1.0.Final 3.3.0 diff --git a/samples/server/petstore/jaxrs-cxf-cdi-default-value/.openapi-generator/VERSION b/samples/server/petstore/jaxrs-cxf-cdi-default-value/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/server/petstore/jaxrs-cxf-cdi-default-value/.openapi-generator/VERSION +++ b/samples/server/petstore/jaxrs-cxf-cdi-default-value/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/server/petstore/jaxrs-cxf-cdi/.openapi-generator/VERSION b/samples/server/petstore/jaxrs-cxf-cdi/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/server/petstore/jaxrs-cxf-cdi/.openapi-generator/VERSION +++ b/samples/server/petstore/jaxrs-cxf-cdi/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x 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 5f68295fc19..e8415097f3a 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,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x 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 b969ba62f50..cf1b6b22218 100644 --- a/samples/server/petstore/jaxrs-cxf-non-spring-app/pom.xml +++ b/samples/server/petstore/jaxrs-cxf-non-spring-app/pom.xml @@ -200,7 +200,7 @@ 1.5.22 9.2.9.v20150224 4.13 - 1.1.7 + 1.2.0 2.5 1.1.0.Final 3.3.0 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 d99e7162d01..6555596f931 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.0.0-SNAPSHOT \ No newline at end of file +5.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 649cf9d0e98..f17dde84bad 100644 --- a/samples/server/petstore/jaxrs-cxf-test-data/pom.xml +++ b/samples/server/petstore/jaxrs-cxf-test-data/pom.xml @@ -233,7 +233,7 @@ org.openapitools openapi-generator - 5.0.0-SNAPSHOT + 5.2.0-SNAPSHOT diff --git a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/api/FakeApi.java b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/api/FakeApi.java index 35c97ab755a..21065b6fc8b 100644 --- a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/api/FakeApi.java +++ b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/api/FakeApi.java @@ -48,7 +48,7 @@ public interface FakeApi { @POST @Path("/create_xml_item") @Consumes({ "application/xml", "application/xml; charset=utf-8", "application/xml; charset=utf-16", "text/xml", "text/xml; charset=utf-8", "text/xml; charset=utf-16" }) - @ApiOperation(value = "creates an XmlItem", tags={ "fake", }) + @ApiOperation(value = "creates an XmlItem", tags={ "fake" }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation") }) public void createXmlItem(@Valid XmlItem xmlItem); @@ -57,7 +57,7 @@ public interface FakeApi { @Path("/outer/boolean") @Consumes({ "text/plain" }) @Produces({ "*/*" }) - @ApiOperation(value = "", tags={ "fake", }) + @ApiOperation(value = "", tags={ "fake" }) @ApiResponses(value = { @ApiResponse(code = 200, message = "Output boolean", response = Boolean.class) }) public Boolean fakeOuterBooleanSerialize(@Valid Boolean body); @@ -66,7 +66,7 @@ public interface FakeApi { @Path("/outer/composite") @Consumes({ "application/json" }) @Produces({ "*/*" }) - @ApiOperation(value = "", tags={ "fake", }) + @ApiOperation(value = "", tags={ "fake" }) @ApiResponses(value = { @ApiResponse(code = 200, message = "Output composite", response = OuterComposite.class) }) public OuterComposite fakeOuterCompositeSerialize(@Valid OuterComposite body); @@ -75,7 +75,7 @@ public interface FakeApi { @Path("/outer/number") @Consumes({ "text/plain" }) @Produces({ "*/*" }) - @ApiOperation(value = "", tags={ "fake", }) + @ApiOperation(value = "", tags={ "fake" }) @ApiResponses(value = { @ApiResponse(code = 200, message = "Output number", response = BigDecimal.class) }) public BigDecimal fakeOuterNumberSerialize(@Valid BigDecimal body); @@ -84,7 +84,7 @@ public interface FakeApi { @Path("/outer/string") @Consumes({ "text/plain" }) @Produces({ "*/*" }) - @ApiOperation(value = "", tags={ "fake", }) + @ApiOperation(value = "", tags={ "fake" }) @ApiResponses(value = { @ApiResponse(code = 200, message = "Output string", response = String.class) }) public String fakeOuterStringSerialize(@Valid String body); @@ -92,7 +92,7 @@ public interface FakeApi { @PUT @Path("/body-with-file-schema") @Consumes({ "application/json" }) - @ApiOperation(value = "", tags={ "fake", }) + @ApiOperation(value = "", tags={ "fake" }) @ApiResponses(value = { @ApiResponse(code = 200, message = "Success") }) public void testBodyWithFileSchema(@Valid FileSchemaTestClass body); @@ -100,7 +100,7 @@ public interface FakeApi { @PUT @Path("/body-with-query-params") @Consumes({ "application/json" }) - @ApiOperation(value = "", tags={ "fake", }) + @ApiOperation(value = "", tags={ "fake" }) @ApiResponses(value = { @ApiResponse(code = 200, message = "Success") }) public void testBodyWithQueryParams(@QueryParam("query") @NotNull String query, @Valid User body); @@ -115,7 +115,7 @@ public interface FakeApi { @Consumes({ "application/json" }) @Produces({ "application/json" }) - @ApiOperation(value = "To test \"client\" model", tags={ "fake", }) + @ApiOperation(value = "To test \"client\" model", tags={ "fake" }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Client.class) }) public Client testClientModel(@Valid Client body); @@ -129,7 +129,7 @@ public interface FakeApi { @POST @Consumes({ "application/x-www-form-urlencoded" }) - @ApiOperation(value = "Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트", tags={ "fake", }) + @ApiOperation(value = "Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트", tags={ "fake" }) @ApiResponses(value = { @ApiResponse(code = 400, message = "Invalid username supplied"), @ApiResponse(code = 404, message = "User not found") }) @@ -144,7 +144,7 @@ public interface FakeApi { @GET @Consumes({ "application/x-www-form-urlencoded" }) - @ApiOperation(value = "To test enum parameters", tags={ "fake", }) + @ApiOperation(value = "To test enum parameters", tags={ "fake" }) @ApiResponses(value = { @ApiResponse(code = 400, message = "Invalid request"), @ApiResponse(code = 404, message = "Not found") }) @@ -158,7 +158,7 @@ public interface FakeApi { */ @DELETE - @ApiOperation(value = "Fake endpoint to test group parameters (optional)", tags={ "fake", }) + @ApiOperation(value = "Fake endpoint to test group parameters (optional)", tags={ "fake" }) @ApiResponses(value = { @ApiResponse(code = 400, message = "Someting wrong") }) public 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); @@ -170,7 +170,7 @@ public interface FakeApi { @POST @Path("/inline-additionalProperties") @Consumes({ "application/json" }) - @ApiOperation(value = "test inline additionalProperties", tags={ "fake", }) + @ApiOperation(value = "test inline additionalProperties", tags={ "fake" }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation") }) public void testInlineAdditionalProperties(@Valid Map param); @@ -182,7 +182,7 @@ public interface FakeApi { @GET @Path("/jsonFormData") @Consumes({ "application/x-www-form-urlencoded" }) - @ApiOperation(value = "test json serialization of form data", tags={ "fake", }) + @ApiOperation(value = "test json serialization of form data", tags={ "fake" }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation") }) public void testJsonFormData(@Multipart(value = "param") String param, @Multipart(value = "param2") String param2); diff --git a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/api/PetApi.java b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/api/PetApi.java index 8a6246e339f..a78ab96f161 100644 --- a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/api/PetApi.java +++ b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/api/PetApi.java @@ -42,7 +42,7 @@ public interface PetApi { @POST @Path("/pet") @Consumes({ "application/json", "application/xml" }) - @ApiOperation(value = "Add a new pet to the store", tags={ "pet", }) + @ApiOperation(value = "Add a new pet to the store", tags={ "pet" }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation"), @ApiResponse(code = 405, message = "Invalid input") }) @@ -54,7 +54,7 @@ public interface PetApi { */ @DELETE @Path("/pet/{petId}") - @ApiOperation(value = "Deletes a pet", tags={ "pet", }) + @ApiOperation(value = "Deletes a pet", tags={ "pet" }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation"), @ApiResponse(code = 400, message = "Invalid pet value") }) @@ -69,7 +69,7 @@ public interface PetApi { @GET @Path("/pet/findByStatus") @Produces({ "application/xml", "application/json" }) - @ApiOperation(value = "Finds Pets by status", tags={ "pet", }) + @ApiOperation(value = "Finds Pets by status", tags={ "pet" }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Pet.class, responseContainer = "List"), @ApiResponse(code = 400, message = "Invalid status value") }) @@ -84,7 +84,7 @@ public interface PetApi { @GET @Path("/pet/findByTags") @Produces({ "application/xml", "application/json" }) - @ApiOperation(value = "Finds Pets by tags", tags={ "pet", }) + @ApiOperation(value = "Finds Pets by tags", tags={ "pet" }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Pet.class, responseContainer = "Set"), @ApiResponse(code = 400, message = "Invalid tag value") }) @@ -99,7 +99,7 @@ public interface PetApi { @GET @Path("/pet/{petId}") @Produces({ "application/xml", "application/json" }) - @ApiOperation(value = "Find pet by ID", tags={ "pet", }) + @ApiOperation(value = "Find pet by ID", tags={ "pet" }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Pet.class), @ApiResponse(code = 400, message = "Invalid ID supplied"), @@ -113,7 +113,7 @@ public interface PetApi { @PUT @Path("/pet") @Consumes({ "application/json", "application/xml" }) - @ApiOperation(value = "Update an existing pet", tags={ "pet", }) + @ApiOperation(value = "Update an existing pet", tags={ "pet" }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation"), @ApiResponse(code = 400, message = "Invalid ID supplied"), @@ -128,7 +128,7 @@ public interface PetApi { @POST @Path("/pet/{petId}") @Consumes({ "application/x-www-form-urlencoded" }) - @ApiOperation(value = "Updates a pet in the store with form data", tags={ "pet", }) + @ApiOperation(value = "Updates a pet in the store with form data", tags={ "pet" }) @ApiResponses(value = { @ApiResponse(code = 405, message = "Invalid input") }) public void updatePetWithForm(@PathParam("petId") Long petId, @Multipart(value = "name", required = false) String name, @Multipart(value = "status", required = false) String status); @@ -141,7 +141,7 @@ public interface PetApi { @Path("/pet/{petId}/uploadImage") @Consumes({ "multipart/form-data" }) @Produces({ "application/json" }) - @ApiOperation(value = "uploads an image", tags={ "pet", }) + @ApiOperation(value = "uploads an image", tags={ "pet" }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = ModelApiResponse.class) }) public ModelApiResponse uploadFile(@PathParam("petId") Long petId, @Multipart(value = "additionalMetadata", required = false) String additionalMetadata, @Multipart(value = "file" , required = false) Attachment fileDetail); diff --git a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/api/StoreApi.java b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/api/StoreApi.java index f440481f152..ac0a02f63fc 100644 --- a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/api/StoreApi.java +++ b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/api/StoreApi.java @@ -39,7 +39,7 @@ public interface StoreApi { */ @DELETE @Path("/order/{order_id}") - @ApiOperation(value = "Delete purchase order by ID", tags={ "store", }) + @ApiOperation(value = "Delete purchase order by ID", tags={ "store" }) @ApiResponses(value = { @ApiResponse(code = 400, message = "Invalid ID supplied"), @ApiResponse(code = 404, message = "Order not found") }) @@ -54,7 +54,7 @@ public interface StoreApi { @GET @Path("/inventory") @Produces({ "application/json" }) - @ApiOperation(value = "Returns pet inventories by status", tags={ "store", }) + @ApiOperation(value = "Returns pet inventories by status", tags={ "store" }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Map.class, responseContainer = "Map") }) public Map getInventory(); @@ -68,7 +68,7 @@ public interface StoreApi { @GET @Path("/order/{order_id}") @Produces({ "application/xml", "application/json" }) - @ApiOperation(value = "Find purchase order by ID", tags={ "store", }) + @ApiOperation(value = "Find purchase order by ID", tags={ "store" }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Order.class), @ApiResponse(code = 400, message = "Invalid ID supplied"), diff --git a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/api/UserApi.java b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/api/UserApi.java index edff4962812..a90c5ac242a 100644 --- a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/api/UserApi.java +++ b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/api/UserApi.java @@ -40,7 +40,7 @@ public interface UserApi { @POST @Consumes({ "application/json" }) - @ApiOperation(value = "Create user", tags={ "user", }) + @ApiOperation(value = "Create user", tags={ "user" }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation") }) public void createUser(@Valid User body); @@ -52,7 +52,7 @@ public interface UserApi { @POST @Path("/createWithArray") @Consumes({ "application/json" }) - @ApiOperation(value = "Creates list of users with given input array", tags={ "user", }) + @ApiOperation(value = "Creates list of users with given input array", tags={ "user" }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation") }) public void createUsersWithArrayInput(@Valid List body); @@ -64,7 +64,7 @@ public interface UserApi { @POST @Path("/createWithList") @Consumes({ "application/json" }) - @ApiOperation(value = "Creates list of users with given input array", tags={ "user", }) + @ApiOperation(value = "Creates list of users with given input array", tags={ "user" }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation") }) public void createUsersWithListInput(@Valid List body); @@ -77,7 +77,7 @@ public interface UserApi { */ @DELETE @Path("/{username}") - @ApiOperation(value = "Delete user", tags={ "user", }) + @ApiOperation(value = "Delete user", tags={ "user" }) @ApiResponses(value = { @ApiResponse(code = 400, message = "Invalid username supplied"), @ApiResponse(code = 404, message = "User not found") }) @@ -90,7 +90,7 @@ public interface UserApi { @GET @Path("/{username}") @Produces({ "application/xml", "application/json" }) - @ApiOperation(value = "Get user by user name", tags={ "user", }) + @ApiOperation(value = "Get user by user name", tags={ "user" }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = User.class), @ApiResponse(code = 400, message = "Invalid username supplied"), @@ -104,7 +104,7 @@ public interface UserApi { @GET @Path("/login") @Produces({ "application/xml", "application/json" }) - @ApiOperation(value = "Logs user into the system", tags={ "user", }) + @ApiOperation(value = "Logs user into the system", tags={ "user" }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = String.class), @ApiResponse(code = 400, message = "Invalid username/password supplied") }) @@ -116,7 +116,7 @@ public interface UserApi { */ @GET @Path("/logout") - @ApiOperation(value = "Logs out current logged in user session", tags={ "user", }) + @ApiOperation(value = "Logs out current logged in user session", tags={ "user" }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation") }) public void logoutUser(); 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 196b973164a..aff505263a5 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 @@ -18,9 +18,9 @@ import com.fasterxml.jackson.annotation.JsonProperty; @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "className", visible = true) @JsonSubTypes({ - @JsonSubTypes.Type(value = Dog.class, name = "Dog"), - @JsonSubTypes.Type(value = Cat.class, name = "Cat"), @JsonSubTypes.Type(value = BigCat.class, name = "BigCat"), + @JsonSubTypes.Type(value = Cat.class, name = "Cat"), + @JsonSubTypes.Type(value = Dog.class, name = "Dog"), }) public class Animal { 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 ea440f03445..11d450e49d6 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 @@ -1,5 +1,7 @@ package org.openapitools.model; +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.*; diff --git a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/BigCatAllOf.java b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/BigCatAllOf.java index 3ca25178105..c9d95b07dd4 100644 --- a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/BigCatAllOf.java +++ b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/BigCatAllOf.java @@ -1,5 +1,7 @@ package org.openapitools.model; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; import javax.validation.constraints.*; import javax.validation.Valid; 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 ae16f4a7bf6..0671e7b13f8 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 @@ -1,5 +1,7 @@ package org.openapitools.model; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; import java.util.ArrayList; import java.util.List; import javax.validation.constraints.*; 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 acd2762872f..cee18f27aab 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,5 +1,7 @@ package org.openapitools.model; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; import org.openapitools.model.OuterEnum; import javax.validation.constraints.*; import javax.validation.Valid; 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 9e915d8f54c..560ef7288ef 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 @@ -65,6 +65,7 @@ public class FormatTest { private String password; @ApiModelProperty(value = "") + @Valid private BigDecimal bigDecimal; /** * Get integer 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 c9495d9f7d4..e5af440e022 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 @@ -1,5 +1,7 @@ package org.openapitools.model; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; import java.util.HashMap; import java.util.List; import java.util.Map; 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 c17b378f5b9..baf2e5252bd 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 @@ -1,5 +1,7 @@ package org.openapitools.model; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; import java.util.Date; import javax.validation.constraints.*; import javax.validation.Valid; 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 e23e730eeff..289c50b9f4a 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 @@ -1,5 +1,7 @@ package org.openapitools.model; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; import java.util.ArrayList; import java.util.LinkedHashSet; import java.util.List; diff --git a/samples/server/petstore/jaxrs-cxf/.openapi-generator/VERSION b/samples/server/petstore/jaxrs-cxf/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/server/petstore/jaxrs-cxf/.openapi-generator/VERSION +++ b/samples/server/petstore/jaxrs-cxf/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/server/petstore/jaxrs-cxf/pom.xml b/samples/server/petstore/jaxrs-cxf/pom.xml index a98a3d7b11f..9403958f983 100644 --- a/samples/server/petstore/jaxrs-cxf/pom.xml +++ b/samples/server/petstore/jaxrs-cxf/pom.xml @@ -200,7 +200,7 @@ 1.5.22 9.2.9.v20150224 4.13 - 1.1.7 + 1.2.0 2.5 1.1.0.Final 3.3.0 diff --git a/samples/server/petstore/jaxrs-datelib-j8/.openapi-generator/VERSION b/samples/server/petstore/jaxrs-datelib-j8/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/server/petstore/jaxrs-datelib-j8/.openapi-generator/VERSION +++ b/samples/server/petstore/jaxrs-datelib-j8/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/server/petstore/jaxrs-datelib-j8/pom.xml b/samples/server/petstore/jaxrs-datelib-j8/pom.xml index c183185efec..56dda9ce81e 100644 --- a/samples/server/petstore/jaxrs-datelib-j8/pom.xml +++ b/samples/server/petstore/jaxrs-datelib-j8/pom.xml @@ -186,7 +186,7 @@ 2.22.2 2.9.9 4.13.1 - 1.1.7 + 1.2.0 2.5 UTF-8 diff --git a/samples/server/petstore/jaxrs-jersey/.openapi-generator/VERSION b/samples/server/petstore/jaxrs-jersey/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/server/petstore/jaxrs-jersey/.openapi-generator/VERSION +++ b/samples/server/petstore/jaxrs-jersey/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/server/petstore/jaxrs-jersey/pom.xml b/samples/server/petstore/jaxrs-jersey/pom.xml index 5087e5621c3..242055058d7 100644 --- a/samples/server/petstore/jaxrs-jersey/pom.xml +++ b/samples/server/petstore/jaxrs-jersey/pom.xml @@ -186,7 +186,7 @@ 2.22.2 2.9.9 4.13.1 - 1.1.7 + 1.2.0 2.5 UTF-8 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 43796a701ef..9cfd7cd8869 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 @@ -153,10 +153,22 @@ public class FakeApi { return delegate.fakePropertyEnumIntegerSerialize(outerObjectWithEnumProperty, securityContext); } @PUT + @Path("/body-with-binary") + @Consumes({ "image/png" }) + + @io.swagger.annotations.ApiOperation(value = "", notes = "For this test, the body has to be a binary file.", response = Void.class, tags={ "fake", }) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 200, message = "Success", response = Void.class) + }) + public Response testBodyWithBinary(@ApiParam(value = "image to upload", required = true) @NotNull File body,@Context SecurityContext securityContext) + throws NotFoundException { + return delegate.testBodyWithBinary(body, securityContext); + } + @PUT @Path("/body-with-file-schema") @Consumes({ "application/json" }) - @io.swagger.annotations.ApiOperation(value = "", notes = "For this test, the body for this request much reference a schema named `File`.", response = Void.class, tags={ "fake", }) + @io.swagger.annotations.ApiOperation(value = "", notes = "For this test, the body for this request must reference a schema named `File`.", response = Void.class, tags={ "fake", }) @io.swagger.annotations.ApiResponses(value = { @io.swagger.annotations.ApiResponse(code = 200, message = "Success", response = Void.class) }) 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 60685a8f5ff..e5c1a063e88 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 @@ -35,6 +35,7 @@ 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 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; 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 10c9235fe62..b9b56985363 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 @@ -64,6 +64,11 @@ public class FakeApiServiceImpl extends FakeApiService { 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(); + } + @Override public Response testBodyWithFileSchema(FileSchemaTestClass fileSchemaTestClass, 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/.openapi-generator/VERSION b/samples/server/petstore/jaxrs-resteasy/default-value/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/server/petstore/jaxrs-resteasy/default-value/.openapi-generator/VERSION +++ b/samples/server/petstore/jaxrs-resteasy/default-value/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/server/petstore/jaxrs-resteasy/default/.openapi-generator/VERSION b/samples/server/petstore/jaxrs-resteasy/default/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/server/petstore/jaxrs-resteasy/default/.openapi-generator/VERSION +++ b/samples/server/petstore/jaxrs-resteasy/default/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x 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 5f68295fc19..e8415097f3a 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,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x 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 5f68295fc19..e8415097f3a 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,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/server/petstore/jaxrs-resteasy/eap/.openapi-generator/VERSION b/samples/server/petstore/jaxrs-resteasy/eap/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/server/petstore/jaxrs-resteasy/eap/.openapi-generator/VERSION +++ b/samples/server/petstore/jaxrs-resteasy/eap/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/server/petstore/jaxrs-resteasy/joda/.openapi-generator/VERSION b/samples/server/petstore/jaxrs-resteasy/joda/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/server/petstore/jaxrs-resteasy/joda/.openapi-generator/VERSION +++ b/samples/server/petstore/jaxrs-resteasy/joda/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x 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 d99e7162d01..6555596f931 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 @@ -5.0.0-SNAPSHOT \ No newline at end of file +5.2.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 355d55d58d6..fdf423d8275 100644 --- a/samples/server/petstore/jaxrs-spec-interface-response/pom.xml +++ b/samples/server/petstore/jaxrs-spec-interface-response/pom.xml @@ -79,6 +79,6 @@ 2.9.9 - 4.8.1 + 4.13.1 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 396dbd24cfe..0d7fa5cb4d0 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 @@ -23,5 +23,5 @@ import javax.validation.Valid; @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 Client body); + Response call123testSpecialTags(@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 3b7b4a9af83..e7cd7f519d1 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 @@ -30,15 +30,15 @@ import javax.validation.Valid; @POST @Path("/create_xml_item") @Consumes({ "application/xml", "application/xml; charset=utf-8", "application/xml; charset=utf-16", "text/xml", "text/xml; charset=utf-8", "text/xml; charset=utf-16" }) - @ApiOperation(value = "creates an XmlItem", notes = "this route creates an XmlItem", tags={ "fake", }) + @ApiOperation(value = "creates an XmlItem", notes = "this route creates an XmlItem", tags={ "fake" }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Void.class) }) - Response createXmlItem(@Valid XmlItem xmlItem); + Response createXmlItem(@Valid @NotNull XmlItem xmlItem); @POST @Path("/outer/boolean") @Produces({ "*/*" }) - @ApiOperation(value = "", notes = "Test serialization of outer boolean types", tags={ "fake", }) + @ApiOperation(value = "", notes = "Test serialization of outer boolean types", tags={ "fake" }) @ApiResponses(value = { @ApiResponse(code = 200, message = "Output boolean", response = Boolean.class) }) Response fakeOuterBooleanSerialize(@Valid Boolean body); @@ -46,7 +46,7 @@ import javax.validation.Valid; @POST @Path("/outer/composite") @Produces({ "*/*" }) - @ApiOperation(value = "", notes = "Test serialization of object with outer number type", tags={ "fake", }) + @ApiOperation(value = "", notes = "Test serialization of object with outer number type", tags={ "fake" }) @ApiResponses(value = { @ApiResponse(code = 200, message = "Output composite", response = OuterComposite.class) }) Response fakeOuterCompositeSerialize(@Valid OuterComposite body); @@ -54,7 +54,7 @@ import javax.validation.Valid; @POST @Path("/outer/number") @Produces({ "*/*" }) - @ApiOperation(value = "", notes = "Test serialization of outer number types", tags={ "fake", }) + @ApiOperation(value = "", notes = "Test serialization of outer number types", tags={ "fake" }) @ApiResponses(value = { @ApiResponse(code = 200, message = "Output number", response = BigDecimal.class) }) Response fakeOuterNumberSerialize(@Valid BigDecimal body); @@ -62,7 +62,7 @@ import javax.validation.Valid; @POST @Path("/outer/string") @Produces({ "*/*" }) - @ApiOperation(value = "", notes = "Test serialization of outer string types", tags={ "fake", }) + @ApiOperation(value = "", notes = "Test serialization of outer string types", tags={ "fake" }) @ApiResponses(value = { @ApiResponse(code = 200, message = "Output string", response = String.class) }) Response fakeOuterStringSerialize(@Valid String body); @@ -70,32 +70,33 @@ import javax.validation.Valid; @PUT @Path("/body-with-file-schema") @Consumes({ "application/json" }) - @ApiOperation(value = "", notes = "For this test, the body for this request much reference a schema named `File`.", tags={ "fake", }) + @ApiOperation(value = "", notes = "For this test, the body for this request much reference a schema named `File`.", tags={ "fake" }) @ApiResponses(value = { @ApiResponse(code = 200, message = "Success", response = Void.class) }) - Response testBodyWithFileSchema(@Valid FileSchemaTestClass body); + Response testBodyWithFileSchema(@Valid @NotNull FileSchemaTestClass body); @PUT @Path("/body-with-query-params") @Consumes({ "application/json" }) - @ApiOperation(value = "", notes = "", tags={ "fake", }) + @ApiOperation(value = "", notes = "", tags={ "fake" }) @ApiResponses(value = { @ApiResponse(code = 200, message = "Success", response = Void.class) }) - Response testBodyWithQueryParams(@QueryParam("query") @NotNull String query,@Valid User body); + Response testBodyWithQueryParams(@QueryParam("query") @NotNull String query,@Valid @NotNull User body); @PATCH @Consumes({ "application/json" }) @Produces({ "application/json" }) - @ApiOperation(value = "To test \"client\" model", notes = "To test \"client\" model", tags={ "fake", }) + @ApiOperation(value = "To test \"client\" model", notes = "To test \"client\" model", tags={ "fake" }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Client.class) }) - Response testClientModel(@Valid Client body); + 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 = { + @Authorization(value = "http_basic_test") - }, tags={ "fake", }) + }, tags={ "fake" }) @ApiResponses(value = { @ApiResponse(code = 400, message = "Invalid username supplied", response = Void.class), @ApiResponse(code = 404, message = "User not found", response = Void.class) }) @@ -103,14 +104,14 @@ import javax.validation.Valid; @GET @Consumes({ "application/x-www-form-urlencoded" }) - @ApiOperation(value = "To test enum parameters", notes = "To test enum parameters", tags={ "fake", }) + @ApiOperation(value = "To test enum parameters", notes = "To test enum parameters", tags={ "fake" }) @ApiResponses(value = { @ApiResponse(code = 400, message = "Invalid request", response = Void.class), @ApiResponse(code = 404, message = "Not found", response = Void.class) }) - Response testEnumParameters(@HeaderParam("enum_header_string_array") @DefaultValue("new ArrayList()") @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); + 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", }) + @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 = "Someting 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); @@ -118,22 +119,22 @@ import javax.validation.Valid; @POST @Path("/inline-additionalProperties") @Consumes({ "application/json" }) - @ApiOperation(value = "test inline additionalProperties", notes = "", tags={ "fake", }) + @ApiOperation(value = "test inline additionalProperties", notes = "", tags={ "fake" }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Void.class) }) - Response testInlineAdditionalProperties(@Valid Map param); + Response testInlineAdditionalProperties(@Valid @NotNull Map param); @GET @Path("/jsonFormData") @Consumes({ "application/x-www-form-urlencoded" }) - @ApiOperation(value = "test json serialization of form data", notes = "", tags={ "fake", }) + @ApiOperation(value = "test json serialization of form data", notes = "", tags={ "fake" }) @ApiResponses(value = { @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-paramters") - @ApiOperation(value = "", notes = "To test the collection format in query parameters", tags={ "fake", }) + @ApiOperation(value = "", notes = "To test the collection format in query parameters", tags={ "fake" }) @ApiResponses(value = { @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); @@ -145,9 +146,8 @@ import javax.validation.Valid; @ApiOperation(value = "uploads an image (required)", notes = "", authorizations = { @Authorization(value = "petstore_auth", scopes = { @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), - @AuthorizationScope(scope = "read:pets", description = "read your pets") - }) - }, tags={ "pet" }) + @AuthorizationScope(scope = "read:pets", description = "read your pets") }) + }, tags={ "pet" }) @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 58c51e67a78..5d1c770b70a 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 @@ -21,9 +21,10 @@ import javax.validation.Valid; @Consumes({ "application/json" }) @Produces({ "application/json" }) @ApiOperation(value = "To test class name in snake case", notes = "To test class name in snake case", authorizations = { + @Authorization(value = "api_key_query") - }, tags={ "fake_classname_tags 123#$%^" }) + }, tags={ "fake_classname_tags 123#$%^" }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Client.class) }) - Response testClassname(@Valid Client body); + 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 2154b8d1e8a..480057d9367 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 @@ -25,22 +25,20 @@ import javax.validation.Valid; @ApiOperation(value = "Add a new pet to the store", notes = "", authorizations = { @Authorization(value = "petstore_auth", scopes = { @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), - @AuthorizationScope(scope = "read:pets", description = "read your pets") - }) - }, tags={ "pet", }) + @AuthorizationScope(scope = "read:pets", description = "read your pets") }) + }, tags={ "pet" }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Void.class), @ApiResponse(code = 405, message = "Invalid input", response = Void.class) }) - Response addPet(@Valid Pet body); + Response addPet(@Valid @NotNull Pet body); @DELETE @Path("/{petId}") @ApiOperation(value = "Deletes a pet", notes = "", authorizations = { @Authorization(value = "petstore_auth", scopes = { @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), - @AuthorizationScope(scope = "read:pets", description = "read your pets") - }) - }, tags={ "pet", }) + @AuthorizationScope(scope = "read:pets", description = "read your pets") }) + }, tags={ "pet" }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Void.class), @ApiResponse(code = 400, message = "Invalid pet value", response = Void.class) }) @@ -52,9 +50,8 @@ import javax.validation.Valid; @ApiOperation(value = "Finds Pets by status", notes = "Multiple status values can be provided with comma separated strings", authorizations = { @Authorization(value = "petstore_auth", scopes = { @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), - @AuthorizationScope(scope = "read:pets", description = "read your pets") - }) - }, tags={ "pet", }) + @AuthorizationScope(scope = "read:pets", description = "read your pets") }) + }, tags={ "pet" }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Pet.class, responseContainer = "List"), @ApiResponse(code = 400, message = "Invalid status value", response = Void.class, responseContainer = "List") }) @@ -66,9 +63,8 @@ import javax.validation.Valid; @ApiOperation(value = "Finds Pets by tags", notes = "Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.", authorizations = { @Authorization(value = "petstore_auth", scopes = { @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), - @AuthorizationScope(scope = "read:pets", description = "read your pets") - }) - }, tags={ "pet", }) + @AuthorizationScope(scope = "read:pets", description = "read your pets") }) + }, tags={ "pet" }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Pet.class, responseContainer = "Set"), @ApiResponse(code = 400, message = "Invalid tag value", response = Void.class, responseContainer = "Set") }) @@ -78,8 +74,9 @@ import javax.validation.Valid; @Path("/{petId}") @Produces({ "application/xml", "application/json" }) @ApiOperation(value = "Find pet by ID", notes = "Returns a single pet", authorizations = { + @Authorization(value = "api_key") - }, tags={ "pet", }) + }, tags={ "pet" }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Pet.class), @ApiResponse(code = 400, message = "Invalid ID supplied", response = Void.class), @@ -91,15 +88,14 @@ import javax.validation.Valid; @ApiOperation(value = "Update an existing pet", notes = "", authorizations = { @Authorization(value = "petstore_auth", scopes = { @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), - @AuthorizationScope(scope = "read:pets", description = "read your pets") - }) - }, tags={ "pet", }) + @AuthorizationScope(scope = "read:pets", description = "read your pets") }) + }, tags={ "pet" }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Void.class), @ApiResponse(code = 400, message = "Invalid ID supplied", response = Void.class), @ApiResponse(code = 404, message = "Pet not found", response = Void.class), @ApiResponse(code = 405, message = "Validation exception", response = Void.class) }) - Response updatePet(@Valid Pet body); + Response updatePet(@Valid @NotNull Pet body); @POST @Path("/{petId}") @@ -107,9 +103,8 @@ import javax.validation.Valid; @ApiOperation(value = "Updates a pet in the store with form data", notes = "", authorizations = { @Authorization(value = "petstore_auth", scopes = { @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), - @AuthorizationScope(scope = "read:pets", description = "read your pets") - }) - }, tags={ "pet", }) + @AuthorizationScope(scope = "read:pets", description = "read your pets") }) + }, tags={ "pet" }) @ApiResponses(value = { @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); @@ -121,9 +116,8 @@ import javax.validation.Valid; @ApiOperation(value = "uploads an image", notes = "", authorizations = { @Authorization(value = "petstore_auth", scopes = { @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), - @AuthorizationScope(scope = "read:pets", description = "read your pets") - }) - }, tags={ "pet" }) + @AuthorizationScope(scope = "read:pets", description = "read your pets") }) + }, tags={ "pet" }) @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 01593fedfec..06a7a2967ed 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 @@ -20,7 +20,7 @@ import javax.validation.Valid; @DELETE @Path("/order/{order_id}") - @ApiOperation(value = "Delete purchase order by ID", notes = "For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors", tags={ "store", }) + @ApiOperation(value = "Delete purchase order by ID", notes = "For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors", tags={ "store" }) @ApiResponses(value = { @ApiResponse(code = 400, message = "Invalid ID supplied", response = Void.class), @ApiResponse(code = 404, message = "Order not found", response = Void.class) }) @@ -30,8 +30,9 @@ import javax.validation.Valid; @Path("/inventory") @Produces({ "application/json" }) @ApiOperation(value = "Returns pet inventories by status", notes = "Returns a map of status codes to quantities", authorizations = { + @Authorization(value = "api_key") - }, tags={ "store", }) + }, tags={ "store" }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Map.class, responseContainer = "Map") }) Response getInventory(); @@ -39,7 +40,7 @@ import javax.validation.Valid; @GET @Path("/order/{order_id}") @Produces({ "application/xml", "application/json" }) - @ApiOperation(value = "Find purchase order by ID", notes = "For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions", tags={ "store", }) + @ApiOperation(value = "Find purchase order by ID", notes = "For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions", tags={ "store" }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Order.class), @ApiResponse(code = 400, message = "Invalid ID supplied", response = Void.class), @@ -53,5 +54,5 @@ import javax.validation.Valid; @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Order.class), @ApiResponse(code = 400, message = "Invalid Order", response = Void.class) }) - Response placeOrder(@Valid Order body); + 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 7d821837153..77ea16dbeb8 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 @@ -19,28 +19,28 @@ import javax.validation.Valid; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen")public interface UserApi { @POST - @ApiOperation(value = "Create user", notes = "This can only be done by the logged in user.", tags={ "user", }) + @ApiOperation(value = "Create user", notes = "This can only be done by the logged in user.", tags={ "user" }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Void.class) }) - Response createUser(@Valid User body); + Response createUser(@Valid @NotNull User body); @POST @Path("/createWithArray") - @ApiOperation(value = "Creates list of users with given input array", notes = "", tags={ "user", }) + @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 List body); + Response createUsersWithArrayInput(@Valid @NotNull List body); @POST @Path("/createWithList") - @ApiOperation(value = "Creates list of users with given input array", notes = "", tags={ "user", }) + @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 List body); + Response createUsersWithListInput(@Valid @NotNull List body); @DELETE @Path("/{username}") - @ApiOperation(value = "Delete user", notes = "This can only be done by the logged in user.", tags={ "user", }) + @ApiOperation(value = "Delete user", notes = "This can only be done by the logged in user.", tags={ "user" }) @ApiResponses(value = { @ApiResponse(code = 400, message = "Invalid username supplied", response = Void.class), @ApiResponse(code = 404, message = "User not found", response = Void.class) }) @@ -49,7 +49,7 @@ import javax.validation.Valid; @GET @Path("/{username}") @Produces({ "application/xml", "application/json" }) - @ApiOperation(value = "Get user by user name", notes = "", tags={ "user", }) + @ApiOperation(value = "Get user by user name", notes = "", tags={ "user" }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = User.class), @ApiResponse(code = 400, message = "Invalid username supplied", response = Void.class), @@ -59,7 +59,7 @@ import javax.validation.Valid; @GET @Path("/login") @Produces({ "application/xml", "application/json" }) - @ApiOperation(value = "Logs user into the system", notes = "", tags={ "user", }) + @ApiOperation(value = "Logs user into the system", notes = "", tags={ "user" }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = String.class), @ApiResponse(code = 400, message = "Invalid username/password supplied", response = Void.class) }) @@ -67,7 +67,7 @@ import javax.validation.Valid; @GET @Path("/logout") - @ApiOperation(value = "Logs out current logged in user session", notes = "", tags={ "user", }) + @ApiOperation(value = "Logs out current logged in user session", notes = "", tags={ "user" }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Void.class) }) Response logoutUser(); @@ -78,5 +78,5 @@ import javax.validation.Valid; @ApiResponses(value = { @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 User body); + 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/AdditionalPropertiesAnyType.java b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/AdditionalPropertiesAnyType.java index f2521988441..6b9dcfa1ac6 100644 --- a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/AdditionalPropertiesAnyType.java +++ b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/AdditionalPropertiesAnyType.java @@ -40,6 +40,7 @@ import com.fasterxml.jackson.annotation.JsonValue; this.name = name; } + @Override public boolean equals(Object o) { if (this == o) { diff --git a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/AdditionalPropertiesArray.java b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/AdditionalPropertiesArray.java index 7cc3e609972..1b504c15f4e 100644 --- a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/AdditionalPropertiesArray.java +++ b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/AdditionalPropertiesArray.java @@ -41,6 +41,7 @@ import com.fasterxml.jackson.annotation.JsonValue; this.name = name; } + @Override public boolean equals(Object o) { if (this == o) { diff --git a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/AdditionalPropertiesBoolean.java b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/AdditionalPropertiesBoolean.java index 172c5f42dad..d842728a186 100644 --- a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/AdditionalPropertiesBoolean.java +++ b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/AdditionalPropertiesBoolean.java @@ -40,6 +40,7 @@ import com.fasterxml.jackson.annotation.JsonValue; this.name = name; } + @Override public boolean equals(Object o) { if (this == o) { 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 b646cfb0b0d..ab1baad9976 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 @@ -50,7 +50,9 @@ import com.fasterxml.jackson.annotation.JsonValue; public void setMapString(Map mapString) { this.mapString = mapString; - }/** + } + +/** **/ public AdditionalPropertiesClass mapNumber(Map mapNumber) { this.mapNumber = mapNumber; @@ -68,7 +70,9 @@ import com.fasterxml.jackson.annotation.JsonValue; public void setMapNumber(Map mapNumber) { this.mapNumber = mapNumber; - }/** + } + +/** **/ public AdditionalPropertiesClass mapInteger(Map mapInteger) { this.mapInteger = mapInteger; @@ -86,7 +90,9 @@ import com.fasterxml.jackson.annotation.JsonValue; public void setMapInteger(Map mapInteger) { this.mapInteger = mapInteger; - }/** + } + +/** **/ public AdditionalPropertiesClass mapBoolean(Map mapBoolean) { this.mapBoolean = mapBoolean; @@ -104,7 +110,9 @@ import com.fasterxml.jackson.annotation.JsonValue; public void setMapBoolean(Map mapBoolean) { this.mapBoolean = mapBoolean; - }/** + } + +/** **/ public AdditionalPropertiesClass mapArrayInteger(Map> mapArrayInteger) { this.mapArrayInteger = mapArrayInteger; @@ -122,7 +130,9 @@ import com.fasterxml.jackson.annotation.JsonValue; public void setMapArrayInteger(Map> mapArrayInteger) { this.mapArrayInteger = mapArrayInteger; - }/** + } + +/** **/ public AdditionalPropertiesClass mapArrayAnytype(Map> mapArrayAnytype) { this.mapArrayAnytype = mapArrayAnytype; @@ -140,7 +150,9 @@ import com.fasterxml.jackson.annotation.JsonValue; public void setMapArrayAnytype(Map> mapArrayAnytype) { this.mapArrayAnytype = mapArrayAnytype; - }/** + } + +/** **/ public AdditionalPropertiesClass mapMapString(Map> mapMapString) { this.mapMapString = mapMapString; @@ -158,7 +170,9 @@ import com.fasterxml.jackson.annotation.JsonValue; public void setMapMapString(Map> mapMapString) { this.mapMapString = mapMapString; - }/** + } + +/** **/ public AdditionalPropertiesClass mapMapAnytype(Map> mapMapAnytype) { this.mapMapAnytype = mapMapAnytype; @@ -176,7 +190,9 @@ import com.fasterxml.jackson.annotation.JsonValue; public void setMapMapAnytype(Map> mapMapAnytype) { this.mapMapAnytype = mapMapAnytype; - }/** + } + +/** **/ public AdditionalPropertiesClass anytype1(Object anytype1) { this.anytype1 = anytype1; @@ -194,7 +210,9 @@ import com.fasterxml.jackson.annotation.JsonValue; public void setAnytype1(Object anytype1) { this.anytype1 = anytype1; - }/** + } + +/** **/ public AdditionalPropertiesClass anytype2(Object anytype2) { this.anytype2 = anytype2; @@ -212,7 +230,9 @@ import com.fasterxml.jackson.annotation.JsonValue; public void setAnytype2(Object anytype2) { this.anytype2 = anytype2; - }/** + } + +/** **/ public AdditionalPropertiesClass anytype3(Object anytype3) { this.anytype3 = anytype3; @@ -232,6 +252,7 @@ import com.fasterxml.jackson.annotation.JsonValue; this.anytype3 = anytype3; } + @Override public boolean equals(Object o) { if (this == o) { diff --git a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/AdditionalPropertiesInteger.java b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/AdditionalPropertiesInteger.java index 2c2e51fb83b..6f925720aba 100644 --- a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/AdditionalPropertiesInteger.java +++ b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/AdditionalPropertiesInteger.java @@ -40,6 +40,7 @@ import com.fasterxml.jackson.annotation.JsonValue; this.name = name; } + @Override public boolean equals(Object o) { if (this == o) { diff --git a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/AdditionalPropertiesNumber.java b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/AdditionalPropertiesNumber.java index 4735b0fd5bd..884577dcdd0 100644 --- a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/AdditionalPropertiesNumber.java +++ b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/AdditionalPropertiesNumber.java @@ -41,6 +41,7 @@ import com.fasterxml.jackson.annotation.JsonValue; this.name = name; } + @Override public boolean equals(Object o) { if (this == o) { diff --git a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/AdditionalPropertiesObject.java b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/AdditionalPropertiesObject.java index 05f7408f9a8..cbe4428f3e3 100644 --- a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/AdditionalPropertiesObject.java +++ b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/AdditionalPropertiesObject.java @@ -40,6 +40,7 @@ import com.fasterxml.jackson.annotation.JsonValue; this.name = name; } + @Override public boolean equals(Object o) { if (this == o) { diff --git a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/AdditionalPropertiesString.java b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/AdditionalPropertiesString.java index 03739679cd0..16f6a60afd1 100644 --- a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/AdditionalPropertiesString.java +++ b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/AdditionalPropertiesString.java @@ -40,6 +40,7 @@ import com.fasterxml.jackson.annotation.JsonValue; this.name = name; } + @Override public boolean equals(Object o) { if (this == o) { diff --git a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/Animal.java b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/Animal.java index 3b0eff6127c..8ddd9ed2f8c 100644 --- a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/Animal.java +++ b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/Animal.java @@ -16,9 +16,9 @@ import com.fasterxml.jackson.annotation.JsonValue; @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "className", visible = true) @JsonSubTypes({ - @JsonSubTypes.Type(value = Dog.class, name = "Dog"), - @JsonSubTypes.Type(value = Cat.class, name = "Cat"), @JsonSubTypes.Type(value = BigCat.class, name = "BigCat"), + @JsonSubTypes.Type(value = Cat.class, name = "Cat"), + @JsonSubTypes.Type(value = Dog.class, name = "Dog"), }) @@ -46,7 +46,9 @@ import com.fasterxml.jackson.annotation.JsonValue; public void setClassName(String className) { this.className = className; - }/** + } + +/** **/ public Animal color(String color) { this.color = color; @@ -66,6 +68,7 @@ import com.fasterxml.jackson.annotation.JsonValue; this.color = color; } + @Override public boolean equals(Object o) { if (this == o) { 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 77a46a2186a..9643930053c 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 @@ -41,6 +41,7 @@ import com.fasterxml.jackson.annotation.JsonValue; this.arrayArrayNumber = arrayArrayNumber; } + @Override public boolean equals(Object o) { if (this == o) { 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 36039422cf3..2c585cdc1e8 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 @@ -41,6 +41,7 @@ import com.fasterxml.jackson.annotation.JsonValue; this.arrayNumber = arrayNumber; } + @Override public boolean equals(Object o) { if (this == o) { 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 374527d8ad5..edc0b7a9484 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 @@ -41,7 +41,9 @@ import com.fasterxml.jackson.annotation.JsonValue; public void setArrayOfString(List arrayOfString) { this.arrayOfString = arrayOfString; - }/** + } + +/** **/ public ArrayTest arrayArrayOfInteger(List> arrayArrayOfInteger) { this.arrayArrayOfInteger = arrayArrayOfInteger; @@ -59,7 +61,9 @@ import com.fasterxml.jackson.annotation.JsonValue; public void setArrayArrayOfInteger(List> arrayArrayOfInteger) { this.arrayArrayOfInteger = arrayArrayOfInteger; - }/** + } + +/** **/ public ArrayTest arrayArrayOfModel(List> arrayArrayOfModel) { this.arrayArrayOfModel = arrayArrayOfModel; @@ -79,6 +83,7 @@ import com.fasterxml.jackson.annotation.JsonValue; this.arrayArrayOfModel = arrayArrayOfModel; } + @Override public boolean equals(Object o) { if (this == o) { 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 33dff05e836..1a3ddba789b 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 @@ -73,6 +73,7 @@ public enum KindEnum { this.kind = kind; } + @Override public boolean equals(Object o) { if (this == o) { diff --git a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/BigCatAllOf.java b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/BigCatAllOf.java index 0b5a153a074..080e86afaca 100644 --- a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/BigCatAllOf.java +++ b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/BigCatAllOf.java @@ -71,6 +71,7 @@ public enum KindEnum { this.kind = kind; } + @Override public boolean equals(Object o) { if (this == o) { diff --git a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/Capitalization.java b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/Capitalization.java index 27f378125da..a65c79d984e 100644 --- a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/Capitalization.java +++ b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/Capitalization.java @@ -41,7 +41,9 @@ import com.fasterxml.jackson.annotation.JsonValue; public void setSmallCamel(String smallCamel) { this.smallCamel = smallCamel; - }/** + } + +/** **/ public Capitalization capitalCamel(String capitalCamel) { this.capitalCamel = capitalCamel; @@ -59,7 +61,9 @@ import com.fasterxml.jackson.annotation.JsonValue; public void setCapitalCamel(String capitalCamel) { this.capitalCamel = capitalCamel; - }/** + } + +/** **/ public Capitalization smallSnake(String smallSnake) { this.smallSnake = smallSnake; @@ -77,7 +81,9 @@ import com.fasterxml.jackson.annotation.JsonValue; public void setSmallSnake(String smallSnake) { this.smallSnake = smallSnake; - }/** + } + +/** **/ public Capitalization capitalSnake(String capitalSnake) { this.capitalSnake = capitalSnake; @@ -95,7 +101,9 @@ import com.fasterxml.jackson.annotation.JsonValue; public void setCapitalSnake(String capitalSnake) { this.capitalSnake = capitalSnake; - }/** + } + +/** **/ public Capitalization scAETHFlowPoints(String scAETHFlowPoints) { this.scAETHFlowPoints = scAETHFlowPoints; @@ -113,7 +121,9 @@ import com.fasterxml.jackson.annotation.JsonValue; public void setScAETHFlowPoints(String scAETHFlowPoints) { this.scAETHFlowPoints = scAETHFlowPoints; - }/** + } + +/** * Name of the pet **/ public Capitalization ATT_NAME(String ATT_NAME) { @@ -134,6 +144,7 @@ import com.fasterxml.jackson.annotation.JsonValue; this.ATT_NAME = ATT_NAME; } + @Override public boolean equals(Object o) { if (this == o) { diff --git a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/Cat.java b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/Cat.java index b0a2eacada2..4cc078e2235 100644 --- a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/Cat.java +++ b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/Cat.java @@ -40,6 +40,7 @@ import com.fasterxml.jackson.annotation.JsonValue; this.declawed = declawed; } + @Override public boolean equals(Object o) { if (this == o) { diff --git a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/CatAllOf.java b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/CatAllOf.java index f405b41e872..e56df72d3be 100644 --- a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/CatAllOf.java +++ b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/CatAllOf.java @@ -38,6 +38,7 @@ import com.fasterxml.jackson.annotation.JsonValue; this.declawed = declawed; } + @Override public boolean equals(Object o) { if (this == o) { diff --git a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/Category.java b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/Category.java index 32076613c9d..9af6f93c7c4 100644 --- a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/Category.java +++ b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/Category.java @@ -37,7 +37,9 @@ import com.fasterxml.jackson.annotation.JsonValue; public void setId(Long id) { this.id = id; - }/** + } + +/** **/ public Category name(String name) { this.name = name; @@ -58,6 +60,7 @@ import com.fasterxml.jackson.annotation.JsonValue; this.name = name; } + @Override public boolean equals(Object o) { if (this == o) { diff --git a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/ClassModel.java b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/ClassModel.java index e3153a9f03e..f050e12bb25 100644 --- a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/ClassModel.java +++ b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/ClassModel.java @@ -40,6 +40,7 @@ import com.fasterxml.jackson.annotation.JsonValue; this.propertyClass = propertyClass; } + @Override public boolean equals(Object o) { if (this == o) { diff --git a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/Client.java b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/Client.java index 81a1033e052..4cdbbef940d 100644 --- a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/Client.java +++ b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/Client.java @@ -38,6 +38,7 @@ import com.fasterxml.jackson.annotation.JsonValue; this.client = client; } + @Override public boolean equals(Object o) { if (this == o) { diff --git a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/Dog.java b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/Dog.java index 01e256a23d0..87c3a825ba8 100644 --- a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/Dog.java +++ b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/Dog.java @@ -40,6 +40,7 @@ import com.fasterxml.jackson.annotation.JsonValue; this.breed = breed; } + @Override public boolean equals(Object o) { if (this == o) { diff --git a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/DogAllOf.java b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/DogAllOf.java index 3291b8f7c78..5496e3c8915 100644 --- a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/DogAllOf.java +++ b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/DogAllOf.java @@ -38,6 +38,7 @@ import com.fasterxml.jackson.annotation.JsonValue; this.breed = breed; } + @Override public boolean equals(Object o) { if (this == o) { 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 c7ceed68c70..fc7770afa09 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 @@ -105,7 +105,9 @@ public enum ArrayEnumEnum { public void setJustSymbol(JustSymbolEnum justSymbol) { this.justSymbol = justSymbol; - }/** + } + +/** **/ public EnumArrays arrayEnum(List arrayEnum) { this.arrayEnum = arrayEnum; @@ -125,6 +127,7 @@ public enum ArrayEnumEnum { this.arrayEnum = arrayEnum; } + @Override public boolean equals(Object o) { if (this == o) { 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 d74cb2ff037..6c02f0647c9 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 @@ -173,7 +173,9 @@ public enum EnumNumberEnum { public void setEnumString(EnumStringEnum enumString) { this.enumString = enumString; - }/** + } + +/** **/ public EnumTest enumStringRequired(EnumStringRequiredEnum enumStringRequired) { this.enumStringRequired = enumStringRequired; @@ -192,7 +194,9 @@ public enum EnumNumberEnum { public void setEnumStringRequired(EnumStringRequiredEnum enumStringRequired) { this.enumStringRequired = enumStringRequired; - }/** + } + +/** **/ public EnumTest enumInteger(EnumIntegerEnum enumInteger) { this.enumInteger = enumInteger; @@ -210,7 +214,9 @@ public enum EnumNumberEnum { public void setEnumInteger(EnumIntegerEnum enumInteger) { this.enumInteger = enumInteger; - }/** + } + +/** **/ public EnumTest enumNumber(EnumNumberEnum enumNumber) { this.enumNumber = enumNumber; @@ -228,7 +234,9 @@ public enum EnumNumberEnum { public void setEnumNumber(EnumNumberEnum enumNumber) { this.enumNumber = enumNumber; - }/** + } + +/** **/ public EnumTest outerEnum(OuterEnum outerEnum) { this.outerEnum = outerEnum; @@ -248,6 +256,7 @@ public enum EnumNumberEnum { this.outerEnum = outerEnum; } + @Override public boolean equals(Object o) { if (this == o) { 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 8aa815da794..b8ba37d5cdc 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 @@ -39,7 +39,9 @@ import com.fasterxml.jackson.annotation.JsonValue; public void setFile(java.io.File file) { this.file = file; - }/** + } + +/** **/ public FileSchemaTestClass files(List files) { this.files = files; @@ -59,6 +61,7 @@ import com.fasterxml.jackson.annotation.JsonValue; this.files = files; } + @Override public boolean equals(Object o) { if (this == o) { 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 70a7eed2fdd..ca11645f9ae 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 @@ -56,7 +56,9 @@ import com.fasterxml.jackson.annotation.JsonValue; public void setInteger(Integer integer) { this.integer = integer; - }/** + } + +/** * minimum: 20 * maximum: 200 **/ @@ -76,7 +78,9 @@ import com.fasterxml.jackson.annotation.JsonValue; public void setInt32(Integer int32) { this.int32 = int32; - }/** + } + +/** **/ public FormatTest int64(Long int64) { this.int64 = int64; @@ -94,7 +98,9 @@ import com.fasterxml.jackson.annotation.JsonValue; public void setInt64(Long int64) { this.int64 = int64; - }/** + } + +/** * minimum: 32.1 * maximum: 543.2 **/ @@ -115,7 +121,9 @@ import com.fasterxml.jackson.annotation.JsonValue; public void setNumber(BigDecimal number) { this.number = number; - }/** + } + +/** * minimum: 54.3 * maximum: 987.6 **/ @@ -135,7 +143,9 @@ import com.fasterxml.jackson.annotation.JsonValue; public void setFloat(Float _float) { this._float = _float; - }/** + } + +/** * minimum: 67.8 * maximum: 123.4 **/ @@ -155,7 +165,9 @@ import com.fasterxml.jackson.annotation.JsonValue; public void setDouble(Double _double) { this._double = _double; - }/** + } + +/** **/ public FormatTest string(String string) { this.string = string; @@ -173,7 +185,9 @@ import com.fasterxml.jackson.annotation.JsonValue; public void setString(String string) { this.string = string; - }/** + } + +/** **/ public FormatTest _byte(byte[] _byte) { this._byte = _byte; @@ -192,7 +206,9 @@ import com.fasterxml.jackson.annotation.JsonValue; public void setByte(byte[] _byte) { this._byte = _byte; - }/** + } + +/** **/ public FormatTest binary(File binary) { this.binary = binary; @@ -210,7 +226,9 @@ import com.fasterxml.jackson.annotation.JsonValue; public void setBinary(File binary) { this.binary = binary; - }/** + } + +/** **/ public FormatTest date(LocalDate date) { this.date = date; @@ -229,7 +247,9 @@ import com.fasterxml.jackson.annotation.JsonValue; public void setDate(LocalDate date) { this.date = date; - }/** + } + +/** **/ public FormatTest dateTime(Date dateTime) { this.dateTime = dateTime; @@ -247,7 +267,9 @@ import com.fasterxml.jackson.annotation.JsonValue; public void setDateTime(Date dateTime) { this.dateTime = dateTime; - }/** + } + +/** **/ public FormatTest uuid(UUID uuid) { this.uuid = uuid; @@ -265,7 +287,9 @@ import com.fasterxml.jackson.annotation.JsonValue; public void setUuid(UUID uuid) { this.uuid = uuid; - }/** + } + +/** **/ public FormatTest password(String password) { this.password = password; @@ -284,7 +308,9 @@ import com.fasterxml.jackson.annotation.JsonValue; public void setPassword(String password) { this.password = password; - }/** + } + +/** **/ public FormatTest bigDecimal(BigDecimal bigDecimal) { this.bigDecimal = bigDecimal; @@ -304,6 +330,7 @@ import com.fasterxml.jackson.annotation.JsonValue; this.bigDecimal = bigDecimal; } + @Override public boolean equals(Object o) { if (this == o) { diff --git a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/HasOnlyReadOnly.java b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/HasOnlyReadOnly.java index cebb1bb512b..6438846d569 100644 --- a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/HasOnlyReadOnly.java +++ b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/HasOnlyReadOnly.java @@ -37,7 +37,9 @@ import com.fasterxml.jackson.annotation.JsonValue; public void setBar(String bar) { this.bar = bar; - }/** + } + +/** **/ public HasOnlyReadOnly foo(String foo) { this.foo = foo; @@ -57,6 +59,7 @@ import com.fasterxml.jackson.annotation.JsonValue; this.foo = foo; } + @Override public boolean equals(Object o) { if (this == o) { 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 be225de067d..a8eff4c21b2 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 @@ -75,7 +75,9 @@ public enum InnerEnum { public void setMapMapOfString(Map> mapMapOfString) { this.mapMapOfString = mapMapOfString; - }/** + } + +/** **/ public MapTest mapOfEnumString(Map mapOfEnumString) { this.mapOfEnumString = mapOfEnumString; @@ -93,7 +95,9 @@ public enum InnerEnum { public void setMapOfEnumString(Map mapOfEnumString) { this.mapOfEnumString = mapOfEnumString; - }/** + } + +/** **/ public MapTest directMap(Map directMap) { this.directMap = directMap; @@ -111,7 +115,9 @@ public enum InnerEnum { public void setDirectMap(Map directMap) { this.directMap = directMap; - }/** + } + +/** **/ public MapTest indirectMap(Map indirectMap) { this.indirectMap = indirectMap; @@ -131,6 +137,7 @@ public enum InnerEnum { this.indirectMap = indirectMap; } + @Override public boolean equals(Object o) { if (this == o) { 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 136a4fab119..aace3762eb9 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 @@ -44,7 +44,9 @@ import com.fasterxml.jackson.annotation.JsonValue; public void setUuid(UUID uuid) { this.uuid = uuid; - }/** + } + +/** **/ public MixedPropertiesAndAdditionalPropertiesClass dateTime(Date dateTime) { this.dateTime = dateTime; @@ -62,7 +64,9 @@ import com.fasterxml.jackson.annotation.JsonValue; public void setDateTime(Date dateTime) { this.dateTime = dateTime; - }/** + } + +/** **/ public MixedPropertiesAndAdditionalPropertiesClass map(Map map) { this.map = map; @@ -82,6 +86,7 @@ import com.fasterxml.jackson.annotation.JsonValue; this.map = map; } + @Override public boolean equals(Object o) { if (this == o) { diff --git a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/Model200Response.java b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/Model200Response.java index 3a8a04baa8f..d96df1aceae 100644 --- a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/Model200Response.java +++ b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/Model200Response.java @@ -39,7 +39,9 @@ import com.fasterxml.jackson.annotation.JsonValue; public void setName(Integer name) { this.name = name; - }/** + } + +/** **/ public Model200Response propertyClass(String propertyClass) { this.propertyClass = propertyClass; @@ -59,6 +61,7 @@ import com.fasterxml.jackson.annotation.JsonValue; this.propertyClass = propertyClass; } + @Override public boolean equals(Object o) { if (this == o) { diff --git a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/ModelApiResponse.java b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/ModelApiResponse.java index f382361e58c..952439560b5 100644 --- a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/ModelApiResponse.java +++ b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/ModelApiResponse.java @@ -38,7 +38,9 @@ import com.fasterxml.jackson.annotation.JsonValue; public void setCode(Integer code) { this.code = code; - }/** + } + +/** **/ public ModelApiResponse type(String type) { this.type = type; @@ -56,7 +58,9 @@ import com.fasterxml.jackson.annotation.JsonValue; public void setType(String type) { this.type = type; - }/** + } + +/** **/ public ModelApiResponse message(String message) { this.message = message; @@ -76,6 +80,7 @@ import com.fasterxml.jackson.annotation.JsonValue; this.message = message; } + @Override public boolean equals(Object o) { if (this == o) { diff --git a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/ModelReturn.java b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/ModelReturn.java index 30180e1f251..6d6cb5b806f 100644 --- a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/ModelReturn.java +++ b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/ModelReturn.java @@ -40,6 +40,7 @@ import com.fasterxml.jackson.annotation.JsonValue; this._return = _return; } + @Override public boolean equals(Object o) { if (this == o) { diff --git a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/Name.java b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/Name.java index 199e9772bf0..6fd504dbe9d 100644 --- a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/Name.java +++ b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/Name.java @@ -42,7 +42,9 @@ import com.fasterxml.jackson.annotation.JsonValue; public void setName(Integer name) { this.name = name; - }/** + } + +/** **/ public Name snakeCase(Integer snakeCase) { this.snakeCase = snakeCase; @@ -60,7 +62,9 @@ import com.fasterxml.jackson.annotation.JsonValue; public void setSnakeCase(Integer snakeCase) { this.snakeCase = snakeCase; - }/** + } + +/** **/ public Name property(String property) { this.property = property; @@ -78,7 +82,9 @@ import com.fasterxml.jackson.annotation.JsonValue; public void setProperty(String property) { this.property = property; - }/** + } + +/** **/ public Name _123number(Integer _123number) { this._123number = _123number; @@ -98,6 +104,7 @@ import com.fasterxml.jackson.annotation.JsonValue; this._123number = _123number; } + @Override public boolean equals(Object o) { if (this == o) { diff --git a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/NumberOnly.java b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/NumberOnly.java index 6e62b0792c7..07a70cd9da5 100644 --- a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/NumberOnly.java +++ b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/NumberOnly.java @@ -39,6 +39,7 @@ import com.fasterxml.jackson.annotation.JsonValue; this.justNumber = justNumber; } + @Override public boolean equals(Object o) { if (this == o) { 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 6a877eda5db..9929a0d5043 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 @@ -75,7 +75,9 @@ public enum StatusEnum { public void setId(Long id) { this.id = id; - }/** + } + +/** **/ public Order petId(Long petId) { this.petId = petId; @@ -93,7 +95,9 @@ public enum StatusEnum { public void setPetId(Long petId) { this.petId = petId; - }/** + } + +/** **/ public Order quantity(Integer quantity) { this.quantity = quantity; @@ -111,7 +115,9 @@ public enum StatusEnum { public void setQuantity(Integer quantity) { this.quantity = quantity; - }/** + } + +/** **/ public Order shipDate(Date shipDate) { this.shipDate = shipDate; @@ -129,7 +135,9 @@ public enum StatusEnum { public void setShipDate(Date shipDate) { this.shipDate = shipDate; - }/** + } + +/** * Order Status **/ public Order status(StatusEnum status) { @@ -148,7 +156,9 @@ public enum StatusEnum { public void setStatus(StatusEnum status) { this.status = status; - }/** + } + +/** **/ public Order complete(Boolean complete) { this.complete = complete; @@ -168,6 +178,7 @@ public enum StatusEnum { this.complete = complete; } + @Override public boolean equals(Object o) { if (this == o) { diff --git a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/OuterComposite.java b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/OuterComposite.java index 118a92239cb..6e34a0e0a80 100644 --- a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/OuterComposite.java +++ b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/OuterComposite.java @@ -39,7 +39,9 @@ import com.fasterxml.jackson.annotation.JsonValue; public void setMyNumber(BigDecimal myNumber) { this.myNumber = myNumber; - }/** + } + +/** **/ public OuterComposite myString(String myString) { this.myString = myString; @@ -57,7 +59,9 @@ import com.fasterxml.jackson.annotation.JsonValue; public void setMyString(String myString) { this.myString = myString; - }/** + } + +/** **/ public OuterComposite myBoolean(Boolean myBoolean) { this.myBoolean = myBoolean; @@ -77,6 +81,7 @@ import com.fasterxml.jackson.annotation.JsonValue; this.myBoolean = myBoolean; } + @Override public boolean equals(Object o) { if (this == o) { 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 c0e131f545d..63e1d1abbd3 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 @@ -80,7 +80,9 @@ public enum StatusEnum { public void setId(Long id) { this.id = id; - }/** + } + +/** **/ public Pet category(Category category) { this.category = category; @@ -98,7 +100,9 @@ public enum StatusEnum { public void setCategory(Category category) { this.category = category; - }/** + } + +/** **/ public Pet name(String name) { this.name = name; @@ -117,7 +121,9 @@ public enum StatusEnum { public void setName(String name) { this.name = name; - }/** + } + +/** **/ public Pet photoUrls(Set photoUrls) { this.photoUrls = photoUrls; @@ -136,7 +142,9 @@ public enum StatusEnum { public void setPhotoUrls(Set photoUrls) { this.photoUrls = photoUrls; - }/** + } + +/** **/ public Pet tags(List tags) { this.tags = tags; @@ -154,7 +162,9 @@ public enum StatusEnum { public void setTags(List tags) { this.tags = tags; - }/** + } + +/** * pet status in the store **/ public Pet status(StatusEnum status) { @@ -175,6 +185,7 @@ public enum StatusEnum { this.status = status; } + @Override public boolean equals(Object o) { if (this == o) { diff --git a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/ReadOnlyFirst.java b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/ReadOnlyFirst.java index 8ab6292e7f6..72efcebf52c 100644 --- a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/ReadOnlyFirst.java +++ b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/ReadOnlyFirst.java @@ -37,7 +37,9 @@ import com.fasterxml.jackson.annotation.JsonValue; public void setBar(String bar) { this.bar = bar; - }/** + } + +/** **/ public ReadOnlyFirst baz(String baz) { this.baz = baz; @@ -57,6 +59,7 @@ import com.fasterxml.jackson.annotation.JsonValue; this.baz = baz; } + @Override public boolean equals(Object o) { if (this == o) { diff --git a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/SpecialModelName.java b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/SpecialModelName.java index 61f7ae1e722..ece6b68dc3a 100644 --- a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/SpecialModelName.java +++ b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/SpecialModelName.java @@ -38,6 +38,7 @@ import com.fasterxml.jackson.annotation.JsonValue; this.$specialPropertyName = $specialPropertyName; } + @Override public boolean equals(Object o) { if (this == o) { diff --git a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/Tag.java b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/Tag.java index 5f855730981..1c7c5198894 100644 --- a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/Tag.java +++ b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/Tag.java @@ -37,7 +37,9 @@ import com.fasterxml.jackson.annotation.JsonValue; public void setId(Long id) { this.id = id; - }/** + } + +/** **/ public Tag name(String name) { this.name = name; @@ -57,6 +59,7 @@ import com.fasterxml.jackson.annotation.JsonValue; this.name = name; } + @Override public boolean equals(Object o) { if (this == o) { 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 8ad93d7553d..502c22c455e 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 @@ -44,7 +44,9 @@ import com.fasterxml.jackson.annotation.JsonValue; public void setStringItem(String stringItem) { this.stringItem = stringItem; - }/** + } + +/** **/ public TypeHolderDefault numberItem(BigDecimal numberItem) { this.numberItem = numberItem; @@ -63,7 +65,9 @@ import com.fasterxml.jackson.annotation.JsonValue; public void setNumberItem(BigDecimal numberItem) { this.numberItem = numberItem; - }/** + } + +/** **/ public TypeHolderDefault integerItem(Integer integerItem) { this.integerItem = integerItem; @@ -82,7 +86,9 @@ import com.fasterxml.jackson.annotation.JsonValue; public void setIntegerItem(Integer integerItem) { this.integerItem = integerItem; - }/** + } + +/** **/ public TypeHolderDefault boolItem(Boolean boolItem) { this.boolItem = boolItem; @@ -101,7 +107,9 @@ import com.fasterxml.jackson.annotation.JsonValue; public void setBoolItem(Boolean boolItem) { this.boolItem = boolItem; - }/** + } + +/** **/ public TypeHolderDefault arrayItem(List arrayItem) { this.arrayItem = arrayItem; @@ -122,6 +130,7 @@ import com.fasterxml.jackson.annotation.JsonValue; this.arrayItem = arrayItem; } + @Override public boolean equals(Object o) { if (this == o) { 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 fe7be2d28e3..fb31859dedd 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 @@ -45,7 +45,9 @@ import com.fasterxml.jackson.annotation.JsonValue; public void setStringItem(String stringItem) { this.stringItem = stringItem; - }/** + } + +/** **/ public TypeHolderExample numberItem(BigDecimal numberItem) { this.numberItem = numberItem; @@ -64,7 +66,9 @@ import com.fasterxml.jackson.annotation.JsonValue; public void setNumberItem(BigDecimal numberItem) { this.numberItem = numberItem; - }/** + } + +/** **/ public TypeHolderExample floatItem(Float floatItem) { this.floatItem = floatItem; @@ -83,7 +87,9 @@ import com.fasterxml.jackson.annotation.JsonValue; public void setFloatItem(Float floatItem) { this.floatItem = floatItem; - }/** + } + +/** **/ public TypeHolderExample integerItem(Integer integerItem) { this.integerItem = integerItem; @@ -102,7 +108,9 @@ import com.fasterxml.jackson.annotation.JsonValue; public void setIntegerItem(Integer integerItem) { this.integerItem = integerItem; - }/** + } + +/** **/ public TypeHolderExample boolItem(Boolean boolItem) { this.boolItem = boolItem; @@ -121,7 +129,9 @@ import com.fasterxml.jackson.annotation.JsonValue; public void setBoolItem(Boolean boolItem) { this.boolItem = boolItem; - }/** + } + +/** **/ public TypeHolderExample arrayItem(List arrayItem) { this.arrayItem = arrayItem; @@ -142,6 +152,7 @@ import com.fasterxml.jackson.annotation.JsonValue; this.arrayItem = arrayItem; } + @Override public boolean equals(Object o) { if (this == o) { diff --git a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/User.java b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/User.java index 6e82dd75fed..ad16074f63b 100644 --- a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/User.java +++ b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/User.java @@ -43,7 +43,9 @@ import com.fasterxml.jackson.annotation.JsonValue; public void setId(Long id) { this.id = id; - }/** + } + +/** **/ public User username(String username) { this.username = username; @@ -61,7 +63,9 @@ import com.fasterxml.jackson.annotation.JsonValue; public void setUsername(String username) { this.username = username; - }/** + } + +/** **/ public User firstName(String firstName) { this.firstName = firstName; @@ -79,7 +83,9 @@ import com.fasterxml.jackson.annotation.JsonValue; public void setFirstName(String firstName) { this.firstName = firstName; - }/** + } + +/** **/ public User lastName(String lastName) { this.lastName = lastName; @@ -97,7 +103,9 @@ import com.fasterxml.jackson.annotation.JsonValue; public void setLastName(String lastName) { this.lastName = lastName; - }/** + } + +/** **/ public User email(String email) { this.email = email; @@ -115,7 +123,9 @@ import com.fasterxml.jackson.annotation.JsonValue; public void setEmail(String email) { this.email = email; - }/** + } + +/** **/ public User password(String password) { this.password = password; @@ -133,7 +143,9 @@ import com.fasterxml.jackson.annotation.JsonValue; public void setPassword(String password) { this.password = password; - }/** + } + +/** **/ public User phone(String phone) { this.phone = phone; @@ -151,7 +163,9 @@ import com.fasterxml.jackson.annotation.JsonValue; public void setPhone(String phone) { this.phone = phone; - }/** + } + +/** * User Status **/ public User userStatus(Integer userStatus) { @@ -172,6 +186,7 @@ import com.fasterxml.jackson.annotation.JsonValue; this.userStatus = userStatus; } + @Override public boolean equals(Object o) { if (this == o) { 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 596002cf3a0..15a5d35673f 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 @@ -67,7 +67,9 @@ import com.fasterxml.jackson.annotation.JsonValue; public void setAttributeString(String attributeString) { this.attributeString = attributeString; - }/** + } + +/** **/ public XmlItem attributeNumber(BigDecimal attributeNumber) { this.attributeNumber = attributeNumber; @@ -85,7 +87,9 @@ import com.fasterxml.jackson.annotation.JsonValue; public void setAttributeNumber(BigDecimal attributeNumber) { this.attributeNumber = attributeNumber; - }/** + } + +/** **/ public XmlItem attributeInteger(Integer attributeInteger) { this.attributeInteger = attributeInteger; @@ -103,7 +107,9 @@ import com.fasterxml.jackson.annotation.JsonValue; public void setAttributeInteger(Integer attributeInteger) { this.attributeInteger = attributeInteger; - }/** + } + +/** **/ public XmlItem attributeBoolean(Boolean attributeBoolean) { this.attributeBoolean = attributeBoolean; @@ -121,7 +127,9 @@ import com.fasterxml.jackson.annotation.JsonValue; public void setAttributeBoolean(Boolean attributeBoolean) { this.attributeBoolean = attributeBoolean; - }/** + } + +/** **/ public XmlItem wrappedArray(List wrappedArray) { this.wrappedArray = wrappedArray; @@ -139,7 +147,9 @@ import com.fasterxml.jackson.annotation.JsonValue; public void setWrappedArray(List wrappedArray) { this.wrappedArray = wrappedArray; - }/** + } + +/** **/ public XmlItem nameString(String nameString) { this.nameString = nameString; @@ -157,7 +167,9 @@ import com.fasterxml.jackson.annotation.JsonValue; public void setNameString(String nameString) { this.nameString = nameString; - }/** + } + +/** **/ public XmlItem nameNumber(BigDecimal nameNumber) { this.nameNumber = nameNumber; @@ -175,7 +187,9 @@ import com.fasterxml.jackson.annotation.JsonValue; public void setNameNumber(BigDecimal nameNumber) { this.nameNumber = nameNumber; - }/** + } + +/** **/ public XmlItem nameInteger(Integer nameInteger) { this.nameInteger = nameInteger; @@ -193,7 +207,9 @@ import com.fasterxml.jackson.annotation.JsonValue; public void setNameInteger(Integer nameInteger) { this.nameInteger = nameInteger; - }/** + } + +/** **/ public XmlItem nameBoolean(Boolean nameBoolean) { this.nameBoolean = nameBoolean; @@ -211,7 +227,9 @@ import com.fasterxml.jackson.annotation.JsonValue; public void setNameBoolean(Boolean nameBoolean) { this.nameBoolean = nameBoolean; - }/** + } + +/** **/ public XmlItem nameArray(List nameArray) { this.nameArray = nameArray; @@ -229,7 +247,9 @@ import com.fasterxml.jackson.annotation.JsonValue; public void setNameArray(List nameArray) { this.nameArray = nameArray; - }/** + } + +/** **/ public XmlItem nameWrappedArray(List nameWrappedArray) { this.nameWrappedArray = nameWrappedArray; @@ -247,7 +267,9 @@ import com.fasterxml.jackson.annotation.JsonValue; public void setNameWrappedArray(List nameWrappedArray) { this.nameWrappedArray = nameWrappedArray; - }/** + } + +/** **/ public XmlItem prefixString(String prefixString) { this.prefixString = prefixString; @@ -265,7 +287,9 @@ import com.fasterxml.jackson.annotation.JsonValue; public void setPrefixString(String prefixString) { this.prefixString = prefixString; - }/** + } + +/** **/ public XmlItem prefixNumber(BigDecimal prefixNumber) { this.prefixNumber = prefixNumber; @@ -283,7 +307,9 @@ import com.fasterxml.jackson.annotation.JsonValue; public void setPrefixNumber(BigDecimal prefixNumber) { this.prefixNumber = prefixNumber; - }/** + } + +/** **/ public XmlItem prefixInteger(Integer prefixInteger) { this.prefixInteger = prefixInteger; @@ -301,7 +327,9 @@ import com.fasterxml.jackson.annotation.JsonValue; public void setPrefixInteger(Integer prefixInteger) { this.prefixInteger = prefixInteger; - }/** + } + +/** **/ public XmlItem prefixBoolean(Boolean prefixBoolean) { this.prefixBoolean = prefixBoolean; @@ -319,7 +347,9 @@ import com.fasterxml.jackson.annotation.JsonValue; public void setPrefixBoolean(Boolean prefixBoolean) { this.prefixBoolean = prefixBoolean; - }/** + } + +/** **/ public XmlItem prefixArray(List prefixArray) { this.prefixArray = prefixArray; @@ -337,7 +367,9 @@ import com.fasterxml.jackson.annotation.JsonValue; public void setPrefixArray(List prefixArray) { this.prefixArray = prefixArray; - }/** + } + +/** **/ public XmlItem prefixWrappedArray(List prefixWrappedArray) { this.prefixWrappedArray = prefixWrappedArray; @@ -355,7 +387,9 @@ import com.fasterxml.jackson.annotation.JsonValue; public void setPrefixWrappedArray(List prefixWrappedArray) { this.prefixWrappedArray = prefixWrappedArray; - }/** + } + +/** **/ public XmlItem namespaceString(String namespaceString) { this.namespaceString = namespaceString; @@ -373,7 +407,9 @@ import com.fasterxml.jackson.annotation.JsonValue; public void setNamespaceString(String namespaceString) { this.namespaceString = namespaceString; - }/** + } + +/** **/ public XmlItem namespaceNumber(BigDecimal namespaceNumber) { this.namespaceNumber = namespaceNumber; @@ -391,7 +427,9 @@ import com.fasterxml.jackson.annotation.JsonValue; public void setNamespaceNumber(BigDecimal namespaceNumber) { this.namespaceNumber = namespaceNumber; - }/** + } + +/** **/ public XmlItem namespaceInteger(Integer namespaceInteger) { this.namespaceInteger = namespaceInteger; @@ -409,7 +447,9 @@ import com.fasterxml.jackson.annotation.JsonValue; public void setNamespaceInteger(Integer namespaceInteger) { this.namespaceInteger = namespaceInteger; - }/** + } + +/** **/ public XmlItem namespaceBoolean(Boolean namespaceBoolean) { this.namespaceBoolean = namespaceBoolean; @@ -427,7 +467,9 @@ import com.fasterxml.jackson.annotation.JsonValue; public void setNamespaceBoolean(Boolean namespaceBoolean) { this.namespaceBoolean = namespaceBoolean; - }/** + } + +/** **/ public XmlItem namespaceArray(List namespaceArray) { this.namespaceArray = namespaceArray; @@ -445,7 +487,9 @@ import com.fasterxml.jackson.annotation.JsonValue; public void setNamespaceArray(List namespaceArray) { this.namespaceArray = namespaceArray; - }/** + } + +/** **/ public XmlItem namespaceWrappedArray(List namespaceWrappedArray) { this.namespaceWrappedArray = namespaceWrappedArray; @@ -463,7 +507,9 @@ import com.fasterxml.jackson.annotation.JsonValue; public void setNamespaceWrappedArray(List namespaceWrappedArray) { this.namespaceWrappedArray = namespaceWrappedArray; - }/** + } + +/** **/ public XmlItem prefixNsString(String prefixNsString) { this.prefixNsString = prefixNsString; @@ -481,7 +527,9 @@ import com.fasterxml.jackson.annotation.JsonValue; public void setPrefixNsString(String prefixNsString) { this.prefixNsString = prefixNsString; - }/** + } + +/** **/ public XmlItem prefixNsNumber(BigDecimal prefixNsNumber) { this.prefixNsNumber = prefixNsNumber; @@ -499,7 +547,9 @@ import com.fasterxml.jackson.annotation.JsonValue; public void setPrefixNsNumber(BigDecimal prefixNsNumber) { this.prefixNsNumber = prefixNsNumber; - }/** + } + +/** **/ public XmlItem prefixNsInteger(Integer prefixNsInteger) { this.prefixNsInteger = prefixNsInteger; @@ -517,7 +567,9 @@ import com.fasterxml.jackson.annotation.JsonValue; public void setPrefixNsInteger(Integer prefixNsInteger) { this.prefixNsInteger = prefixNsInteger; - }/** + } + +/** **/ public XmlItem prefixNsBoolean(Boolean prefixNsBoolean) { this.prefixNsBoolean = prefixNsBoolean; @@ -535,7 +587,9 @@ import com.fasterxml.jackson.annotation.JsonValue; public void setPrefixNsBoolean(Boolean prefixNsBoolean) { this.prefixNsBoolean = prefixNsBoolean; - }/** + } + +/** **/ public XmlItem prefixNsArray(List prefixNsArray) { this.prefixNsArray = prefixNsArray; @@ -553,7 +607,9 @@ import com.fasterxml.jackson.annotation.JsonValue; public void setPrefixNsArray(List prefixNsArray) { this.prefixNsArray = prefixNsArray; - }/** + } + +/** **/ public XmlItem prefixNsWrappedArray(List prefixNsWrappedArray) { this.prefixNsWrappedArray = prefixNsWrappedArray; @@ -573,6 +629,7 @@ import com.fasterxml.jackson.annotation.JsonValue; this.prefixNsWrappedArray = prefixNsWrappedArray; } + @Override public boolean equals(Object o) { if (this == o) { 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 da95378bbc8..7d2de524fc6 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 @@ -2225,10 +2225,12 @@ components: properties: breed: type: string + type: object Cat_allOf: properties: declawed: type: boolean + type: object BigCat_allOf: properties: kind: @@ -2238,6 +2240,7 @@ components: - leopards - jaguars type: string + type: object securitySchemes: petstore_auth: flows: @@ -2258,3 +2261,4 @@ components: http_basic_test: scheme: basic type: http +x-original-swagger-version: "2.0" diff --git a/samples/server/petstore/jaxrs-spec-interface/.openapi-generator/VERSION b/samples/server/petstore/jaxrs-spec-interface/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/server/petstore/jaxrs-spec-interface/.openapi-generator/VERSION +++ b/samples/server/petstore/jaxrs-spec-interface/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/server/petstore/jaxrs-spec/.openapi-generator/VERSION b/samples/server/petstore/jaxrs-spec/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/server/petstore/jaxrs-spec/.openapi-generator/VERSION +++ b/samples/server/petstore/jaxrs-spec/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/server/petstore/jaxrs/jersey1-useTags/.openapi-generator/VERSION b/samples/server/petstore/jaxrs/jersey1-useTags/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/server/petstore/jaxrs/jersey1-useTags/.openapi-generator/VERSION +++ b/samples/server/petstore/jaxrs/jersey1-useTags/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/server/petstore/jaxrs/jersey1/.openapi-generator/VERSION b/samples/server/petstore/jaxrs/jersey1/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/server/petstore/jaxrs/jersey1/.openapi-generator/VERSION +++ b/samples/server/petstore/jaxrs/jersey1/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/server/petstore/jaxrs/jersey2-useTags/.openapi-generator/VERSION b/samples/server/petstore/jaxrs/jersey2-useTags/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/server/petstore/jaxrs/jersey2-useTags/.openapi-generator/VERSION +++ b/samples/server/petstore/jaxrs/jersey2-useTags/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/server/petstore/jaxrs/jersey2-useTags/pom.xml b/samples/server/petstore/jaxrs/jersey2-useTags/pom.xml index d534555f77d..68907b27d0d 100644 --- a/samples/server/petstore/jaxrs/jersey2-useTags/pom.xml +++ b/samples/server/petstore/jaxrs/jersey2-useTags/pom.xml @@ -186,7 +186,7 @@ 2.22.2 2.9.9 4.13.1 - 1.1.7 + 1.2.0 2.5 UTF-8 diff --git a/samples/server/petstore/jaxrs/jersey2/.openapi-generator/VERSION b/samples/server/petstore/jaxrs/jersey2/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/server/petstore/jaxrs/jersey2/.openapi-generator/VERSION +++ b/samples/server/petstore/jaxrs/jersey2/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/server/petstore/jaxrs/jersey2/pom.xml b/samples/server/petstore/jaxrs/jersey2/pom.xml index 3acc7ea707b..9f547514d92 100644 --- a/samples/server/petstore/jaxrs/jersey2/pom.xml +++ b/samples/server/petstore/jaxrs/jersey2/pom.xml @@ -186,7 +186,7 @@ 2.22.2 2.9.9 4.13.1 - 1.1.7 + 1.2.0 2.5 UTF-8 diff --git a/samples/server/petstore/kotlin-server/ktor/.openapi-generator/VERSION b/samples/server/petstore/kotlin-server/ktor/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/server/petstore/kotlin-server/ktor/.openapi-generator/VERSION +++ b/samples/server/petstore/kotlin-server/ktor/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/server/petstore/kotlin-server/ktor/README.md b/samples/server/petstore/kotlin-server/ktor/README.md index 69886a32d5a..6a324199804 100644 --- a/samples/server/petstore/kotlin-server/ktor/README.md +++ b/samples/server/petstore/kotlin-server/ktor/README.md @@ -2,12 +2,16 @@ This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. +<<<<<<< HEAD Generated by OpenAPI Generator 6.0.0-SNAPSHOT. +======= +Generated by OpenAPI Generator 5.3.0-SNAPSHOT. +>>>>>>> origin/5.3.x ## Requires -* Kotlin 1.4.31 -* Gradle 6.8.2 +* Kotlin 1.4.32 +* Gradle 6.9 ## Build diff --git a/samples/server/petstore/kotlin-server/ktor/build.gradle b/samples/server/petstore/kotlin-server/ktor/build.gradle index c69f129160f..ebf0c988068 100644 --- a/samples/server/petstore/kotlin-server/ktor/build.gradle +++ b/samples/server/petstore/kotlin-server/ktor/build.gradle @@ -1,37 +1,35 @@ -group 'org.openapitools' -version '1.0.0' +group "org.openapitools" +version "1.0.0" wrapper { - gradleVersion = '6.8.2' + gradleVersion = "6.9" distributionUrl = "https://services.gradle.org/distributions/gradle-$gradleVersion-all.zip" } buildscript { - ext.kotlin_version = '1.4.31' - ext.ktor_version = '1.5.2' - ext.shadow_version = '2.0.3' + ext.kotlin_version = "1.4.32" + ext.ktor_version = "1.5.4" + ext.shadow_version = "6.1.0" repositories { maven { url "https://repo1.maven.org/maven2" } - maven { - url = "https://plugins.gradle.org/m2/" - } + maven { url "https://plugins.gradle.org/m2/" } } dependencies { - classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" - classpath "com.github.jengelman.gradle.plugins:shadow:$shadow_version" + classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version") + classpath("com.github.jengelman.gradle.plugins:shadow:$shadow_version") } } -apply plugin: 'java' -apply plugin: 'kotlin' -apply plugin: 'application' +apply plugin: "java" +apply plugin: "kotlin" +apply plugin: "application" mainClassName = "io.ktor.server.netty.DevelopmentEngine" -// Initialization order with shadow 2.0.1 and Gradle 6.8.2 is weird. +// Initialization order with shadow 2.0.1 and Gradle 6.9 is weird. // See https://github.com/johnrengelman/shadow/issues/336#issuecomment-355402508 -apply plugin: 'com.github.johnrengelman.shadow' +apply plugin: "com.github.johnrengelman.shadow" sourceCompatibility = 1.8 @@ -44,26 +42,28 @@ compileTestKotlin { } shadowJar { - baseName = 'kotlin-server' + baseName = "kotlin-server" classifier = null version = null } repositories { - maven { url "https://repo1.maven.org/maven2" } - maven { url "https://dl.bintray.com/kotlin/ktor" } - maven { url "https://dl.bintray.com/kotlin/kotlinx" } + maven { setUrl("https://repo1.maven.org/maven2") } + maven { setUrl("https://dl.bintray.com/kotlin/ktor") } + maven { setUrl("https://dl.bintray.com/kotlin/kotlinx") } } dependencies { - compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version" - compile "io.ktor:ktor-server-netty:$ktor_version" - compile "io.ktor:ktor-metrics:$ktor_version" - compile "io.ktor:ktor-auth:$ktor_version" - compile "io.ktor:ktor-locations:$ktor_version" - compile "io.ktor:ktor-gson:$ktor_version" - compile "io.ktor:ktor-client-core:$ktor_version" - compile "io.ktor:ktor-client-apache:$ktor_version" - compile "ch.qos.logback:logback-classic:1.2.1" - testCompile group: 'junit', name: 'junit', version: '4.13' + implementation("org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version") + implementation("ch.qos.logback:logback-classic:1.2.1") + implementation("com.typesafe:config:1.4.1") + implementation("io.ktor:ktor-auth:$ktor_version") + implementation("io.ktor:ktor-client-apache:$ktor_version") + implementation("io.ktor:ktor-gson:$ktor_version") + implementation("io.ktor:ktor-locations:$ktor_version") + implementation("io.dropwizard.metrics:metrics-core:4.1.18") + implementation("io.ktor:ktor-metrics:$ktor_version") + implementation("io.ktor:ktor-server-netty:$ktor_version") + + testImplementation("junit:junit:4.13.2") } diff --git a/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/AppMain.kt b/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/AppMain.kt index 54658d6ba5d..9b0468fb568 100644 --- a/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/AppMain.kt +++ b/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/AppMain.kt @@ -1,31 +1,21 @@ package org.openapitools.server import com.codahale.metrics.Slf4jReporter +import io.ktor.application.* +import io.ktor.features.* +import io.ktor.gson.* +import io.ktor.http.* +import io.ktor.locations.* +import io.ktor.metrics.dropwizard.* +import java.util.concurrent.TimeUnit +import io.ktor.routing.* +import io.ktor.util.* import com.typesafe.config.ConfigFactory -import io.ktor.application.Application -import io.ktor.application.ApplicationStopping -import io.ktor.application.install -import io.ktor.application.log +import io.ktor.auth.* import io.ktor.client.HttpClient import io.ktor.client.engine.apache.Apache import io.ktor.config.HoconApplicationConfig -import io.ktor.features.AutoHeadResponse -import io.ktor.features.Compression -import io.ktor.features.ContentNegotiation -import io.ktor.features.DefaultHeaders -import io.ktor.features.HSTS -import io.ktor.gson.GsonConverter -import io.ktor.http.ContentType -import io.ktor.locations.KtorExperimentalLocationsAPI -import io.ktor.locations.Locations -import io.ktor.routing.Routing -import java.util.concurrent.TimeUnit -import io.ktor.auth.Authentication -import io.ktor.auth.oauth -import io.ktor.metrics.dropwizard.DropwizardMetrics -import org.openapitools.server.infrastructure.ApiKeyCredential -import org.openapitools.server.infrastructure.ApiPrincipal -import org.openapitools.server.infrastructure.apiKeyAuth +import org.openapitools.server.infrastructure.* import org.openapitools.server.apis.PetApi import org.openapitools.server.apis.StoreApi import org.openapitools.server.apis.UserApi @@ -37,6 +27,7 @@ object HTTP { val client = HttpClient(Apache) } +@KtorExperimentalAPI @KtorExperimentalLocationsAPI fun Application.main() { install(DefaultHeaders) @@ -51,10 +42,10 @@ fun Application.main() { install(ContentNegotiation) { register(ContentType.Application.Json, GsonConverter()) } - install(AutoHeadResponse) // see http://ktor.io/features/autoheadresponse.html - install(HSTS, ApplicationHstsConfiguration()) // see http://ktor.io/features/hsts.html - install(Compression, ApplicationCompressionConfiguration()) // see http://ktor.io/features/compression.html - install(Locations) // see http://ktor.io/features/locations.html + install(AutoHeadResponse) // see https://ktor.io/docs/autoheadresponse.html + install(Compression, ApplicationCompressionConfiguration()) // see https://ktor.io/docs/compression.html + install(HSTS, ApplicationHstsConfiguration()) // see https://ktor.io/docs/hsts.html + install(Locations) // see https://ktor.io/docs/features-locations.html install(Authentication) { // "Implement API key auth (api_key) for parameter name 'api_key'." apiKeyAuth("api_key") { @@ -80,8 +71,4 @@ fun Application.main() { UserApi() } - - environment.monitor.subscribe(ApplicationStopping) { - HTTP.client.close() - } } diff --git a/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/Configuration.kt b/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/Configuration.kt index 8483e64319d..93aa1c72822 100644 --- a/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/Configuration.kt +++ b/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/Configuration.kt @@ -1,16 +1,13 @@ package org.openapitools.server // Use this file to hold package-level internal functions that return receiver object passed to the `install` method. -import io.ktor.auth.OAuthServerSettings -import io.ktor.features.Compression -import io.ktor.features.HSTS -import io.ktor.features.deflate -import io.ktor.features.gzip -import io.ktor.features.minimumSize -import io.ktor.http.HttpMethod +import io.ktor.auth.* +import io.ktor.features.* +import io.ktor.http.* +import io.ktor.util.* +import java.time.Duration import java.util.concurrent.TimeUnit - /** * Application block for [HSTS] configuration. * @@ -67,8 +64,8 @@ val ApplicationAuthProviders: Map = listOf) /** @@ -46,7 +43,6 @@ object Paths { * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. * @param tags Tags to filter by */ - @KtorExperimentalLocationsAPI @Location("/pet/findByTags") class findPetsByTags(val tags: kotlin.collections.List) /** @@ -54,7 +50,6 @@ object Paths { * Returns a single pet * @param petId ID of pet to return */ - @KtorExperimentalLocationsAPI @Location("/pet/{petId}") class getPetById(val petId: kotlin.Long) /** @@ -62,7 +57,6 @@ object Paths { * * @param body Pet object that needs to be added to the store */ - @KtorExperimentalLocationsAPI @Location("/pet") class updatePet(val body: Pet) /** @@ -72,7 +66,6 @@ object Paths { * @param name Updated name of the pet (optional) * @param status Updated status of the pet (optional) */ - @KtorExperimentalLocationsAPI @Location("/pet/{petId}") class updatePetWithForm(val petId: kotlin.Long, val name: kotlin.String? = null, val status: kotlin.String? = null) /** @@ -82,7 +75,6 @@ object Paths { * @param additionalMetadata Additional data to pass to server (optional) * @param file file to upload (optional) */ - @KtorExperimentalLocationsAPI @Location("/pet/{petId}/uploadImage") class uploadFile(val petId: kotlin.Long, val additionalMetadata: kotlin.String? = null, val file: java.io.File? = null) /** @@ -90,22 +82,19 @@ object Paths { * 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 */ - @KtorExperimentalLocationsAPI @Location("/store/order/{orderId}") class deleteOrder(val orderId: kotlin.String) /** * Returns pet inventories by status * Returns a map of status codes to quantities */ - @KtorExperimentalLocationsAPI - @Location("/store/inventory") class getInventory() + @Location("/store/inventory") object getInventory /** * Find purchase order by ID * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions * @param orderId ID of pet that needs to be fetched */ - @KtorExperimentalLocationsAPI @Location("/store/order/{orderId}") class getOrderById(val orderId: kotlin.Long) /** @@ -113,7 +102,6 @@ object Paths { * * @param body order placed for purchasing the pet */ - @KtorExperimentalLocationsAPI @Location("/store/order") class placeOrder(val body: Order) /** @@ -121,7 +109,6 @@ object Paths { * This can only be done by the logged in user. * @param body Created user object */ - @KtorExperimentalLocationsAPI @Location("/user") class createUser(val body: User) /** @@ -129,7 +116,6 @@ object Paths { * * @param body List of user object */ - @KtorExperimentalLocationsAPI @Location("/user/createWithArray") class createUsersWithArrayInput(val body: kotlin.collections.List) /** @@ -137,7 +123,6 @@ object Paths { * * @param body List of user object */ - @KtorExperimentalLocationsAPI @Location("/user/createWithList") class createUsersWithListInput(val body: kotlin.collections.List) /** @@ -145,7 +130,6 @@ object Paths { * This can only be done by the logged in user. * @param username The name that needs to be deleted */ - @KtorExperimentalLocationsAPI @Location("/user/{username}") class deleteUser(val username: kotlin.String) /** @@ -153,7 +137,6 @@ object Paths { * * @param username The name that needs to be fetched. Use user1 for testing. */ - @KtorExperimentalLocationsAPI @Location("/user/{username}") class getUserByName(val username: kotlin.String) /** @@ -162,15 +145,13 @@ object Paths { * @param username The user name for login * @param password The password for login in clear text */ - @KtorExperimentalLocationsAPI @Location("/user/login") class loginUser(val username: kotlin.String, val password: kotlin.String) /** * Logs out current logged in user session * */ - @KtorExperimentalLocationsAPI - @Location("/user/logout") class logoutUser() + @Location("/user/logout") object logoutUser /** * Updated user @@ -178,7 +159,6 @@ object Paths { * @param username name that need to be deleted * @param body Updated user object */ - @KtorExperimentalLocationsAPI @Location("/user/{username}") class updateUser(val username: kotlin.String, val body: User) } 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 9226541eb34..95f5d7fb880 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 @@ -12,29 +12,14 @@ package org.openapitools.server.apis import com.google.gson.Gson -import io.ktor.application.call -import io.ktor.auth.UserIdPrincipal -import io.ktor.auth.authentication -import io.ktor.auth.authenticate -import io.ktor.auth.OAuthAccessTokenResponse -import io.ktor.auth.OAuthServerSettings -import io.ktor.http.ContentType -import io.ktor.http.HttpStatusCode -import io.ktor.response.respond -import io.ktor.response.respondText -import io.ktor.routing.Route +import io.ktor.application.* +import io.ktor.auth.* +import io.ktor.http.* +import io.ktor.response.* import org.openapitools.server.Paths -import io.ktor.locations.KtorExperimentalLocationsAPI -import io.ktor.locations.delete -import io.ktor.locations.get -import io.ktor.locations.post -import io.ktor.locations.put -import io.ktor.locations.options -import io.ktor.locations.head - +import io.ktor.locations.* +import io.ktor.routing.* import org.openapitools.server.infrastructure.ApiPrincipal - - import org.openapitools.server.models.ApiResponse import org.openapitools.server.models.Pet @@ -42,6 +27,7 @@ import org.openapitools.server.models.Pet fun Route.PetApi() { val gson = Gson() val empty = mutableMapOf() + authenticate("petstore_auth") { post { val principal = call.authentication.principal()!! 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 2e5f4ab8b96..b195797a020 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 @@ -12,35 +12,21 @@ package org.openapitools.server.apis import com.google.gson.Gson -import io.ktor.application.call -import io.ktor.auth.UserIdPrincipal -import io.ktor.auth.authentication -import io.ktor.auth.authenticate -import io.ktor.auth.OAuthAccessTokenResponse -import io.ktor.auth.OAuthServerSettings -import io.ktor.http.ContentType -import io.ktor.http.HttpStatusCode -import io.ktor.response.respond -import io.ktor.response.respondText -import io.ktor.routing.Route +import io.ktor.application.* +import io.ktor.auth.* +import io.ktor.http.* +import io.ktor.response.* import org.openapitools.server.Paths -import io.ktor.locations.KtorExperimentalLocationsAPI -import io.ktor.locations.delete -import io.ktor.locations.get -import io.ktor.locations.post -import io.ktor.locations.put -import io.ktor.locations.options -import io.ktor.locations.head - +import io.ktor.locations.* +import io.ktor.routing.* import org.openapitools.server.infrastructure.ApiPrincipal - - import org.openapitools.server.models.Order @KtorExperimentalLocationsAPI fun Route.StoreApi() { val gson = Gson() val empty = mutableMapOf() + delete { call.respond(HttpStatusCode.NotImplemented) } 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 e248d75ae0c..1871c4b3097 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 @@ -12,35 +12,21 @@ package org.openapitools.server.apis import com.google.gson.Gson -import io.ktor.application.call -import io.ktor.auth.UserIdPrincipal -import io.ktor.auth.authentication -import io.ktor.auth.authenticate -import io.ktor.auth.OAuthAccessTokenResponse -import io.ktor.auth.OAuthServerSettings -import io.ktor.http.ContentType -import io.ktor.http.HttpStatusCode -import io.ktor.response.respond -import io.ktor.response.respondText -import io.ktor.routing.Route +import io.ktor.application.* +import io.ktor.auth.* +import io.ktor.http.* +import io.ktor.response.* import org.openapitools.server.Paths -import io.ktor.locations.KtorExperimentalLocationsAPI -import io.ktor.locations.delete -import io.ktor.locations.get -import io.ktor.locations.post -import io.ktor.locations.put -import io.ktor.locations.options -import io.ktor.locations.head - +import io.ktor.locations.* +import io.ktor.routing.* import org.openapitools.server.infrastructure.ApiPrincipal - - import org.openapitools.server.models.User @KtorExperimentalLocationsAPI fun Route.UserApi() { val gson = Gson() val empty = mutableMapOf() + post { call.respond(HttpStatusCode.NotImplemented) } diff --git a/samples/server/petstore/kotlin-springboot-delegate/.openapi-generator/VERSION b/samples/server/petstore/kotlin-springboot-delegate/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/server/petstore/kotlin-springboot-delegate/.openapi-generator/VERSION +++ b/samples/server/petstore/kotlin-springboot-delegate/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x 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 3249c199588..2b3942eb2a8 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,9 @@ /** +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (6.0.0-SNAPSHOT). +======= + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.3.0-SNAPSHOT). +>>>>>>> origin/5.3.x * https://openapi-generator.tech * Do not edit the class manually. */ 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 63a1dfe5d9e..847d715ffdc 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,9 @@ /** +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (6.0.0-SNAPSHOT). +======= + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.3.0-SNAPSHOT). +>>>>>>> origin/5.3.x * https://openapi-generator.tech * Do not edit the class manually. */ 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 237efa3f58c..cd6f99e4ca7 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,9 @@ /** +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (6.0.0-SNAPSHOT). +======= + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.3.0-SNAPSHOT). +>>>>>>> origin/5.3.x * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/kotlin-springboot-reactive/.openapi-generator/VERSION b/samples/server/petstore/kotlin-springboot-reactive/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/server/petstore/kotlin-springboot-reactive/.openapi-generator/VERSION +++ b/samples/server/petstore/kotlin-springboot-reactive/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/server/petstore/kotlin-springboot/.openapi-generator/VERSION b/samples/server/petstore/kotlin-springboot/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/server/petstore/kotlin-springboot/.openapi-generator/VERSION +++ b/samples/server/petstore/kotlin-springboot/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/server/petstore/php-laravel/.openapi-generator/VERSION b/samples/server/petstore/php-laravel/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/server/petstore/php-laravel/.openapi-generator/VERSION +++ b/samples/server/petstore/php-laravel/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x 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 cb3da629aaa..a0b1238d92e 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 @@ -228,6 +228,30 @@ class FakeController extends Controller return response('How about implementing testGroupParameters as a delete method ?'); } + /** + * Operation testBodyWithBinary + * + * . + * + * + * @return Http response + */ + public function testBodyWithBinary() + { + $input = Request::all(); + + //path params validation + + + //not path params validation + if (!isset($input['body'])) { + throw new \InvalidArgumentException('Missing the required parameter $body when calling testBodyWithBinary'); + } + $body = $input['body']; + + + return response('How about implementing testBodyWithBinary as a put method ?'); + } /** * Operation testBodyWithFileSchema * diff --git a/samples/server/petstore/php-laravel/lib/routes/api.php b/samples/server/petstore/php-laravel/lib/routes/api.php index 856cc66810a..fec2cea4a3c 100644 --- a/samples/server/petstore/php-laravel/lib/routes/api.php +++ b/samples/server/petstore/php-laravel/lib/routes/api.php @@ -63,10 +63,17 @@ Route::get('/v2/fake', 'FakeController@testEnumParameters'); */ Route::delete('/v2/fake', 'FakeController@testGroupParameters'); +/** + * put testBodyWithBinary + * Summary: + * Notes: For this test, the body has to be a binary file. + + */ +Route::put('/v2/fake/body-with-binary', 'FakeController@testBodyWithBinary'); /** * put testBodyWithFileSchema * Summary: - * Notes: For this test, the body for this request much reference a schema named `File`. + * Notes: For this test, the body for this request must reference a schema named `File`. */ Route::put('/v2/fake/body-with-file-schema', 'FakeController@testBodyWithFileSchema'); diff --git a/samples/server/petstore/php-lumen/.openapi-generator/VERSION b/samples/server/petstore/php-lumen/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/server/petstore/php-lumen/.openapi-generator/VERSION +++ b/samples/server/petstore/php-lumen/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x 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 86e5ae7356f..e3b631dd097 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 @@ -224,6 +224,30 @@ class FakeApi extends Controller return response('How about implementing testGroupParameters as a delete method ?'); } + /** + * Operation testBodyWithBinary + * + * . + * + * + * @return Http response + */ + public function testBodyWithBinary() + { + $input = Request::all(); + + //path params validation + + + //not path params validation + if (!isset($input['body'])) { + throw new \InvalidArgumentException('Missing the required parameter $body when calling testBodyWithBinary'); + } + $body = $input['body']; + + + return response('How about implementing testBodyWithBinary as a put method ?'); + } /** * Operation testBodyWithFileSchema * diff --git a/samples/server/petstore/php-lumen/lib/routes/web.php b/samples/server/petstore/php-lumen/lib/routes/web.php index f159b8da780..9831967079f 100644 --- a/samples/server/petstore/php-lumen/lib/routes/web.php +++ b/samples/server/petstore/php-lumen/lib/routes/web.php @@ -79,10 +79,17 @@ $router->get('/v2/fake', 'FakeApi@testEnumParameters'); */ $router->delete('/v2/fake', 'FakeApi@testGroupParameters'); +/** + * put testBodyWithBinary + * Summary: + * Notes: For this test, the body has to be a binary file. + */ +$router->put('/v2/fake/body-with-binary', 'FakeApi@testBodyWithBinary'); + /** * put testBodyWithFileSchema * Summary: - * Notes: For this test, the body for this request much reference a schema named `File`. + * Notes: For this test, the body for this request must reference a schema named `File`. */ $router->put('/v2/fake/body-with-file-schema', 'FakeApi@testBodyWithFileSchema'); diff --git a/samples/server/petstore/php-mezzio-ph-modern/.gitignore b/samples/server/petstore/php-mezzio-ph-modern/.gitignore new file mode 100644 index 00000000000..1ddcdf2a709 --- /dev/null +++ b/samples/server/petstore/php-mezzio-ph-modern/.gitignore @@ -0,0 +1,9 @@ +#based on .gitignore generated by https://github.com/zendframework/zend-expressive-skeleton +.idea + +# Composer files +composer.phar +vendor/ + +# Default cache folder +data/cache/ diff --git a/samples/server/petstore/php-mezzio-ph-modern/.openapi-generator-ignore b/samples/server/petstore/php-mezzio-ph-modern/.openapi-generator-ignore new file mode 100644 index 00000000000..7484ee590a3 --- /dev/null +++ b/samples/server/petstore/php-mezzio-ph-modern/.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/php-mezzio-ph-modern/.openapi-generator/FILES b/samples/server/petstore/php-mezzio-ph-modern/.openapi-generator/FILES new file mode 100644 index 00000000000..bc9a68917b6 --- /dev/null +++ b/samples/server/petstore/php-mezzio-ph-modern/.openapi-generator/FILES @@ -0,0 +1,71 @@ +.gitignore +README.md +application/config.yml +application/config/app.yml +application/config/data_transfer.yml +application/config/path_handler.yml +application/container.php +composer.json +public/index.php +src/App/DTO/ApiResponse.php +src/App/DTO/Category.php +src/App/DTO/Collection.php +src/App/DTO/Collection1.php +src/App/DTO/Collection10.php +src/App/DTO/Collection11.php +src/App/DTO/Collection12.php +src/App/DTO/Collection13.php +src/App/DTO/Collection14.php +src/App/DTO/Collection15.php +src/App/DTO/Collection16.php +src/App/DTO/Collection17.php +src/App/DTO/Collection18.php +src/App/DTO/Collection19.php +src/App/DTO/Collection2.php +src/App/DTO/Collection20.php +src/App/DTO/Collection21.php +src/App/DTO/Collection22.php +src/App/DTO/Collection23.php +src/App/DTO/Collection24.php +src/App/DTO/Collection25.php +src/App/DTO/Collection26.php +src/App/DTO/Collection27.php +src/App/DTO/Collection28.php +src/App/DTO/Collection29.php +src/App/DTO/Collection3.php +src/App/DTO/Collection30.php +src/App/DTO/Collection31.php +src/App/DTO/Collection32.php +src/App/DTO/Collection33.php +src/App/DTO/Collection34.php +src/App/DTO/Collection35.php +src/App/DTO/Collection36.php +src/App/DTO/Collection4.php +src/App/DTO/Collection5.php +src/App/DTO/Collection6.php +src/App/DTO/Collection7.php +src/App/DTO/Collection8.php +src/App/DTO/Collection9.php +src/App/DTO/FindPetsByStatusQueryData.php +src/App/DTO/FindPetsByTagsQueryData.php +src/App/DTO/LoginUserQueryData.php +src/App/DTO/Order.php +src/App/DTO/Pet.php +src/App/DTO/Tag.php +src/App/DTO/User.php +src/App/Factory.php +src/App/Handler/Pet.php +src/App/Handler/PetFindByStatus.php +src/App/Handler/PetFindByTags.php +src/App/Handler/PetPetId.php +src/App/Handler/PetPetIdUploadImage.php +src/App/Handler/StoreInventory.php +src/App/Handler/StoreOrder.php +src/App/Handler/StoreOrderOrderId.php +src/App/Handler/User.php +src/App/Handler/UserCreateWithArray.php +src/App/Handler/UserCreateWithList.php +src/App/Handler/UserLogin.php +src/App/Handler/UserLogout.php +src/App/Handler/UserUsername.php +src/App/Middleware/InternalServerError.php diff --git a/samples/server/petstore/php-mezzio-ph-modern/.openapi-generator/VERSION b/samples/server/petstore/php-mezzio-ph-modern/.openapi-generator/VERSION new file mode 100644 index 00000000000..4b448de535c --- /dev/null +++ b/samples/server/petstore/php-mezzio-ph-modern/.openapi-generator/VERSION @@ -0,0 +1 @@ +5.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/openapi3/server/petstore/php-mezzio-ph/README.md b/samples/server/petstore/php-mezzio-ph-modern/README.md similarity index 93% rename from samples/openapi3/server/petstore/php-mezzio-ph/README.md rename to samples/server/petstore/php-mezzio-ph-modern/README.md index 584fd156879..fd66369b261 100644 --- a/samples/openapi3/server/petstore/php-mezzio-ph/README.md +++ b/samples/server/petstore/php-mezzio-ph-modern/README.md @@ -5,9 +5,9 @@ Generated by the [OpenAPI Generator](https://openapi-generator.tech) project. ## Overview This server stub aims to provide light, yet comprehensive structure for your API project using: -- PHP: >=7.2 -- [Laminas Mezzio](https://docs.mezzio.dev/mezzio/): >=3.2 -- [Path Handler](https://github.com/Articus/PathHandler): >=0.6 +- PHP: >=8.0 +- [Laminas Mezzio](https://docs.mezzio.dev/mezzio/): >=3.3 +- [Path Handler](https://github.com/Articus/PathHandler): >=0.7 ## How to use All you have to do to start development is: diff --git a/samples/server/petstore/php-mezzio-ph-modern/application/config.yml b/samples/server/petstore/php-mezzio-ph-modern/application/config.yml new file mode 100644 index 00000000000..58056552c5b --- /dev/null +++ b/samples/server/petstore/php-mezzio-ph-modern/application/config.yml @@ -0,0 +1,21 @@ +#Empty configuration placeholder, remove when you add any real configuration settings to this file +{} + +#Enable configuration cache +#cache_configuration: true + +#Articus\PathHandler\RouteInjection\Factory: +# #Enable routing table cache +# router: +# cache: +# directory: ./data/cache/PathHandler + +#Enable handler metadata cache +#Articus\PathHandler\MetadataProvider\PhpAttribute: +# cache: +# directory: ./data/cache/PathHandler + +#Enable data transfer metadata cache for DTOs +#Articus\DataTransfer\MetadataProvider\PhpAttribute: +# cache: +# directory: ./data/cache/DataTransfer diff --git a/samples/server/petstore/php-mezzio-ph-modern/application/config/app.yml b/samples/server/petstore/php-mezzio-ph-modern/application/config/app.yml new file mode 100644 index 00000000000..0ffd5e8864c --- /dev/null +++ b/samples/server/petstore/php-mezzio-ph-modern/application/config/app.yml @@ -0,0 +1,22 @@ +dependencies: + invokables: + Laminas\HttpHandlerRunner\Emitter\EmitterInterface: Laminas\HttpHandlerRunner\Emitter\SapiStreamEmitter + factories: + Mezzio\Application: App\Factory + Mezzio\MiddlewareContainer: Mezzio\Container\MiddlewareContainerFactory + Mezzio\MiddlewareFactory: Mezzio\Container\MiddlewareFactoryFactory + Mezzio\Router\RouteCollector: Mezzio\Router\RouteCollectorFactory + + Psr\Http\Message\ServerRequestInterface: Mezzio\Container\ServerRequestFactoryFactory + Psr\Http\Message\StreamInterface: Mezzio\Container\StreamFactoryFactory + Psr\Http\Message\ResponseInterface: Mezzio\Container\ResponseFactoryFactory + + App\Middleware\InternalServerError: Laminas\ServiceManager\AbstractFactory\ConfigAbstractFactory + Mezzio\Router\Middleware\RouteMiddleware: Mezzio\Router\Middleware\RouteMiddlewareFactory + Mezzio\Router\Middleware\DispatchMiddleware: Mezzio\Router\Middleware\DispatchMiddlewareFactory + Mezzio\Router\Middleware\MethodNotAllowedMiddleware: Mezzio\Router\Middleware\MethodNotAllowedMiddlewareFactory + Mezzio\Handler\NotFoundHandler: Mezzio\Container\NotFoundHandlerFactory + +Laminas\ServiceManager\AbstractFactory\ConfigAbstractFactory: + App\Middleware\InternalServerError: + - Psr\Http\Message\ResponseInterface diff --git a/samples/openapi3/server/petstore/php-mezzio-ph/application/config/data_transfer.yml b/samples/server/petstore/php-mezzio-ph-modern/application/config/data_transfer.yml similarity index 69% rename from samples/openapi3/server/petstore/php-mezzio-ph/application/config/data_transfer.yml rename to samples/server/petstore/php-mezzio-ph-modern/application/config/data_transfer.yml index c5174147c23..7bdd139bb9f 100644 --- a/samples/openapi3/server/petstore/php-mezzio-ph/application/config/data_transfer.yml +++ b/samples/server/petstore/php-mezzio-ph-modern/application/config/data_transfer.yml @@ -1,13 +1,13 @@ dependencies: factories: Articus\DataTransfer\Service: Articus\DataTransfer\Factory - Articus\DataTransfer\MetadataProvider\Annotation: Articus\DataTransfer\MetadataProvider\Factory\Annotation + Articus\DataTransfer\MetadataProvider\PhpAttribute: Articus\DataTransfer\MetadataProvider\Factory\PhpAttribute Articus\DataTransfer\Strategy\PluginManager: Articus\DataTransfer\Strategy\Factory\PluginManager Articus\DataTransfer\Validator\PluginManager: Articus\DataTransfer\Validator\Factory\PluginManager Laminas\Validator\ValidatorPluginManager: Laminas\Validator\ValidatorPluginManagerFactory aliases: - Articus\DataTransfer\ClassMetadataProviderInterface: Articus\DataTransfer\MetadataProvider\Annotation - Articus\DataTransfer\FieldMetadataProviderInterface: Articus\DataTransfer\MetadataProvider\Annotation + Articus\DataTransfer\ClassMetadataProviderInterface: Articus\DataTransfer\MetadataProvider\PhpAttribute + Articus\DataTransfer\FieldMetadataProviderInterface: Articus\DataTransfer\MetadataProvider\PhpAttribute Articus\DataTransfer\Strategy\PluginManager: invokables: @@ -16,6 +16,10 @@ Articus\DataTransfer\Strategy\PluginManager: factories: Date: OpenAPIGenerator\Common\Strategy\Factory\MutableDate DateTime: OpenAPIGenerator\Common\Strategy\Factory\MutableDateTime + ObjectList: OpenAPIGenerator\Common\Strategy\Factory\NoArgObjectList + ObjectMap: OpenAPIGenerator\Common\Strategy\Factory\NoArgObjectMap + ScalarList: OpenAPIGenerator\Common\Strategy\Factory\ScalarList + ScalarMap: OpenAPIGenerator\Common\Strategy\Factory\ScalarMap Articus\DataTransfer\Validator\PluginManager: invokables: @@ -24,3 +28,7 @@ Articus\DataTransfer\Validator\PluginManager: QueryStringScalarArray: OpenAPIGenerator\Common\Validator\QueryStringScalarArray abstract_factories: - Articus\DataTransfer\Validator\Factory\Laminas + +validators: + invokables: + Count: Laminas\Validator\IsCountable diff --git a/samples/openapi3/server/petstore/php-mezzio-ph/application/config/path_handler.yml b/samples/server/petstore/php-mezzio-ph-modern/application/config/path_handler.yml similarity index 53% rename from samples/openapi3/server/petstore/php-mezzio-ph/application/config/path_handler.yml rename to samples/server/petstore/php-mezzio-ph-modern/application/config/path_handler.yml index 25995b20d6f..eb46b1891a3 100644 --- a/samples/openapi3/server/petstore/php-mezzio-ph/application/config/path_handler.yml +++ b/samples/server/petstore/php-mezzio-ph-modern/application/config/path_handler.yml @@ -1,8 +1,13 @@ dependencies: factories: - Mezzio\Router\RouterInterface: Articus\PathHandler\RouteInjection\Factory + Mezzio\Router\RouterInterface: Articus\PathHandler\RouteInjectionFactory + Articus\PathHandler\MetadataProviderInterface: Articus\PathHandler\MetadataProvider\Factory\PhpAttribute + Articus\PathHandler\Handler\PluginManager: Articus\PathHandler\Handler\Factory\PluginManager + Articus\PathHandler\Consumer\PluginManager: Articus\PathHandler\Consumer\Factory\PluginManager + Articus\PathHandler\Attribute\PluginManager: Articus\PathHandler\Attribute\Factory\PluginManager + Articus\PathHandler\Producer\PluginManager: Articus\PathHandler\Producer\Factory\PluginManager -Articus\PathHandler\RouteInjection\Factory: +Articus\PathHandler\RouteInjectionFactory: paths: '/v2': - App\Handler\Pet @@ -19,18 +24,22 @@ Articus\PathHandler\RouteInjection\Factory: - App\Handler\UserLogin - App\Handler\UserLogout - App\Handler\UserUsername - handlers: - abstract_factories: - - Laminas\ServiceManager\AbstractFactory\ConfigAbstractFactory -# consumers: -# factories: -# invokables: -# attributes: -# factories: -# invokables: -# producers: -# factories: -# invokables: + +Articus\PathHandler\Handler\PluginManager: + abstract_factories: + - Laminas\ServiceManager\AbstractFactory\ConfigAbstractFactory + +#Articus\PathHandler\Consumer\PluginManager: +# factories: +# invokables: + +#Articus\PathHandler\Attribute\PluginManager: +# factories: +# invokables: + +#Articus\PathHandler\Producer\PluginManager: +# factories: +# invokables: Laminas\ServiceManager\AbstractFactory\ConfigAbstractFactory: App\Handler\Pet: [] diff --git a/samples/server/petstore/php-mezzio-ph-modern/application/container.php b/samples/server/petstore/php-mezzio-ph-modern/application/container.php new file mode 100644 index 00000000000..9c54fafcfec --- /dev/null +++ b/samples/server/petstore/php-mezzio-ph-modern/application/container.php @@ -0,0 +1,43 @@ +setService('config', $config); +$container->setAlias('Config', 'config'); + +return $container; diff --git a/samples/server/petstore/php-mezzio-ph-modern/composer.json b/samples/server/petstore/php-mezzio-ph-modern/composer.json new file mode 100644 index 00000000000..7f03f079e4a --- /dev/null +++ b/samples/server/petstore/php-mezzio-ph-modern/composer.json @@ -0,0 +1,26 @@ +{ + "name": "git_user_id/git_repo_id", + "description": "", + "license": "unlicense", + "version": "1.0.0", + "type": "project", + "require": { + "php": "^8.0", + "ext-yaml": "^2.2", + "mezzio/mezzio": "^3.3", + "laminas/laminas-diactoros": "^2.5", + "articus/path-handler": "^0.7", + "articus/data-transfer": "^0.5", + "articus/openapi-generator-common": "^0.2", + "psr/simple-cache": "^1.0", + "laminas/laminas-config": "^3.4", + "laminas/laminas-stdlib": "^3.3", + "laminas/laminas-validator": "^2.14", + "nikic/fast-route": "^1.3" + }, + "autoload": { + "psr-4": { + "": "src/" + } + } +} \ No newline at end of file diff --git a/samples/server/petstore/php-mezzio-ph-modern/public/index.php b/samples/server/petstore/php-mezzio-ph-modern/public/index.php new file mode 100644 index 00000000000..7c3de73df16 --- /dev/null +++ b/samples/server/petstore/php-mezzio-ph-modern/public/index.php @@ -0,0 +1,11 @@ +get(\Mezzio\Application::class); +$app->run(); diff --git a/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/ApiResponse.php b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/ApiResponse.php new file mode 100644 index 00000000000..bfe65906ea5 --- /dev/null +++ b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/ApiResponse.php @@ -0,0 +1,25 @@ + "int"])] + public int|null $code = null; + + #[DTA\Data(field: "type", nullable: true)] + #[DTA\Validator("Scalar", ["type" => "string"])] + public string|null $type = null; + + #[DTA\Data(field: "message", nullable: true)] + #[DTA\Validator("Scalar", ["type" => "string"])] + public string|null $message = null; + +} diff --git a/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Category.php b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Category.php new file mode 100644 index 00000000000..e6b28c29028 --- /dev/null +++ b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Category.php @@ -0,0 +1,22 @@ + "int"])] + public int|null $id = null; + + #[DTA\Data(field: "name", nullable: true)] + #[DTA\Validator("Scalar", ["type" => "string"])] + #[DTA\Validator("Regex", ["pattern" => "/^[a-zA-Z0-9]+[a-zA-Z0-9\\.\\-_]*[a-zA-Z0-9]+$/"])] + public string|null $name = null; + +} diff --git a/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection.php b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection.php new file mode 100644 index 00000000000..f0e14da6cd8 --- /dev/null +++ b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection.php @@ -0,0 +1,14 @@ + "string"])] +#[DTA\Validator("Collection", ["validators" => [ + ["name" => "Scalar", "options" => ["type" => "string"]] +]])] +class Collection extends \ArrayObject +{ +} diff --git a/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection1.php b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection1.php new file mode 100644 index 00000000000..c05da2858bd --- /dev/null +++ b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection1.php @@ -0,0 +1,14 @@ + \App\DTO\Tag::class])] +#[DTA\Validator("Collection", ["validators" => [ + ["name" => "TypeCompliant", "options" => ["type" => \App\DTO\Tag::class]] +]])] +class Collection1 extends \ArrayObject +{ +} diff --git a/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection10.php b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection10.php new file mode 100644 index 00000000000..29e6ccdb347 --- /dev/null +++ b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection10.php @@ -0,0 +1,14 @@ + "string"])] +#[DTA\Validator("Collection", ["validators" => [ + ["name" => "Scalar", "options" => ["type" => "string"]] +]])] +class Collection10 extends \ArrayObject +{ +} diff --git a/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection11.php b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection11.php new file mode 100644 index 00000000000..89b2d0d01f8 --- /dev/null +++ b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection11.php @@ -0,0 +1,14 @@ + \App\DTO\Tag::class])] +#[DTA\Validator("Collection", ["validators" => [ + ["name" => "TypeCompliant", "options" => ["type" => \App\DTO\Tag::class]] +]])] +class Collection11 extends \ArrayObject +{ +} diff --git a/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection12.php b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection12.php new file mode 100644 index 00000000000..e0657b0d467 --- /dev/null +++ b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection12.php @@ -0,0 +1,14 @@ + "string"])] +#[DTA\Validator("Collection", ["validators" => [ + ["name" => "Scalar", "options" => ["type" => "string"]] +]])] +class Collection12 extends \ArrayObject +{ +} diff --git a/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection13.php b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection13.php new file mode 100644 index 00000000000..26f88d9685d --- /dev/null +++ b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection13.php @@ -0,0 +1,14 @@ + \App\DTO\Tag::class])] +#[DTA\Validator("Collection", ["validators" => [ + ["name" => "TypeCompliant", "options" => ["type" => \App\DTO\Tag::class]] +]])] +class Collection13 extends \ArrayObject +{ +} diff --git a/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection14.php b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection14.php new file mode 100644 index 00000000000..d1e0e11495b --- /dev/null +++ b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection14.php @@ -0,0 +1,14 @@ + "string"])] +#[DTA\Validator("Collection", ["validators" => [ + ["name" => "Scalar", "options" => ["type" => "string"]] +]])] +class Collection14 extends \ArrayObject +{ +} diff --git a/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection15.php b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection15.php new file mode 100644 index 00000000000..085f17e1e97 --- /dev/null +++ b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection15.php @@ -0,0 +1,14 @@ + \App\DTO\Tag::class])] +#[DTA\Validator("Collection", ["validators" => [ + ["name" => "TypeCompliant", "options" => ["type" => \App\DTO\Tag::class]] +]])] +class Collection15 extends \ArrayObject +{ +} diff --git a/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection16.php b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection16.php new file mode 100644 index 00000000000..1b1523c7d09 --- /dev/null +++ b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection16.php @@ -0,0 +1,14 @@ + "string"])] +#[DTA\Validator("Collection", ["validators" => [ + ["name" => "Scalar", "options" => ["type" => "string"]] +]])] +class Collection16 extends \ArrayObject +{ +} diff --git a/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection17.php b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection17.php new file mode 100644 index 00000000000..eb5b0e828f8 --- /dev/null +++ b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection17.php @@ -0,0 +1,14 @@ + "string"])] +#[DTA\Validator("Collection", ["validators" => [ + ["name" => "Scalar", "options" => ["type" => "string"]] +]])] +class Collection17 extends \ArrayObject +{ +} diff --git a/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection18.php b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection18.php new file mode 100644 index 00000000000..dd55bd5840a --- /dev/null +++ b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection18.php @@ -0,0 +1,14 @@ + \App\DTO\Tag::class])] +#[DTA\Validator("Collection", ["validators" => [ + ["name" => "TypeCompliant", "options" => ["type" => \App\DTO\Tag::class]] +]])] +class Collection18 extends \ArrayObject +{ +} diff --git a/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection19.php b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection19.php new file mode 100644 index 00000000000..45da36c7301 --- /dev/null +++ b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection19.php @@ -0,0 +1,14 @@ + \App\DTO\Pet::class])] +#[DTA\Validator("Collection", ["validators" => [ + ["name" => "TypeCompliant", "options" => ["type" => \App\DTO\Pet::class]] +]])] +class Collection19 extends \ArrayObject +{ +} diff --git a/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection2.php b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection2.php new file mode 100644 index 00000000000..26176dcc5e5 --- /dev/null +++ b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection2.php @@ -0,0 +1,14 @@ + "string"])] +#[DTA\Validator("Collection", ["validators" => [ + ["name" => "Scalar", "options" => ["type" => "string"]] +]])] +class Collection2 extends \ArrayObject +{ +} diff --git a/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection20.php b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection20.php new file mode 100644 index 00000000000..26b16ef104e --- /dev/null +++ b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection20.php @@ -0,0 +1,14 @@ + "string"])] +#[DTA\Validator("Collection", ["validators" => [ + ["name" => "Scalar", "options" => ["type" => "string"]] +]])] +class Collection20 extends \ArrayObject +{ +} diff --git a/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection21.php b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection21.php new file mode 100644 index 00000000000..9e0c2429bde --- /dev/null +++ b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection21.php @@ -0,0 +1,14 @@ + \App\DTO\Tag::class])] +#[DTA\Validator("Collection", ["validators" => [ + ["name" => "TypeCompliant", "options" => ["type" => \App\DTO\Tag::class]] +]])] +class Collection21 extends \ArrayObject +{ +} diff --git a/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection22.php b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection22.php new file mode 100644 index 00000000000..6f7a04ff4bd --- /dev/null +++ b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection22.php @@ -0,0 +1,14 @@ + \App\DTO\Pet::class])] +#[DTA\Validator("Collection", ["validators" => [ + ["name" => "TypeCompliant", "options" => ["type" => \App\DTO\Pet::class]] +]])] +class Collection22 extends \ArrayObject +{ +} diff --git a/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection23.php b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection23.php new file mode 100644 index 00000000000..608c9ad5020 --- /dev/null +++ b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection23.php @@ -0,0 +1,14 @@ + "string"])] +#[DTA\Validator("Collection", ["validators" => [ + ["name" => "Scalar", "options" => ["type" => "string"]] +]])] +class Collection23 extends \ArrayObject +{ +} diff --git a/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection24.php b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection24.php new file mode 100644 index 00000000000..b876816c2dd --- /dev/null +++ b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection24.php @@ -0,0 +1,14 @@ + "string"])] +#[DTA\Validator("Collection", ["validators" => [ + ["name" => "Scalar", "options" => ["type" => "string"]] +]])] +class Collection24 extends \ArrayObject +{ +} diff --git a/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection25.php b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection25.php new file mode 100644 index 00000000000..ad3a8102ad3 --- /dev/null +++ b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection25.php @@ -0,0 +1,14 @@ + \App\DTO\Tag::class])] +#[DTA\Validator("Collection", ["validators" => [ + ["name" => "TypeCompliant", "options" => ["type" => \App\DTO\Tag::class]] +]])] +class Collection25 extends \ArrayObject +{ +} diff --git a/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection26.php b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection26.php new file mode 100644 index 00000000000..f8e958fcb40 --- /dev/null +++ b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection26.php @@ -0,0 +1,14 @@ + \App\DTO\Pet::class])] +#[DTA\Validator("Collection", ["validators" => [ + ["name" => "TypeCompliant", "options" => ["type" => \App\DTO\Pet::class]] +]])] +class Collection26 extends \ArrayObject +{ +} diff --git a/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection27.php b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection27.php new file mode 100644 index 00000000000..b53e9e87a72 --- /dev/null +++ b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection27.php @@ -0,0 +1,14 @@ + "string"])] +#[DTA\Validator("Collection", ["validators" => [ + ["name" => "Scalar", "options" => ["type" => "string"]] +]])] +class Collection27 extends \ArrayObject +{ +} diff --git a/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection28.php b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection28.php new file mode 100644 index 00000000000..3b6e05419ef --- /dev/null +++ b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection28.php @@ -0,0 +1,14 @@ + \App\DTO\Tag::class])] +#[DTA\Validator("Collection", ["validators" => [ + ["name" => "TypeCompliant", "options" => ["type" => \App\DTO\Tag::class]] +]])] +class Collection28 extends \ArrayObject +{ +} diff --git a/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection29.php b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection29.php new file mode 100644 index 00000000000..24a1ee261d8 --- /dev/null +++ b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection29.php @@ -0,0 +1,14 @@ + \App\DTO\Pet::class])] +#[DTA\Validator("Collection", ["validators" => [ + ["name" => "TypeCompliant", "options" => ["type" => \App\DTO\Pet::class]] +]])] +class Collection29 extends \ArrayObject +{ +} diff --git a/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection3.php b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection3.php new file mode 100644 index 00000000000..1833307cd7e --- /dev/null +++ b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection3.php @@ -0,0 +1,14 @@ + \App\DTO\Tag::class])] +#[DTA\Validator("Collection", ["validators" => [ + ["name" => "TypeCompliant", "options" => ["type" => \App\DTO\Tag::class]] +]])] +class Collection3 extends \ArrayObject +{ +} diff --git a/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection30.php b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection30.php new file mode 100644 index 00000000000..916229afc92 --- /dev/null +++ b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection30.php @@ -0,0 +1,14 @@ + "string"])] +#[DTA\Validator("Collection", ["validators" => [ + ["name" => "Scalar", "options" => ["type" => "string"]] +]])] +class Collection30 extends \ArrayObject +{ +} diff --git a/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection31.php b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection31.php new file mode 100644 index 00000000000..12b771c1c16 --- /dev/null +++ b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection31.php @@ -0,0 +1,14 @@ + \App\DTO\Tag::class])] +#[DTA\Validator("Collection", ["validators" => [ + ["name" => "TypeCompliant", "options" => ["type" => \App\DTO\Tag::class]] +]])] +class Collection31 extends \ArrayObject +{ +} diff --git a/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection32.php b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection32.php new file mode 100644 index 00000000000..e89cbcd4397 --- /dev/null +++ b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection32.php @@ -0,0 +1,14 @@ + "string"])] +#[DTA\Validator("Collection", ["validators" => [ + ["name" => "Scalar", "options" => ["type" => "string"]] +]])] +class Collection32 extends \ArrayObject +{ +} diff --git a/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection33.php b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection33.php new file mode 100644 index 00000000000..91229b175cf --- /dev/null +++ b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection33.php @@ -0,0 +1,14 @@ + \App\DTO\Tag::class])] +#[DTA\Validator("Collection", ["validators" => [ + ["name" => "TypeCompliant", "options" => ["type" => \App\DTO\Tag::class]] +]])] +class Collection33 extends \ArrayObject +{ +} diff --git a/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection34.php b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection34.php new file mode 100644 index 00000000000..1670c4ee7e3 --- /dev/null +++ b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection34.php @@ -0,0 +1,14 @@ + "int"])] +#[DTA\Validator("Collection", ["validators" => [ + ["name" => "Scalar", "options" => ["type" => "int"]] +]])] +class Collection34 extends \ArrayObject +{ +} diff --git a/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection35.php b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection35.php new file mode 100644 index 00000000000..4b1082abc1b --- /dev/null +++ b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection35.php @@ -0,0 +1,14 @@ + \App\DTO\User::class])] +#[DTA\Validator("Collection", ["validators" => [ + ["name" => "TypeCompliant", "options" => ["type" => \App\DTO\User::class]] +]])] +class Collection35 extends \ArrayObject +{ +} diff --git a/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection36.php b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection36.php new file mode 100644 index 00000000000..38595c2f5d3 --- /dev/null +++ b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection36.php @@ -0,0 +1,14 @@ + \App\DTO\User::class])] +#[DTA\Validator("Collection", ["validators" => [ + ["name" => "TypeCompliant", "options" => ["type" => \App\DTO\User::class]] +]])] +class Collection36 extends \ArrayObject +{ +} diff --git a/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection4.php b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection4.php new file mode 100644 index 00000000000..54e2f1a12de --- /dev/null +++ b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection4.php @@ -0,0 +1,14 @@ + "string"])] +#[DTA\Validator("Collection", ["validators" => [ + ["name" => "Scalar", "options" => ["type" => "string"]] +]])] +class Collection4 extends \ArrayObject +{ +} diff --git a/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection5.php b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection5.php new file mode 100644 index 00000000000..3f32f4513a7 --- /dev/null +++ b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection5.php @@ -0,0 +1,14 @@ + \App\DTO\Tag::class])] +#[DTA\Validator("Collection", ["validators" => [ + ["name" => "TypeCompliant", "options" => ["type" => \App\DTO\Tag::class]] +]])] +class Collection5 extends \ArrayObject +{ +} diff --git a/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection6.php b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection6.php new file mode 100644 index 00000000000..79abc43f339 --- /dev/null +++ b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection6.php @@ -0,0 +1,14 @@ + "string"])] +#[DTA\Validator("Collection", ["validators" => [ + ["name" => "Scalar", "options" => ["type" => "string"]] +]])] +class Collection6 extends \ArrayObject +{ +} diff --git a/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection7.php b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection7.php new file mode 100644 index 00000000000..8574d82b365 --- /dev/null +++ b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection7.php @@ -0,0 +1,14 @@ + \App\DTO\Tag::class])] +#[DTA\Validator("Collection", ["validators" => [ + ["name" => "TypeCompliant", "options" => ["type" => \App\DTO\Tag::class]] +]])] +class Collection7 extends \ArrayObject +{ +} diff --git a/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection8.php b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection8.php new file mode 100644 index 00000000000..c264d8076a1 --- /dev/null +++ b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection8.php @@ -0,0 +1,14 @@ + "string"])] +#[DTA\Validator("Collection", ["validators" => [ + ["name" => "Scalar", "options" => ["type" => "string"]] +]])] +class Collection8 extends \ArrayObject +{ +} diff --git a/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection9.php b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection9.php new file mode 100644 index 00000000000..99cc837d6a5 --- /dev/null +++ b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection9.php @@ -0,0 +1,14 @@ + \App\DTO\Tag::class])] +#[DTA\Validator("Collection", ["validators" => [ + ["name" => "TypeCompliant", "options" => ["type" => \App\DTO\Tag::class]] +]])] +class Collection9 extends \ArrayObject +{ +} diff --git a/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/FindPetsByStatusQueryData.php b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/FindPetsByStatusQueryData.php new file mode 100644 index 00000000000..178b4949794 --- /dev/null +++ b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/FindPetsByStatusQueryData.php @@ -0,0 +1,21 @@ + "string", "format" => "csv"])] + #[DTA\Validator("QueryStringScalarArray", ["type" => "string", "format" => "csv"])] + public array|null $status = null; + +} diff --git a/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/FindPetsByTagsQueryData.php b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/FindPetsByTagsQueryData.php new file mode 100644 index 00000000000..cbf9e1d0c39 --- /dev/null +++ b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/FindPetsByTagsQueryData.php @@ -0,0 +1,21 @@ + "string", "format" => "csv"])] + #[DTA\Validator("QueryStringScalarArray", ["type" => "string", "format" => "csv"])] + public array|null $tags = null; + +} diff --git a/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/LoginUserQueryData.php b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/LoginUserQueryData.php new file mode 100644 index 00000000000..2c01e944c91 --- /dev/null +++ b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/LoginUserQueryData.php @@ -0,0 +1,30 @@ + "string"])] + #[DTA\Validator("QueryStringScalar", ["type" => "string"])] + public string|null $password = null; + + /** + * The user name for login + */ + #[DTA\Data(field: "username")] + #[DTA\Strategy("QueryStringScalar", ["type" => "string"])] + #[DTA\Validator("QueryStringScalar", ["type" => "string"])] + #[DTA\Validator("Regex", ["pattern" => "/^[a-zA-Z0-9]+[a-zA-Z0-9\\.\\-_]*[a-zA-Z0-9]+$/"])] + public string|null $username = null; + +} diff --git a/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Order.php b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Order.php new file mode 100644 index 00000000000..8dd384b4475 --- /dev/null +++ b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Order.php @@ -0,0 +1,41 @@ + "int"])] + public int|null $id = null; + + #[DTA\Data(field: "petId", nullable: true)] + #[DTA\Validator("Scalar", ["type" => "int"])] + public int|null $pet_id = null; + + #[DTA\Data(field: "quantity", nullable: true)] + #[DTA\Validator("Scalar", ["type" => "int"])] + public int|null $quantity = null; + + #[DTA\Data(field: "shipDate", nullable: true)] + #[DTA\Strategy("DateTime")] + #[DTA\Validator("Date", ["format" => \DateTime::RFC3339])] + public \DateTime|null $ship_date = null; + + /** + * Order Status + */ + #[DTA\Data(field: "status", nullable: true)] + #[DTA\Validator("Scalar", ["type" => "string"])] + public string|null $status = null; + + #[DTA\Data(field: "complete", nullable: true)] + #[DTA\Validator("Scalar", ["type" => "bool"])] + public bool|null $complete = null; + +} diff --git a/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Pet.php b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Pet.php new file mode 100644 index 00000000000..bcd5cdb6e81 --- /dev/null +++ b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Pet.php @@ -0,0 +1,43 @@ + "int"])] + public int|null $id = null; + + #[DTA\Data(field: "category", nullable: true)] + #[DTA\Strategy("Object", ["type" => \App\DTO\Category::class])] + #[DTA\Validator("TypeCompliant", ["type" => \App\DTO\Category::class])] + public \App\DTO\Category|null $category = null; + + #[DTA\Data(field: "name")] + #[DTA\Validator("Scalar", ["type" => "string"])] + public string|null $name = null; + + #[DTA\Data(field: "photoUrls")] + #[DTA\Strategy("Object", ["type" => \App\DTO\Collection32::class])] + #[DTA\Validator("TypeCompliant", ["type" => \App\DTO\Collection32::class])] + public \App\DTO\Collection32|null $photo_urls = null; + + #[DTA\Data(field: "tags", nullable: true)] + #[DTA\Strategy("Object", ["type" => \App\DTO\Collection33::class])] + #[DTA\Validator("TypeCompliant", ["type" => \App\DTO\Collection33::class])] + public \App\DTO\Collection33|null $tags = null; + + /** + * pet status in the store + */ + #[DTA\Data(field: "status", nullable: true)] + #[DTA\Validator("Scalar", ["type" => "string"])] + public string|null $status = null; + +} diff --git a/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Tag.php b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Tag.php new file mode 100644 index 00000000000..5fcc6c116b0 --- /dev/null +++ b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Tag.php @@ -0,0 +1,21 @@ + "int"])] + public int|null $id = null; + + #[DTA\Data(field: "name", nullable: true)] + #[DTA\Validator("Scalar", ["type" => "string"])] + public string|null $name = null; + +} diff --git a/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/User.php b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/User.php new file mode 100644 index 00000000000..c257dfea319 --- /dev/null +++ b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/User.php @@ -0,0 +1,48 @@ + "int"])] + public int|null $id = null; + + #[DTA\Data(field: "username", nullable: true)] + #[DTA\Validator("Scalar", ["type" => "string"])] + public string|null $username = null; + + #[DTA\Data(field: "firstName", nullable: true)] + #[DTA\Validator("Scalar", ["type" => "string"])] + public string|null $first_name = null; + + #[DTA\Data(field: "lastName", nullable: true)] + #[DTA\Validator("Scalar", ["type" => "string"])] + public string|null $last_name = null; + + #[DTA\Data(field: "email", nullable: true)] + #[DTA\Validator("Scalar", ["type" => "string"])] + public string|null $email = null; + + #[DTA\Data(field: "password", nullable: true)] + #[DTA\Validator("Scalar", ["type" => "string"])] + public string|null $password = null; + + #[DTA\Data(field: "phone", nullable: true)] + #[DTA\Validator("Scalar", ["type" => "string"])] + public string|null $phone = null; + + /** + * User Status + */ + #[DTA\Data(field: "userStatus", nullable: true)] + #[DTA\Validator("Scalar", ["type" => "int"])] + public int|null $user_status = null; + +} diff --git a/samples/openapi3/server/petstore/php-mezzio-ph/src/App/Factory.php b/samples/server/petstore/php-mezzio-ph-modern/src/App/Factory.php similarity index 71% rename from samples/openapi3/server/petstore/php-mezzio-ph/src/App/Factory.php rename to samples/server/petstore/php-mezzio-ph-modern/src/App/Factory.php index 0757bcfbea7..24eb21b492c 100644 --- a/samples/openapi3/server/petstore/php-mezzio-ph/src/App/Factory.php +++ b/samples/server/petstore/php-mezzio-ph-modern/src/App/Factory.php @@ -23,23 +23,13 @@ class Factory implements FactoryInterface { public function __invoke(ContainerInterface $container, $requestedName, array $options = null): Application { - $errorMiddleware = $container->get(Middleware\InternalServerError::class); - if (!($errorMiddleware instanceof Middleware\InternalServerError)) { - throw new \LogicException(\sprintf( - 'Invalid error middleware: expecting %s, not %s.', - Middleware\InternalServerError::class, - \is_object($errorMiddleware) ? \get_class($errorMiddleware) : \gettype($errorMiddleware) - )); - } + $errorMiddleware = self::getErrorMiddleware($container); $pipeline = new MiddlewarePipe(); $runner = new RequestHandlerRunner( $pipeline, $container->get(EmitterInterface::class), $container->get(ServerRequestInterface::class), - function(\Throwable $error) use ($errorMiddleware) : ResponseInterface - { - return $errorMiddleware->handleError($error); - } + static fn(\Throwable $error): ResponseInterface => $errorMiddleware->handleError($error) ); $application = new Application( $container->get(MiddlewareFactory::class), @@ -55,4 +45,9 @@ class Factory implements FactoryInterface return $application; } + + protected static function getErrorMiddleware(ContainerInterface $container): Middleware\InternalServerError + { + return $container->get(Middleware\InternalServerError::class); + } } diff --git a/samples/server/petstore/php-mezzio-ph-modern/src/App/Handler/Pet.php b/samples/server/petstore/php-mezzio-ph-modern/src/App/Handler/Pet.php new file mode 100644 index 00000000000..625b36f693a --- /dev/null +++ b/samples/server/petstore/php-mezzio-ph-modern/src/App/Handler/Pet.php @@ -0,0 +1,56 @@ + \App\DTO\Pet::class, "objectAttr" => "bodyData"])] + // TODO check if producer is valid, if it has correct priority and if it can be moved to class annotation + #[PHA\Producer("application/xml", PHProducer\Transfer::class)] + // TODO check if producer is valid, if it has correct priority and if it can be moved to class annotation + #[PHA\Producer("application/json", PHProducer\Transfer::class)] + public function addPet(ServerRequestInterface $request): \App\DTO\Pet + { + //TODO implement method + /** @var \App\DTO\Pet $bodyData */ + $bodyData = $request->getAttribute("bodyData"); + throw new PHException\HttpCode(501, "Not implemented"); + } + /** + * Update an existing pet + */ + #[PHA\Put()] + // TODO check if consumer is valid, if it has correct priority and if it can be moved to class annotation + #[PHA\Consumer("application/json", PHConsumer\Json::class)] + // TODO check if consumer is valid, if it has correct priority and if it can be moved to class annotation + #[PHA\Consumer("application/xml", PHConsumer\Json::class)] + #[PHA\Attribute(PHAttribute\Transfer::class, ["type" => \App\DTO\Pet::class, "objectAttr" => "bodyData"])] + // TODO check if producer is valid, if it has correct priority and if it can be moved to class annotation + #[PHA\Producer("application/xml", PHProducer\Transfer::class)] + // TODO check if producer is valid, if it has correct priority and if it can be moved to class annotation + #[PHA\Producer("application/json", PHProducer\Transfer::class)] + public function updatePet(ServerRequestInterface $request): \App\DTO\Pet + { + //TODO implement method + /** @var \App\DTO\Pet $bodyData */ + $bodyData = $request->getAttribute("bodyData"); + throw new PHException\HttpCode(501, "Not implemented"); + } +} diff --git a/samples/server/petstore/php-mezzio-ph-modern/src/App/Handler/PetFindByStatus.php b/samples/server/petstore/php-mezzio-ph-modern/src/App/Handler/PetFindByStatus.php new file mode 100644 index 00000000000..53d217f9969 --- /dev/null +++ b/samples/server/petstore/php-mezzio-ph-modern/src/App/Handler/PetFindByStatus.php @@ -0,0 +1,36 @@ + \App\DTO\FindPetsByStatusQueryData::class, + "objectAttr" => "queryData", + "source" => PHAttribute\Transfer::SOURCE_GET + ])] + // TODO check if producer is valid, if it has correct priority and if it can be moved to class annotation + #[PHA\Producer("application/xml", PHProducer\Transfer::class)] + // TODO check if producer is valid, if it has correct priority and if it can be moved to class annotation + #[PHA\Producer("application/json", PHProducer\Transfer::class)] + public function findPetsByStatus(ServerRequestInterface $request): \App\DTO\Collection19 + { + //TODO implement method + /** @var \App\DTO\FindPetsByStatusQueryData $queryData */ + $queryData = $request->getAttribute("queryData"); + throw new PHException\HttpCode(501, "Not implemented"); + } +} diff --git a/samples/server/petstore/php-mezzio-ph-modern/src/App/Handler/PetFindByTags.php b/samples/server/petstore/php-mezzio-ph-modern/src/App/Handler/PetFindByTags.php new file mode 100644 index 00000000000..a40122909bc --- /dev/null +++ b/samples/server/petstore/php-mezzio-ph-modern/src/App/Handler/PetFindByTags.php @@ -0,0 +1,36 @@ + \App\DTO\FindPetsByTagsQueryData::class, + "objectAttr" => "queryData", + "source" => PHAttribute\Transfer::SOURCE_GET + ])] + // TODO check if producer is valid, if it has correct priority and if it can be moved to class annotation + #[PHA\Producer("application/xml", PHProducer\Transfer::class)] + // TODO check if producer is valid, if it has correct priority and if it can be moved to class annotation + #[PHA\Producer("application/json", PHProducer\Transfer::class)] + public function findPetsByTags(ServerRequestInterface $request): \App\DTO\Collection26 + { + //TODO implement method + /** @var \App\DTO\FindPetsByTagsQueryData $queryData */ + $queryData = $request->getAttribute("queryData"); + throw new PHException\HttpCode(501, "Not implemented"); + } +} diff --git a/samples/openapi3/server/petstore/php-mezzio-ph/src/App/Handler/PetPetId.php b/samples/server/petstore/php-mezzio-ph-modern/src/App/Handler/PetPetId.php similarity index 55% rename from samples/openapi3/server/petstore/php-mezzio-ph/src/App/Handler/PetPetId.php rename to samples/server/petstore/php-mezzio-ph-modern/src/App/Handler/PetPetId.php index 625bbf5832c..8da421be678 100644 --- a/samples/openapi3/server/petstore/php-mezzio-ph/src/App/Handler/PetPetId.php +++ b/samples/server/petstore/php-mezzio-ph-modern/src/App/Handler/PetPetId.php @@ -3,25 +3,20 @@ declare(strict_types=1); namespace App\Handler; -use Articus\PathHandler\Annotation as PHA; +use Articus\PathHandler\PhpAttribute as PHA; use Articus\PathHandler\Consumer as PHConsumer; use Articus\PathHandler\Producer as PHProducer; use Articus\PathHandler\Attribute as PHAttribute; use Articus\PathHandler\Exception as PHException; use Psr\Http\Message\ServerRequestInterface; -/** - * @PHA\Route(pattern="/pet/{petId}") - */ +#[PHA\Route("/pet/{petId}")] class PetPetId { /** * Deletes a pet - * @PHA\Delete() - * @param ServerRequestInterface $request - * - * @throws PHException\HttpCode 501 if the method is not implemented */ + #[PHA\Delete()] public function deletePet(ServerRequestInterface $request) { //TODO implement method @@ -29,17 +24,12 @@ class PetPetId } /** * Find pet by ID - * @PHA\Get() - * TODO check if producer is valid, if it has correct priority and if it can be moved to class annotation - * @PHA\Producer(name=PHProducer\Transfer::class, mediaType="application/xml") - * TODO check if producer is valid, if it has correct priority and if it can be moved to class annotation - * @PHA\Producer(name=PHProducer\Transfer::class, mediaType="application/json") - * @param ServerRequestInterface $request - * - * @throws PHException\HttpCode 501 if the method is not implemented - * - * @return \App\DTO\Pet */ + #[PHA\Get()] + // TODO check if producer is valid, if it has correct priority and if it can be moved to class annotation + #[PHA\Producer("application/xml", PHProducer\Transfer::class)] + // TODO check if producer is valid, if it has correct priority and if it can be moved to class annotation + #[PHA\Producer("application/json", PHProducer\Transfer::class)] public function getPetById(ServerRequestInterface $request): \App\DTO\Pet { //TODO implement method @@ -47,11 +37,8 @@ class PetPetId } /** * Updates a pet in the store with form data - * @PHA\Post() - * @param ServerRequestInterface $request - * - * @throws PHException\HttpCode 501 if the method is not implemented */ + #[PHA\Post()] public function updatePetWithForm(ServerRequestInterface $request) { //TODO implement method diff --git a/samples/openapi3/server/petstore/php-mezzio-ph/src/App/Handler/PetPetIdUploadImage.php b/samples/server/petstore/php-mezzio-ph-modern/src/App/Handler/PetPetIdUploadImage.php similarity index 58% rename from samples/openapi3/server/petstore/php-mezzio-ph/src/App/Handler/PetPetIdUploadImage.php rename to samples/server/petstore/php-mezzio-ph-modern/src/App/Handler/PetPetIdUploadImage.php index 67cc0784caa..886a35c1e32 100644 --- a/samples/openapi3/server/petstore/php-mezzio-ph/src/App/Handler/PetPetIdUploadImage.php +++ b/samples/server/petstore/php-mezzio-ph-modern/src/App/Handler/PetPetIdUploadImage.php @@ -3,29 +3,22 @@ declare(strict_types=1); namespace App\Handler; -use Articus\PathHandler\Annotation as PHA; +use Articus\PathHandler\PhpAttribute as PHA; use Articus\PathHandler\Consumer as PHConsumer; use Articus\PathHandler\Producer as PHProducer; use Articus\PathHandler\Attribute as PHAttribute; use Articus\PathHandler\Exception as PHException; use Psr\Http\Message\ServerRequestInterface; -/** - * @PHA\Route(pattern="/pet/{petId}/uploadImage") - */ +#[PHA\Route("/pet/{petId}/uploadImage")] class PetPetIdUploadImage { /** * uploads an image - * @PHA\Post() - * TODO check if producer is valid, if it has correct priority and if it can be moved to class annotation - * @PHA\Producer(name=PHProducer\Transfer::class, mediaType="application/json") - * @param ServerRequestInterface $request - * - * @throws PHException\HttpCode 501 if the method is not implemented - * - * @return \App\DTO\ApiResponse */ + #[PHA\Post()] + // TODO check if producer is valid, if it has correct priority and if it can be moved to class annotation + #[PHA\Producer("application/json", PHProducer\Transfer::class)] public function uploadFile(ServerRequestInterface $request): \App\DTO\ApiResponse { //TODO implement method diff --git a/samples/openapi3/server/petstore/php-mezzio-ph/src/App/Handler/StoreInventory.php b/samples/server/petstore/php-mezzio-ph-modern/src/App/Handler/StoreInventory.php similarity index 54% rename from samples/openapi3/server/petstore/php-mezzio-ph/src/App/Handler/StoreInventory.php rename to samples/server/petstore/php-mezzio-ph-modern/src/App/Handler/StoreInventory.php index 6d6d3ceb946..bc35720421c 100644 --- a/samples/openapi3/server/petstore/php-mezzio-ph/src/App/Handler/StoreInventory.php +++ b/samples/server/petstore/php-mezzio-ph-modern/src/App/Handler/StoreInventory.php @@ -3,31 +3,23 @@ declare(strict_types=1); namespace App\Handler; -use Articus\PathHandler\Annotation as PHA; +use Articus\PathHandler\PhpAttribute as PHA; use Articus\PathHandler\Consumer as PHConsumer; use Articus\PathHandler\Producer as PHProducer; use Articus\PathHandler\Attribute as PHAttribute; use Articus\PathHandler\Exception as PHException; use Psr\Http\Message\ServerRequestInterface; -/** - * @PHA\Route(pattern="/store/inventory") - */ +#[PHA\Route("/store/inventory")] class StoreInventory { /** * Returns pet inventories by status - * @PHA\Get() - * TODO check if producer is valid, if it has correct priority and if it can be moved to class annotation - * @PHA\Producer(name=PHProducer\Transfer::class, mediaType="application/json") - * @param ServerRequestInterface $request - * - * @throws PHException\HttpCode 501 if the method is not implemented - * - * TODO check if generated return container type is valid - * @return map[string,int] */ - public function getInventory(ServerRequestInterface $request): array + #[PHA\Get()] + // TODO check if producer is valid, if it has correct priority and if it can be moved to class annotation + #[PHA\Producer("application/json", PHProducer\Transfer::class)] + public function getInventory(ServerRequestInterface $request): \App\DTO\Collection34 { //TODO implement method throw new PHException\HttpCode(501, "Not implemented"); diff --git a/samples/server/petstore/php-mezzio-ph-modern/src/App/Handler/StoreOrder.php b/samples/server/petstore/php-mezzio-ph-modern/src/App/Handler/StoreOrder.php new file mode 100644 index 00000000000..9399d0e4d3b --- /dev/null +++ b/samples/server/petstore/php-mezzio-ph-modern/src/App/Handler/StoreOrder.php @@ -0,0 +1,34 @@ + \App\DTO\Order::class, "objectAttr" => "bodyData"])] + // TODO check if producer is valid, if it has correct priority and if it can be moved to class annotation + #[PHA\Producer("application/xml", PHProducer\Transfer::class)] + // TODO check if producer is valid, if it has correct priority and if it can be moved to class annotation + #[PHA\Producer("application/json", PHProducer\Transfer::class)] + public function placeOrder(ServerRequestInterface $request): \App\DTO\Order + { + //TODO implement method + /** @var \App\DTO\Order $bodyData */ + $bodyData = $request->getAttribute("bodyData"); + throw new PHException\HttpCode(501, "Not implemented"); + } +} diff --git a/samples/openapi3/server/petstore/php-mezzio-ph/src/App/Handler/StoreOrderOrderId.php b/samples/server/petstore/php-mezzio-ph-modern/src/App/Handler/StoreOrderOrderId.php similarity index 54% rename from samples/openapi3/server/petstore/php-mezzio-ph/src/App/Handler/StoreOrderOrderId.php rename to samples/server/petstore/php-mezzio-ph-modern/src/App/Handler/StoreOrderOrderId.php index 31c53e597eb..ae8313b20ea 100644 --- a/samples/openapi3/server/petstore/php-mezzio-ph/src/App/Handler/StoreOrderOrderId.php +++ b/samples/server/petstore/php-mezzio-ph-modern/src/App/Handler/StoreOrderOrderId.php @@ -3,25 +3,20 @@ declare(strict_types=1); namespace App\Handler; -use Articus\PathHandler\Annotation as PHA; +use Articus\PathHandler\PhpAttribute as PHA; use Articus\PathHandler\Consumer as PHConsumer; use Articus\PathHandler\Producer as PHProducer; use Articus\PathHandler\Attribute as PHAttribute; use Articus\PathHandler\Exception as PHException; use Psr\Http\Message\ServerRequestInterface; -/** - * @PHA\Route(pattern="/store/order/{orderId}") - */ +#[PHA\Route("/store/order/{orderId}")] class StoreOrderOrderId { /** * Delete purchase order by ID - * @PHA\Delete() - * @param ServerRequestInterface $request - * - * @throws PHException\HttpCode 501 if the method is not implemented */ + #[PHA\Delete()] public function deleteOrder(ServerRequestInterface $request) { //TODO implement method @@ -29,17 +24,12 @@ class StoreOrderOrderId } /** * Find purchase order by ID - * @PHA\Get() - * TODO check if producer is valid, if it has correct priority and if it can be moved to class annotation - * @PHA\Producer(name=PHProducer\Transfer::class, mediaType="application/xml") - * TODO check if producer is valid, if it has correct priority and if it can be moved to class annotation - * @PHA\Producer(name=PHProducer\Transfer::class, mediaType="application/json") - * @param ServerRequestInterface $request - * - * @throws PHException\HttpCode 501 if the method is not implemented - * - * @return \App\DTO\Order */ + #[PHA\Get()] + // TODO check if producer is valid, if it has correct priority and if it can be moved to class annotation + #[PHA\Producer("application/xml", PHProducer\Transfer::class)] + // TODO check if producer is valid, if it has correct priority and if it can be moved to class annotation + #[PHA\Producer("application/json", PHProducer\Transfer::class)] public function getOrderById(ServerRequestInterface $request): \App\DTO\Order { //TODO implement method diff --git a/samples/openapi3/server/petstore/php-mezzio-ph/src/App/Handler/User.php b/samples/server/petstore/php-mezzio-ph-modern/src/App/Handler/User.php similarity index 57% rename from samples/openapi3/server/petstore/php-mezzio-ph/src/App/Handler/User.php rename to samples/server/petstore/php-mezzio-ph-modern/src/App/Handler/User.php index 5a48f2ec072..8ad9221e263 100644 --- a/samples/openapi3/server/petstore/php-mezzio-ph/src/App/Handler/User.php +++ b/samples/server/petstore/php-mezzio-ph-modern/src/App/Handler/User.php @@ -3,28 +3,23 @@ declare(strict_types=1); namespace App\Handler; -use Articus\PathHandler\Annotation as PHA; +use Articus\PathHandler\PhpAttribute as PHA; use Articus\PathHandler\Consumer as PHConsumer; use Articus\PathHandler\Producer as PHProducer; use Articus\PathHandler\Attribute as PHAttribute; use Articus\PathHandler\Exception as PHException; use Psr\Http\Message\ServerRequestInterface; -/** - * @PHA\Route(pattern="/user") - */ +#[PHA\Route("/user")] class User { /** * Create user - * @PHA\Post() - * TODO check if consumer is valid, if it has correct priority and if it can be moved to class annotation - * @PHA\Consumer(name=PHConsumer\Json::class, mediaRange="application/json") - * @PHA\Attribute(name=PHAttribute\Transfer::class, options={"type":\App\DTO\User::class,"objectAttr":"bodyData"}) - * @param ServerRequestInterface $request - * - * @throws PHException\HttpCode 501 if the method is not implemented */ + #[PHA\Post()] + // TODO check if consumer is valid, if it has correct priority and if it can be moved to class annotation + #[PHA\Consumer("application/json", PHConsumer\Json::class)] + #[PHA\Attribute(PHAttribute\Transfer::class, ["type" => \App\DTO\User::class, "objectAttr" => "bodyData"])] public function createUser(ServerRequestInterface $request) { //TODO implement method diff --git a/samples/openapi3/server/petstore/php-mezzio-ph/src/App/Handler/UserCreateWithArray.php b/samples/server/petstore/php-mezzio-ph-modern/src/App/Handler/UserCreateWithArray.php similarity index 52% rename from samples/openapi3/server/petstore/php-mezzio-ph/src/App/Handler/UserCreateWithArray.php rename to samples/server/petstore/php-mezzio-ph-modern/src/App/Handler/UserCreateWithArray.php index a8a39215bab..304f85782c5 100644 --- a/samples/openapi3/server/petstore/php-mezzio-ph/src/App/Handler/UserCreateWithArray.php +++ b/samples/server/petstore/php-mezzio-ph-modern/src/App/Handler/UserCreateWithArray.php @@ -3,33 +3,27 @@ declare(strict_types=1); namespace App\Handler; -use Articus\PathHandler\Annotation as PHA; +use Articus\PathHandler\PhpAttribute as PHA; use Articus\PathHandler\Consumer as PHConsumer; use Articus\PathHandler\Producer as PHProducer; use Articus\PathHandler\Attribute as PHAttribute; use Articus\PathHandler\Exception as PHException; use Psr\Http\Message\ServerRequestInterface; -/** - * @PHA\Route(pattern="/user/createWithArray") - */ +#[PHA\Route("/user/createWithArray")] class UserCreateWithArray { /** * Creates list of users with given input array - * @PHA\Post() - * TODO check if consumer is valid, if it has correct priority and if it can be moved to class annotation - * @PHA\Consumer(name=PHConsumer\Json::class, mediaRange="application/json") - * TODO check if attribute is valid and can handle your container type - * @PHA\Attribute(name=PHAttribute\Transfer::class, options={"type":"\App\DTO\User[]","objectAttr":"bodyData"}) - * @param ServerRequestInterface $request - * - * @throws PHException\HttpCode 501 if the method is not implemented */ + #[PHA\Post()] + // TODO check if consumer is valid, if it has correct priority and if it can be moved to class annotation + #[PHA\Consumer("application/json", PHConsumer\Json::class)] + #[PHA\Attribute(PHAttribute\Transfer::class, ["type" => \App\DTO\Collection36::class, "objectAttr" => "bodyData"])] public function createUsersWithArrayInput(ServerRequestInterface $request) { //TODO implement method - /** @var \App\DTO\User[] $bodyData */ + /** @var \App\DTO\Collection36 $bodyData */ $bodyData = $request->getAttribute("bodyData"); throw new PHException\HttpCode(501, "Not implemented"); } diff --git a/samples/openapi3/server/petstore/php-mezzio-ph/src/App/Handler/UserCreateWithList.php b/samples/server/petstore/php-mezzio-ph-modern/src/App/Handler/UserCreateWithList.php similarity index 52% rename from samples/openapi3/server/petstore/php-mezzio-ph/src/App/Handler/UserCreateWithList.php rename to samples/server/petstore/php-mezzio-ph-modern/src/App/Handler/UserCreateWithList.php index b34cca7045f..1d415fcee23 100644 --- a/samples/openapi3/server/petstore/php-mezzio-ph/src/App/Handler/UserCreateWithList.php +++ b/samples/server/petstore/php-mezzio-ph-modern/src/App/Handler/UserCreateWithList.php @@ -3,33 +3,27 @@ declare(strict_types=1); namespace App\Handler; -use Articus\PathHandler\Annotation as PHA; +use Articus\PathHandler\PhpAttribute as PHA; use Articus\PathHandler\Consumer as PHConsumer; use Articus\PathHandler\Producer as PHProducer; use Articus\PathHandler\Attribute as PHAttribute; use Articus\PathHandler\Exception as PHException; use Psr\Http\Message\ServerRequestInterface; -/** - * @PHA\Route(pattern="/user/createWithList") - */ +#[PHA\Route("/user/createWithList")] class UserCreateWithList { /** * Creates list of users with given input array - * @PHA\Post() - * TODO check if consumer is valid, if it has correct priority and if it can be moved to class annotation - * @PHA\Consumer(name=PHConsumer\Json::class, mediaRange="application/json") - * TODO check if attribute is valid and can handle your container type - * @PHA\Attribute(name=PHAttribute\Transfer::class, options={"type":"\App\DTO\User[]","objectAttr":"bodyData"}) - * @param ServerRequestInterface $request - * - * @throws PHException\HttpCode 501 if the method is not implemented */ + #[PHA\Post()] + // TODO check if consumer is valid, if it has correct priority and if it can be moved to class annotation + #[PHA\Consumer("application/json", PHConsumer\Json::class)] + #[PHA\Attribute(PHAttribute\Transfer::class, ["type" => \App\DTO\Collection36::class, "objectAttr" => "bodyData"])] public function createUsersWithListInput(ServerRequestInterface $request) { //TODO implement method - /** @var \App\DTO\User[] $bodyData */ + /** @var \App\DTO\Collection36 $bodyData */ $bodyData = $request->getAttribute("bodyData"); throw new PHException\HttpCode(501, "Not implemented"); } diff --git a/samples/server/petstore/php-mezzio-ph-modern/src/App/Handler/UserLogin.php b/samples/server/petstore/php-mezzio-ph-modern/src/App/Handler/UserLogin.php new file mode 100644 index 00000000000..38a502537f7 --- /dev/null +++ b/samples/server/petstore/php-mezzio-ph-modern/src/App/Handler/UserLogin.php @@ -0,0 +1,36 @@ + \App\DTO\LoginUserQueryData::class, + "objectAttr" => "queryData", + "source" => PHAttribute\Transfer::SOURCE_GET + ])] + // TODO check if producer is valid, if it has correct priority and if it can be moved to class annotation + #[PHA\Producer("application/xml", PHProducer\Transfer::class)] + // TODO check if producer is valid, if it has correct priority and if it can be moved to class annotation + #[PHA\Producer("application/json", PHProducer\Transfer::class)] + public function loginUser(ServerRequestInterface $request): string + { + //TODO implement method + /** @var \App\DTO\LoginUserQueryData $queryData */ + $queryData = $request->getAttribute("queryData"); + throw new PHException\HttpCode(501, "Not implemented"); + } +} diff --git a/samples/openapi3/server/petstore/php-mezzio-ph/src/App/Handler/UserLogout.php b/samples/server/petstore/php-mezzio-ph-modern/src/App/Handler/UserLogout.php similarity index 70% rename from samples/openapi3/server/petstore/php-mezzio-ph/src/App/Handler/UserLogout.php rename to samples/server/petstore/php-mezzio-ph-modern/src/App/Handler/UserLogout.php index 4c0d8b1bb06..7cb7b9a8a2e 100644 --- a/samples/openapi3/server/petstore/php-mezzio-ph/src/App/Handler/UserLogout.php +++ b/samples/server/petstore/php-mezzio-ph-modern/src/App/Handler/UserLogout.php @@ -3,25 +3,20 @@ declare(strict_types=1); namespace App\Handler; -use Articus\PathHandler\Annotation as PHA; +use Articus\PathHandler\PhpAttribute as PHA; use Articus\PathHandler\Consumer as PHConsumer; use Articus\PathHandler\Producer as PHProducer; use Articus\PathHandler\Attribute as PHAttribute; use Articus\PathHandler\Exception as PHException; use Psr\Http\Message\ServerRequestInterface; -/** - * @PHA\Route(pattern="/user/logout") - */ +#[PHA\Route("/user/logout")] class UserLogout { /** * Logs out current logged in user session - * @PHA\Get() - * @param ServerRequestInterface $request - * - * @throws PHException\HttpCode 501 if the method is not implemented */ + #[PHA\Get()] public function logoutUser(ServerRequestInterface $request) { //TODO implement method diff --git a/samples/openapi3/server/petstore/php-mezzio-ph/src/App/Handler/UserUsername.php b/samples/server/petstore/php-mezzio-ph-modern/src/App/Handler/UserUsername.php similarity index 51% rename from samples/openapi3/server/petstore/php-mezzio-ph/src/App/Handler/UserUsername.php rename to samples/server/petstore/php-mezzio-ph-modern/src/App/Handler/UserUsername.php index ce3de984969..68be5f4fc1a 100644 --- a/samples/openapi3/server/petstore/php-mezzio-ph/src/App/Handler/UserUsername.php +++ b/samples/server/petstore/php-mezzio-ph-modern/src/App/Handler/UserUsername.php @@ -3,25 +3,20 @@ declare(strict_types=1); namespace App\Handler; -use Articus\PathHandler\Annotation as PHA; +use Articus\PathHandler\PhpAttribute as PHA; use Articus\PathHandler\Consumer as PHConsumer; use Articus\PathHandler\Producer as PHProducer; use Articus\PathHandler\Attribute as PHAttribute; use Articus\PathHandler\Exception as PHException; use Psr\Http\Message\ServerRequestInterface; -/** - * @PHA\Route(pattern="/user/{username}") - */ +#[PHA\Route("/user/{username}")] class UserUsername { /** * Delete user - * @PHA\Delete() - * @param ServerRequestInterface $request - * - * @throws PHException\HttpCode 501 if the method is not implemented */ + #[PHA\Delete()] public function deleteUser(ServerRequestInterface $request) { //TODO implement method @@ -29,17 +24,12 @@ class UserUsername } /** * Get user by user name - * @PHA\Get() - * TODO check if producer is valid, if it has correct priority and if it can be moved to class annotation - * @PHA\Producer(name=PHProducer\Transfer::class, mediaType="application/xml") - * TODO check if producer is valid, if it has correct priority and if it can be moved to class annotation - * @PHA\Producer(name=PHProducer\Transfer::class, mediaType="application/json") - * @param ServerRequestInterface $request - * - * @throws PHException\HttpCode 501 if the method is not implemented - * - * @return \App\DTO\User */ + #[PHA\Get()] + // TODO check if producer is valid, if it has correct priority and if it can be moved to class annotation + #[PHA\Producer("application/xml", PHProducer\Transfer::class)] + // TODO check if producer is valid, if it has correct priority and if it can be moved to class annotation + #[PHA\Producer("application/json", PHProducer\Transfer::class)] public function getUserByName(ServerRequestInterface $request): \App\DTO\User { //TODO implement method @@ -47,14 +37,11 @@ class UserUsername } /** * Updated user - * @PHA\Put() - * TODO check if consumer is valid, if it has correct priority and if it can be moved to class annotation - * @PHA\Consumer(name=PHConsumer\Json::class, mediaRange="application/json") - * @PHA\Attribute(name=PHAttribute\Transfer::class, options={"type":\App\DTO\User::class,"objectAttr":"bodyData"}) - * @param ServerRequestInterface $request - * - * @throws PHException\HttpCode 501 if the method is not implemented */ + #[PHA\Put()] + // TODO check if consumer is valid, if it has correct priority and if it can be moved to class annotation + #[PHA\Consumer("application/json", PHConsumer\Json::class)] + #[PHA\Attribute(PHAttribute\Transfer::class, ["type" => \App\DTO\User::class, "objectAttr" => "bodyData"])] public function updateUser(ServerRequestInterface $request) { //TODO implement method diff --git a/samples/openapi3/server/petstore/php-mezzio-ph/src/App/Middleware/InternalServerError.php b/samples/server/petstore/php-mezzio-ph-modern/src/App/Middleware/InternalServerError.php similarity index 82% rename from samples/openapi3/server/petstore/php-mezzio-ph/src/App/Middleware/InternalServerError.php rename to samples/server/petstore/php-mezzio-ph-modern/src/App/Middleware/InternalServerError.php index f0354421e00..bc6d5969e2a 100644 --- a/samples/openapi3/server/petstore/php-mezzio-ph/src/App/Middleware/InternalServerError.php +++ b/samples/server/petstore/php-mezzio-ph-modern/src/App/Middleware/InternalServerError.php @@ -11,17 +11,8 @@ use Laminas\Stdlib\ErrorHandler; class InternalServerError implements MiddlewareInterface { - /** - * @var callable - */ - protected $responseGenerator; - - /** - * @param callable $responseGenerator - */ - public function __construct(callable $responseGenerator) + public function __construct(protected \Closure $responseGenerator) { - $this->responseGenerator = $responseGenerator; } /** diff --git a/samples/server/petstore/php-mezzio-ph/.openapi-generator/FILES b/samples/server/petstore/php-mezzio-ph/.openapi-generator/FILES index fc8224fecb8..bc9a68917b6 100644 --- a/samples/server/petstore/php-mezzio-ph/.openapi-generator/FILES +++ b/samples/server/petstore/php-mezzio-ph/.openapi-generator/FILES @@ -9,6 +9,43 @@ composer.json public/index.php src/App/DTO/ApiResponse.php src/App/DTO/Category.php +src/App/DTO/Collection.php +src/App/DTO/Collection1.php +src/App/DTO/Collection10.php +src/App/DTO/Collection11.php +src/App/DTO/Collection12.php +src/App/DTO/Collection13.php +src/App/DTO/Collection14.php +src/App/DTO/Collection15.php +src/App/DTO/Collection16.php +src/App/DTO/Collection17.php +src/App/DTO/Collection18.php +src/App/DTO/Collection19.php +src/App/DTO/Collection2.php +src/App/DTO/Collection20.php +src/App/DTO/Collection21.php +src/App/DTO/Collection22.php +src/App/DTO/Collection23.php +src/App/DTO/Collection24.php +src/App/DTO/Collection25.php +src/App/DTO/Collection26.php +src/App/DTO/Collection27.php +src/App/DTO/Collection28.php +src/App/DTO/Collection29.php +src/App/DTO/Collection3.php +src/App/DTO/Collection30.php +src/App/DTO/Collection31.php +src/App/DTO/Collection32.php +src/App/DTO/Collection33.php +src/App/DTO/Collection34.php +src/App/DTO/Collection35.php +src/App/DTO/Collection36.php +src/App/DTO/Collection4.php +src/App/DTO/Collection5.php +src/App/DTO/Collection6.php +src/App/DTO/Collection7.php +src/App/DTO/Collection8.php +src/App/DTO/Collection9.php src/App/DTO/FindPetsByStatusQueryData.php src/App/DTO/FindPetsByTagsQueryData.php src/App/DTO/LoginUserQueryData.php diff --git a/samples/server/petstore/php-mezzio-ph/.openapi-generator/VERSION b/samples/server/petstore/php-mezzio-ph/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/server/petstore/php-mezzio-ph/.openapi-generator/VERSION +++ b/samples/server/petstore/php-mezzio-ph/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/server/petstore/php-mezzio-ph/README.md b/samples/server/petstore/php-mezzio-ph/README.md index 584fd156879..a8047005901 100644 --- a/samples/server/petstore/php-mezzio-ph/README.md +++ b/samples/server/petstore/php-mezzio-ph/README.md @@ -5,9 +5,9 @@ Generated by the [OpenAPI Generator](https://openapi-generator.tech) project. ## Overview This server stub aims to provide light, yet comprehensive structure for your API project using: -- PHP: >=7.2 +- PHP: >=7.3 - [Laminas Mezzio](https://docs.mezzio.dev/mezzio/): >=3.2 -- [Path Handler](https://github.com/Articus/PathHandler): >=0.6 +- [Path Handler](https://github.com/Articus/PathHandler): >=0.7 ## How to use All you have to do to start development is: diff --git a/samples/server/petstore/php-mezzio-ph/application/config.yml b/samples/server/petstore/php-mezzio-ph/application/config.yml index 1f106812353..71371becf21 100644 --- a/samples/server/petstore/php-mezzio-ph/application/config.yml +++ b/samples/server/petstore/php-mezzio-ph/application/config.yml @@ -9,10 +9,11 @@ # router: # cache: # directory: ./data/cache/PathHandler -# #Enable handler metadata cache -# metadata: -# cache: -# directory: ./data/cache/PathHandler + +#Enable handler metadata cache +#Articus\PathHandler\MetadataProvider\Annotation: +# cache: +# directory: ./data/cache/PathHandler #Enable data transfer metadata cache for DTOs #Articus\DataTransfer\MetadataProvider\Annotation: diff --git a/samples/server/petstore/php-mezzio-ph/application/config/data_transfer.yml b/samples/server/petstore/php-mezzio-ph/application/config/data_transfer.yml index c5174147c23..548c898fb9c 100644 --- a/samples/server/petstore/php-mezzio-ph/application/config/data_transfer.yml +++ b/samples/server/petstore/php-mezzio-ph/application/config/data_transfer.yml @@ -16,6 +16,10 @@ Articus\DataTransfer\Strategy\PluginManager: factories: Date: OpenAPIGenerator\Common\Strategy\Factory\MutableDate DateTime: OpenAPIGenerator\Common\Strategy\Factory\MutableDateTime + ObjectList: OpenAPIGenerator\Common\Strategy\Factory\NoArgObjectList + ObjectMap: OpenAPIGenerator\Common\Strategy\Factory\NoArgObjectMap + ScalarList: OpenAPIGenerator\Common\Strategy\Factory\ScalarList + ScalarMap: OpenAPIGenerator\Common\Strategy\Factory\ScalarMap Articus\DataTransfer\Validator\PluginManager: invokables: @@ -24,3 +28,7 @@ Articus\DataTransfer\Validator\PluginManager: QueryStringScalarArray: OpenAPIGenerator\Common\Validator\QueryStringScalarArray abstract_factories: - Articus\DataTransfer\Validator\Factory\Laminas + +validators: + invokables: + Count: Laminas\Validator\IsCountable diff --git a/samples/server/petstore/php-mezzio-ph/application/config/path_handler.yml b/samples/server/petstore/php-mezzio-ph/application/config/path_handler.yml index 25995b20d6f..174f6fc3d26 100644 --- a/samples/server/petstore/php-mezzio-ph/application/config/path_handler.yml +++ b/samples/server/petstore/php-mezzio-ph/application/config/path_handler.yml @@ -1,8 +1,13 @@ dependencies: factories: - Mezzio\Router\RouterInterface: Articus\PathHandler\RouteInjection\Factory + Mezzio\Router\RouterInterface: Articus\PathHandler\RouteInjectionFactory + Articus\PathHandler\MetadataProviderInterface: Articus\PathHandler\MetadataProvider\Factory\Annotation + Articus\PathHandler\Handler\PluginManager: Articus\PathHandler\Handler\Factory\PluginManager + Articus\PathHandler\Consumer\PluginManager: Articus\PathHandler\Consumer\Factory\PluginManager + Articus\PathHandler\Attribute\PluginManager: Articus\PathHandler\Attribute\Factory\PluginManager + Articus\PathHandler\Producer\PluginManager: Articus\PathHandler\Producer\Factory\PluginManager -Articus\PathHandler\RouteInjection\Factory: +Articus\PathHandler\RouteInjectionFactory: paths: '/v2': - App\Handler\Pet @@ -19,18 +24,22 @@ Articus\PathHandler\RouteInjection\Factory: - App\Handler\UserLogin - App\Handler\UserLogout - App\Handler\UserUsername - handlers: - abstract_factories: - - Laminas\ServiceManager\AbstractFactory\ConfigAbstractFactory -# consumers: -# factories: -# invokables: -# attributes: -# factories: -# invokables: -# producers: -# factories: -# invokables: + +Articus\PathHandler\Handler\PluginManager: + abstract_factories: + - Laminas\ServiceManager\AbstractFactory\ConfigAbstractFactory + +#Articus\PathHandler\Consumer\PluginManager: +# factories: +# invokables: + +#Articus\PathHandler\Attribute\PluginManager: +# factories: +# invokables: + +#Articus\PathHandler\Producer\PluginManager: +# factories: +# invokables: Laminas\ServiceManager\AbstractFactory\ConfigAbstractFactory: App\Handler\Pet: [] diff --git a/samples/server/petstore/php-mezzio-ph/composer.json b/samples/server/petstore/php-mezzio-ph/composer.json index 54f8e97226c..c98cf998302 100644 --- a/samples/server/petstore/php-mezzio-ph/composer.json +++ b/samples/server/petstore/php-mezzio-ph/composer.json @@ -5,13 +5,13 @@ "version": "1.0.0", "type": "project", "require": { - "php": "^7.2", + "php": "^7.3 || ^8.0", "ext-yaml": "^2.0", "mezzio/mezzio": "^3.2", "laminas/laminas-diactoros": "^2.1", - "articus/path-handler": "^0.6", - "articus/data-transfer": "^0.4", - "articus/openapi-generator-common": "^0.1", + "articus/path-handler": "^0.7", + "articus/data-transfer": "^0.5", + "articus/openapi-generator-common": "^0.2", "doctrine/annotations": "^1.10", "psr/simple-cache": "^1.0", "laminas/laminas-config": "^3.4", diff --git a/samples/server/petstore/php-mezzio-ph/src/App/DTO/ApiResponse.php b/samples/server/petstore/php-mezzio-ph/src/App/DTO/ApiResponse.php index a08cb2c9275..0161f75b2b2 100644 --- a/samples/server/petstore/php-mezzio-ph/src/App/DTO/ApiResponse.php +++ b/samples/server/petstore/php-mezzio-ph/src/App/DTO/ApiResponse.php @@ -16,16 +16,19 @@ class ApiResponse * @var int|null */ public $code; + /** * @DTA\Data(field="type", nullable=true) * @DTA\Validator(name="Scalar", options={"type":"string"}) * @var string|null */ public $type; + /** * @DTA\Data(field="message", nullable=true) * @DTA\Validator(name="Scalar", options={"type":"string"}) * @var string|null */ public $message; + } diff --git a/samples/server/petstore/php-mezzio-ph/src/App/DTO/Category.php b/samples/server/petstore/php-mezzio-ph/src/App/DTO/Category.php index 7b65c273d40..41a221be1cf 100644 --- a/samples/server/petstore/php-mezzio-ph/src/App/DTO/Category.php +++ b/samples/server/petstore/php-mezzio-ph/src/App/DTO/Category.php @@ -16,6 +16,7 @@ class Category * @var int|null */ public $id; + /** * @DTA\Data(field="name", nullable=true) * @DTA\Validator(name="Scalar", options={"type":"string"}) @@ -23,4 +24,5 @@ class Category * @var string|null */ public $name; + } diff --git a/samples/server/petstore/php-mezzio-ph/src/App/DTO/Collection.php b/samples/server/petstore/php-mezzio-ph/src/App/DTO/Collection.php new file mode 100644 index 00000000000..0e478eb4bd8 --- /dev/null +++ b/samples/server/petstore/php-mezzio-ph/src/App/DTO/Collection.php @@ -0,0 +1,16 @@ +get(Middleware\InternalServerError::class); - if (!($errorMiddleware instanceof Middleware\InternalServerError)) { - throw new \LogicException(\sprintf( - 'Invalid error middleware: expecting %s, not %s.', - Middleware\InternalServerError::class, - \is_object($errorMiddleware) ? \get_class($errorMiddleware) : \gettype($errorMiddleware) - )); - } + $errorMiddleware = self::getErrorMiddleware($container); $pipeline = new MiddlewarePipe(); $runner = new RequestHandlerRunner( $pipeline, $container->get(EmitterInterface::class), $container->get(ServerRequestInterface::class), - function(\Throwable $error) use ($errorMiddleware) : ResponseInterface + static function(\Throwable $error) use ($errorMiddleware) : ResponseInterface { return $errorMiddleware->handleError($error); } @@ -55,4 +48,9 @@ class Factory implements FactoryInterface return $application; } + + protected static function getErrorMiddleware(ContainerInterface $container): Middleware\InternalServerError + { + return $container->get(Middleware\InternalServerError::class); + } } diff --git a/samples/server/petstore/php-mezzio-ph/src/App/Handler/PetFindByStatus.php b/samples/server/petstore/php-mezzio-ph/src/App/Handler/PetFindByStatus.php index c1c1ce75400..917f9f767a3 100644 --- a/samples/server/petstore/php-mezzio-ph/src/App/Handler/PetFindByStatus.php +++ b/samples/server/petstore/php-mezzio-ph/src/App/Handler/PetFindByStatus.php @@ -31,10 +31,9 @@ class PetFindByStatus * * @throws PHException\HttpCode 501 if the method is not implemented * - * TODO check if generated return container type is valid - * @return \App\DTO\Pet[] + * @return \App\DTO\Collection19 */ - public function findPetsByStatus(ServerRequestInterface $request): array + public function findPetsByStatus(ServerRequestInterface $request): \App\DTO\Collection19 { //TODO implement method /** @var \App\DTO\FindPetsByStatusQueryData $queryData */ diff --git a/samples/server/petstore/php-mezzio-ph/src/App/Handler/PetFindByTags.php b/samples/server/petstore/php-mezzio-ph/src/App/Handler/PetFindByTags.php index b722a310efb..b74484da909 100644 --- a/samples/server/petstore/php-mezzio-ph/src/App/Handler/PetFindByTags.php +++ b/samples/server/petstore/php-mezzio-ph/src/App/Handler/PetFindByTags.php @@ -31,10 +31,9 @@ class PetFindByTags * * @throws PHException\HttpCode 501 if the method is not implemented * - * TODO check if generated return container type is valid - * @return \App\DTO\Pet[] + * @return \App\DTO\Collection26 */ - public function findPetsByTags(ServerRequestInterface $request): array + public function findPetsByTags(ServerRequestInterface $request): \App\DTO\Collection26 { //TODO implement method /** @var \App\DTO\FindPetsByTagsQueryData $queryData */ diff --git a/samples/server/petstore/php-mezzio-ph/src/App/Handler/StoreInventory.php b/samples/server/petstore/php-mezzio-ph/src/App/Handler/StoreInventory.php index c1ca1be83d1..c9150110c44 100644 --- a/samples/server/petstore/php-mezzio-ph/src/App/Handler/StoreInventory.php +++ b/samples/server/petstore/php-mezzio-ph/src/App/Handler/StoreInventory.php @@ -24,10 +24,9 @@ class StoreInventory * * @throws PHException\HttpCode 501 if the method is not implemented * - * TODO check if generated return container type is valid - * @return array + * @return \App\DTO\Collection34 */ - public function getInventory(ServerRequestInterface $request): array + public function getInventory(ServerRequestInterface $request): \App\DTO\Collection34 { //TODO implement method throw new PHException\HttpCode(501, "Not implemented"); diff --git a/samples/server/petstore/php-mezzio-ph/src/App/Handler/UserCreateWithArray.php b/samples/server/petstore/php-mezzio-ph/src/App/Handler/UserCreateWithArray.php index a8a39215bab..8df1e8b18fd 100644 --- a/samples/server/petstore/php-mezzio-ph/src/App/Handler/UserCreateWithArray.php +++ b/samples/server/petstore/php-mezzio-ph/src/App/Handler/UserCreateWithArray.php @@ -20,8 +20,7 @@ class UserCreateWithArray * @PHA\Post() * TODO check if consumer is valid, if it has correct priority and if it can be moved to class annotation * @PHA\Consumer(name=PHConsumer\Json::class, mediaRange="application/json") - * TODO check if attribute is valid and can handle your container type - * @PHA\Attribute(name=PHAttribute\Transfer::class, options={"type":"\App\DTO\User[]","objectAttr":"bodyData"}) + * @PHA\Attribute(name=PHAttribute\Transfer::class, options={"type":\App\DTO\Collection36::class,"objectAttr":"bodyData"}) * @param ServerRequestInterface $request * * @throws PHException\HttpCode 501 if the method is not implemented @@ -29,7 +28,7 @@ class UserCreateWithArray public function createUsersWithArrayInput(ServerRequestInterface $request) { //TODO implement method - /** @var \App\DTO\User[] $bodyData */ + /** @var \App\DTO\Collection36 $bodyData */ $bodyData = $request->getAttribute("bodyData"); throw new PHException\HttpCode(501, "Not implemented"); } diff --git a/samples/server/petstore/php-mezzio-ph/src/App/Handler/UserCreateWithList.php b/samples/server/petstore/php-mezzio-ph/src/App/Handler/UserCreateWithList.php index b34cca7045f..dae1cc0f264 100644 --- a/samples/server/petstore/php-mezzio-ph/src/App/Handler/UserCreateWithList.php +++ b/samples/server/petstore/php-mezzio-ph/src/App/Handler/UserCreateWithList.php @@ -20,8 +20,7 @@ class UserCreateWithList * @PHA\Post() * TODO check if consumer is valid, if it has correct priority and if it can be moved to class annotation * @PHA\Consumer(name=PHConsumer\Json::class, mediaRange="application/json") - * TODO check if attribute is valid and can handle your container type - * @PHA\Attribute(name=PHAttribute\Transfer::class, options={"type":"\App\DTO\User[]","objectAttr":"bodyData"}) + * @PHA\Attribute(name=PHAttribute\Transfer::class, options={"type":\App\DTO\Collection36::class,"objectAttr":"bodyData"}) * @param ServerRequestInterface $request * * @throws PHException\HttpCode 501 if the method is not implemented @@ -29,7 +28,7 @@ class UserCreateWithList public function createUsersWithListInput(ServerRequestInterface $request) { //TODO implement method - /** @var \App\DTO\User[] $bodyData */ + /** @var \App\DTO\Collection36 $bodyData */ $bodyData = $request->getAttribute("bodyData"); throw new PHException\HttpCode(501, "Not implemented"); } diff --git a/samples/server/petstore/php-slim4/.openapi-generator/VERSION b/samples/server/petstore/php-slim4/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/server/petstore/php-slim4/.openapi-generator/VERSION +++ b/samples/server/petstore/php-slim4/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x 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 5f68295fc19..e8415097f3a 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,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/server/petstore/python-aiohttp-srclayout/.openapi-generator/VERSION b/samples/server/petstore/python-aiohttp-srclayout/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/server/petstore/python-aiohttp-srclayout/.openapi-generator/VERSION +++ b/samples/server/petstore/python-aiohttp-srclayout/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/server/petstore/python-aiohttp/.openapi-generator/VERSION b/samples/server/petstore/python-aiohttp/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/server/petstore/python-aiohttp/.openapi-generator/VERSION +++ b/samples/server/petstore/python-aiohttp/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/server/petstore/python-blueplanet/.openapi-generator/VERSION b/samples/server/petstore/python-blueplanet/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/server/petstore/python-blueplanet/.openapi-generator/VERSION +++ b/samples/server/petstore/python-blueplanet/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/server/petstore/python-fastapi/.flake8 b/samples/server/petstore/python-fastapi/.flake8 new file mode 100644 index 00000000000..9e008c5bb19 --- /dev/null +++ b/samples/server/petstore/python-fastapi/.flake8 @@ -0,0 +1,3 @@ +[flake8] +max-line-length = 88 +exclude = .git,__pycache__,__init__.py,.mypy_cache,.pytest_cache,.venv diff --git a/samples/server/petstore/python-fastapi/.gitignore b/samples/server/petstore/python-fastapi/.gitignore new file mode 100644 index 00000000000..a81c8ee1219 --- /dev/null +++ b/samples/server/petstore/python-fastapi/.gitignore @@ -0,0 +1,138 @@ +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# 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/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py,cover +.hypothesis/ +.pytest_cache/ +cover/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +.pybuilder/ +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +# For a library or package, you might want to ignore these files since the code is +# intended to run in multiple environments; otherwise, check them in: +# .python-version + +# pipenv +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if having platform-specific dependencies or dependencies +# having no cross-platform support, pipenv may install dependencies that don't work, or not +# install all needed dependencies. +#Pipfile.lock + +# PEP 582; used by e.g. github.com/David-OConnor/pyflow +__pypackages__/ + +# Celery stuff +celerybeat-schedule +celerybeat.pid + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ + +# pytype static type analyzer +.pytype/ + +# Cython debug symbols +cython_debug/ diff --git a/samples/server/petstore/python-fastapi/.openapi-generator-ignore b/samples/server/petstore/python-fastapi/.openapi-generator-ignore new file mode 100644 index 00000000000..7484ee590a3 --- /dev/null +++ b/samples/server/petstore/python-fastapi/.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/python-fastapi/.openapi-generator/FILES b/samples/server/petstore/python-fastapi/.openapi-generator/FILES new file mode 100644 index 00000000000..1d9f0c53109 --- /dev/null +++ b/samples/server/petstore/python-fastapi/.openapi-generator/FILES @@ -0,0 +1,24 @@ +.flake8 +.gitignore +Dockerfile +README.md +docker-compose.yaml +openapi.yaml +pyproject.toml +requirements.txt +setup.cfg +src/openapi_server/apis/__init__.py +src/openapi_server/apis/pet_api.py +src/openapi_server/apis/store_api.py +src/openapi_server/apis/user_api.py +src/openapi_server/main.py +src/openapi_server/models/__init__.py +src/openapi_server/models/api_response.py +src/openapi_server/models/category.py +src/openapi_server/models/extra_models.py +src/openapi_server/models/order.py +src/openapi_server/models/pet.py +src/openapi_server/models/tag.py +src/openapi_server/models/user.py +src/openapi_server/security_api.py +tests/conftest.py diff --git a/samples/server/petstore/python-fastapi/.openapi-generator/VERSION b/samples/server/petstore/python-fastapi/.openapi-generator/VERSION new file mode 100644 index 00000000000..4b448de535c --- /dev/null +++ b/samples/server/petstore/python-fastapi/.openapi-generator/VERSION @@ -0,0 +1 @@ +5.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/python-fastapi/Dockerfile b/samples/server/petstore/python-fastapi/Dockerfile new file mode 100644 index 00000000000..b66458eb417 --- /dev/null +++ b/samples/server/petstore/python-fastapi/Dockerfile @@ -0,0 +1,30 @@ +FROM python:3.7 AS builder + +WORKDIR /usr/src/app + +RUN python3 -m venv /venv +ENV PATH="/venv/bin:$PATH" + +RUN pip install --upgrade pip + +COPY . . +RUN pip install --no-cache-dir . + + +FROM python:3.7 AS test_runner +WORKDIR /tmp +COPY --from=builder /venv /venv +COPY --from=builder /usr/src/app/tests tests +ENV PATH=/venv/bin:$PATH + +# install test dependencies +RUN pip install pytest + +# run tests +RUN pytest tests + + +FROM python:3.7 AS service +WORKDIR /root/app/site-packages +COPY --from=test_runner /venv /venv +ENV PATH=/venv/bin:$PATH diff --git a/samples/server/petstore/python-fastapi/README.md b/samples/server/petstore/python-fastapi/README.md new file mode 100644 index 00000000000..34a725321ea --- /dev/null +++ b/samples/server/petstore/python-fastapi/README.md @@ -0,0 +1,38 @@ +# OpenAPI generated FastAPI server + +This Python package is automatically generated by the [OpenAPI Generator](https://openapi-generator.tech) project: + +- API version: 1.0.0 +- Build package: org.openapitools.codegen.languages.PythonFastAPIServerCodegen + +## Requirements. + +Python >= 3.7 + +## Installation & Usage + +To run the server, please execute the following from the root directory: + +```bash +pip3 install -r requirements.txt +uvicorn main:app --host 0.0.0.0 --port 8080 +``` + +and open your browser at `http://localhost:8080/docs/` to see the docs. + +## Running with Docker + +To run the server on a Docker container, please execute the following from the root directory: + +```bash +docker-compose up --build +``` + +## Tests + +To run the tests: + +```bash +pip3 install pytest +PYTHONPATH=src pytest tests +``` diff --git a/samples/server/petstore/python-fastapi/docker-compose.yaml b/samples/server/petstore/python-fastapi/docker-compose.yaml new file mode 100644 index 00000000000..638e4e00d34 --- /dev/null +++ b/samples/server/petstore/python-fastapi/docker-compose.yaml @@ -0,0 +1,9 @@ +version: '3.6' +services: + service: + build: + context: . + target: service + ports: + - "8080:8080" + command: uvicorn openapi_server.main:app --host 0.0.0.0 --port 8080 diff --git a/samples/server/petstore/python-fastapi/openapi.yaml b/samples/server/petstore/python-fastapi/openapi.yaml new file mode 100644 index 00000000000..477694ade00 --- /dev/null +++ b/samples/server/petstore/python-fastapi/openapi.yaml @@ -0,0 +1,840 @@ +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 +- description: Access to Petstore orders + name: store +- description: Operations about user + name: user +paths: + /pet: + post: + 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 + put: + operationId: updatePet + 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 + "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 + /pet/findByStatus: + get: + description: Multiple status values can be provided with comma separated strings + operationId: findPetsByStatus + 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 + /pet/findByTags: + get: + deprecated: true + description: Multiple tags can be provided with comma separated strings. Use + tag1, tag2, tag3 for testing. + operationId: findPetsByTags + 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 + /pet/{petId}: + delete: + operationId: deletePet + 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 + get: + description: Returns a single pet + operationId: getPetById + 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 + post: + operationId: updatePetWithForm + 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/inline_object' + content: + application/x-www-form-urlencoded: + schema: + properties: + name: + description: Updated name of the pet + type: string + status: + description: Updated status of the pet + type: string + type: object + responses: + "405": + description: Invalid input + security: + - petstore_auth: + - write:pets + - read:pets + summary: Updates a pet in the store with form data + tags: + - pet + /pet/{petId}/uploadImage: + post: + operationId: uploadFile + 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/inline_object_1' + content: + multipart/form-data: + schema: + properties: + additionalMetadata: + description: Additional data to pass to server + type: string + file: + description: file to upload + format: binary + type: string + type: object + 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 + /store/inventory: + get: + description: Returns a map of status codes to quantities + operationId: getInventory + 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 + /store/order: + post: + operationId: placeOrder + 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 + /store/order/{orderId}: + delete: + description: For valid response try integer IDs with value < 1000. Anything + above 1000 or nonintegers will generate API errors + operationId: deleteOrder + 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 + get: + description: For valid response try integer IDs with value <= 5 or > 10. Other + values will generated exceptions + operationId: getOrderById + 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 + /user: + post: + description: This can only be done by the logged in user. + operationId: createUser + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/User' + description: Created user object + required: true + responses: + default: + description: successful operation + security: + - api_key: [] + summary: Create user + tags: + - user + /user/createWithArray: + post: + operationId: createUsersWithArrayInput + requestBody: + $ref: '#/components/requestBodies/UserArray' + responses: + default: + description: successful operation + security: + - api_key: [] + summary: Creates list of users with given input array + tags: + - user + /user/createWithList: + post: + operationId: createUsersWithListInput + requestBody: + $ref: '#/components/requestBodies/UserArray' + responses: + default: + description: successful operation + security: + - api_key: [] + summary: Creates list of users with given input array + tags: + - user + /user/login: + get: + operationId: loginUser + 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 `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 + schema: + format: int32 + type: integer + style: simple + X-Expires-After: + description: date in UTC when toekn 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 + /user/logout: + get: + operationId: logoutUser + responses: + default: + description: successful operation + security: + - api_key: [] + summary: Logs out current logged in user session + tags: + - user + /user/{username}: + delete: + description: This can only be done by the logged in user. + operationId: deleteUser + 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: + - api_key: [] + summary: Delete user + tags: + - user + get: + operationId: getUserByName + 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 + put: + description: This can only be done by the logged in user. + operationId: updateUser + 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: + - api_key: [] + summary: Updated user + tags: + - user +components: + requestBodies: + UserArray: + content: + application/json: + schema: + items: + $ref: '#/components/schemas/User' + type: array + 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 + inline_object: + content: + application/x-www-form-urlencoded: + schema: + $ref: '#/components/schemas/inline_object' + inline_object_1: + content: + multipart/form-data: + schema: + $ref: '#/components/schemas/inline_object_1' + 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 + type: integer + username: + type: string + firstName: + type: string + lastName: + type: string + email: + type: string + password: + type: string + phone: + type: string + userStatus: + description: User Status + format: int32 + 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 + 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 + inline_object: + properties: + name: + description: Updated name of the pet + type: string + status: + description: Updated status of the pet + type: string + type: object + inline_object_1: + properties: + additionalMetadata: + description: Additional data to pass to server + type: string + file: + description: file to upload + format: binary + type: string + type: object + 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 + api_key: + in: header + name: api_key + type: apiKey diff --git a/samples/server/petstore/python-fastapi/pom.xml b/samples/server/petstore/python-fastapi/pom.xml new file mode 100644 index 00000000000..cec32c1dc9a --- /dev/null +++ b/samples/server/petstore/python-fastapi/pom.xml @@ -0,0 +1,40 @@ + + 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/pyproject.toml b/samples/server/petstore/python-fastapi/pyproject.toml new file mode 100644 index 00000000000..c2826df3020 --- /dev/null +++ b/samples/server/petstore/python-fastapi/pyproject.toml @@ -0,0 +1,30 @@ +[build-system] +requires = ["setuptools", "wheel"] +build-backend = "setuptools.build_meta" + +[tool.black] +line-length = 88 +exclude = ''' +( + /( + \.eggs # exclude a few common directories in the + | \.git # root of the project + | \.hg + | \.mypy_cache + | \.tox + | \.venv + | _build + | buck-out + | build + | dist + )/ +) +''' + +[tool.isort] +profile = "black" +skip = [ + '.eggs', '.git', '.hg', '.mypy_cache', '.nox', '.pants.d', '.tox', + '.venv', '_build', 'buck-out', 'build', 'dist', 'node_modules', 'venv', +] +skip_gitignore = true diff --git a/samples/server/petstore/python-fastapi/requirements.txt b/samples/server/petstore/python-fastapi/requirements.txt new file mode 100644 index 00000000000..ce66f96d42c --- /dev/null +++ b/samples/server/petstore/python-fastapi/requirements.txt @@ -0,0 +1,36 @@ +aiofiles==0.5.0 +aniso8601==7.0.0 +async-exit-stack==1.0.1 +async-generator==1.10 +certifi==2020.12.5 +chardet==4.0.0 +click==7.1.2 +dnspython==2.1.0 +email-validator==1.1.2 +fastapi==0.65.1 +graphene==2.1.8 +graphql-core==2.3.2 +graphql-relay==2.0.1 +h11==0.12.0 +httptools==0.1.2 +idna==2.10 +itsdangerous==1.1.0 +Jinja2==2.11.3 +MarkupSafe==2.0.1 +orjson==3.5.2 +promise==2.3 +pydantic==1.8.2 +python-dotenv==0.17.1 +python-multipart==0.0.5 +PyYAML==5.4.1 +requests==2.25.1 +Rx==1.6.1 +six==1.16.0 +starlette==0.14.2 +typing-extensions==3.10.0.0 +ujson==4.0.2 +urllib3==1.26.4 +uvicorn==0.13.4 +uvloop==0.14.0 +watchgod==0.7 +websockets==8.1 diff --git a/samples/server/petstore/python-fastapi/setup.cfg b/samples/server/petstore/python-fastapi/setup.cfg new file mode 100644 index 00000000000..cafb7b8cf7d --- /dev/null +++ b/samples/server/petstore/python-fastapi/setup.cfg @@ -0,0 +1,23 @@ +[metadata] +name = openapi_server +version = 1.0.0 +description = This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. +long_description = file: README.md +keywords = OpenAPI OpenAPI Petstore +python_requires = >= 3.7.* +classifiers = + Operating System :: OS Independent + Programming Language :: Python :: 3 + Programming Language :: Python :: 3.7 + +[options] +install_requires = + fastapi[all] +setup_requires = + setuptools +package_dir= + =src +packages=find_namespace: + +[options.packages.find] +where=src diff --git a/samples/server/petstore/python-fastapi/src/openapi_server/apis/__init__.py b/samples/server/petstore/python-fastapi/src/openapi_server/apis/__init__.py new file mode 100644 index 00000000000..e69de29bb2d 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 new file mode 100644 index 00000000000..513d49d1b7a --- /dev/null +++ b/samples/server/petstore/python-fastapi/src/openapi_server/apis/pet_api.py @@ -0,0 +1,176 @@ +# coding: utf-8 + +from typing import Dict, List # noqa: F401 + +from fastapi import ( # noqa: F401 + APIRouter, + Body, + Cookie, + Depends, + Form, + Header, + Path, + Query, + Response, + Security, + status, +) + +from openapi_server.models.extra_models import TokenModel # noqa: F401 +from openapi_server.models.api_response import ApiResponse +from openapi_server.models.pet import Pet +from openapi_server.security_api import get_token_petstore_auth, get_token_api_key + +router = APIRouter() + + +@router.post( + "/pet", + responses={ + 200: {"model": Pet, "description": "successful operation"}, + 405: {"description": "Invalid input"}, + }, + tags=["pet"], + summary="Add a new pet to the store", +) +async def add_pet( + pet: Pet = Body(None, description="Pet object that needs to be added to the store"), + token_petstore_auth: TokenModel = Security( + get_token_petstore_auth, scopes=["write:pets", "read:pets"] + ), +) -> Pet: + ... + + +@router.delete( + "/pet/{petId}", + responses={ + 400: {"description": "Invalid pet value"}, + }, + tags=["pet"], + summary="Deletes a pet", +) +async def delete_pet( + petId: int = Path(None, description="Pet id to delete"), + api_key: str = Header(None, description=""), + token_petstore_auth: TokenModel = Security( + get_token_petstore_auth, scopes=["write:pets", "read:pets"] + ), +) -> None: + ... + + +@router.get( + "/pet/findByStatus", + responses={ + 200: {"model": List[Pet], "description": "successful operation"}, + 400: {"description": "Invalid status value"}, + }, + tags=["pet"], + summary="Finds Pets by status", +) +async def find_pets_by_status( + status: List[str] = Query(None, description="Status values that need to be considered for filter"), + token_petstore_auth: TokenModel = Security( + get_token_petstore_auth, scopes=["read:pets"] + ), +) -> List[Pet]: + """Multiple status values can be provided with comma separated strings""" + ... + + +@router.get( + "/pet/findByTags", + responses={ + 200: {"model": List[Pet], "description": "successful operation"}, + 400: {"description": "Invalid tag value"}, + }, + tags=["pet"], + summary="Finds Pets by tags", +) +async def find_pets_by_tags( + tags: List[str] = Query(None, description="Tags to filter by"), + token_petstore_auth: TokenModel = Security( + get_token_petstore_auth, scopes=["read:pets"] + ), +) -> List[Pet]: + """Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.""" + ... + + +@router.get( + "/pet/{petId}", + responses={ + 200: {"model": Pet, "description": "successful operation"}, + 400: {"description": "Invalid ID supplied"}, + 404: {"description": "Pet not found"}, + }, + tags=["pet"], + summary="Find pet by ID", +) +async def get_pet_by_id( + petId: int = Path(None, description="ID of pet to return"), + token_api_key: TokenModel = Security( + get_token_api_key + ), +) -> Pet: + """Returns a single pet""" + ... + + +@router.put( + "/pet", + responses={ + 200: {"model": Pet, "description": "successful operation"}, + 400: {"description": "Invalid ID supplied"}, + 404: {"description": "Pet not found"}, + 405: {"description": "Validation exception"}, + }, + tags=["pet"], + summary="Update an existing pet", +) +async def update_pet( + pet: Pet = Body(None, description="Pet object that needs to be added to the store"), + token_petstore_auth: TokenModel = Security( + get_token_petstore_auth, scopes=["write:pets", "read:pets"] + ), +) -> Pet: + ... + + +@router.post( + "/pet/{petId}", + responses={ + 405: {"description": "Invalid input"}, + }, + tags=["pet"], + summary="Updates a pet in the store with form data", +) +async def update_pet_with_form( + petId: int = Path(None, description="ID of pet that needs to be updated"), + name: str = Form(None, description="Updated name of the pet"), + status: str = Form(None, description="Updated status of the pet"), + token_petstore_auth: TokenModel = Security( + get_token_petstore_auth, scopes=["write:pets", "read:pets"] + ), +) -> None: + ... + + +@router.post( + "/pet/{petId}/uploadImage", + responses={ + 200: {"model": ApiResponse, "description": "successful operation"}, + }, + tags=["pet"], + summary="uploads an image", +) +async def upload_file( + petId: int = Path(None, description="ID of pet to update"), + additional_metadata: str = Form(None, description="Additional data to pass to server"), + file: str = Form(None, description="file to upload"), + token_petstore_auth: TokenModel = Security( + get_token_petstore_auth, scopes=["write:pets", "read:pets"] + ), +) -> ApiResponse: + ... diff --git a/samples/server/petstore/python-fastapi/src/openapi_server/apis/store_api.py b/samples/server/petstore/python-fastapi/src/openapi_server/apis/store_api.py new file mode 100644 index 00000000000..208cacab632 --- /dev/null +++ b/samples/server/petstore/python-fastapi/src/openapi_server/apis/store_api.py @@ -0,0 +1,88 @@ +# coding: utf-8 + +from typing import Dict, List # noqa: F401 + +from fastapi import ( # noqa: F401 + APIRouter, + Body, + Cookie, + Depends, + Form, + Header, + Path, + Query, + Response, + Security, + status, +) + +from openapi_server.models.extra_models import TokenModel # noqa: F401 +from openapi_server.models.order import Order +from openapi_server.security_api import get_token_api_key + +router = APIRouter() + + +@router.delete( + "/store/order/{orderId}", + responses={ + 400: {"description": "Invalid ID supplied"}, + 404: {"description": "Order not found"}, + }, + tags=["store"], + summary="Delete purchase order by ID", +) +async def delete_order( + orderId: str = Path(None, description="ID of the order that needs to be deleted"), +) -> None: + """For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors""" + ... + + +@router.get( + "/store/inventory", + responses={ + 200: {"model": Dict[str, int], "description": "successful operation"}, + }, + tags=["store"], + summary="Returns pet inventories by status", +) +async def get_inventory( + token_api_key: TokenModel = Security( + get_token_api_key + ), +) -> Dict[str, int]: + """Returns a map of status codes to quantities""" + ... + + +@router.get( + "/store/order/{orderId}", + responses={ + 200: {"model": Order, "description": "successful operation"}, + 400: {"description": "Invalid ID supplied"}, + 404: {"description": "Order not found"}, + }, + tags=["store"], + summary="Find purchase order by ID", +) +async def get_order_by_id( + orderId: int = Path(None, description="ID of pet that needs to be fetched", ge=1, le=5), +) -> Order: + """For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions""" + ... + + +@router.post( + "/store/order", + responses={ + 200: {"model": Order, "description": "successful operation"}, + 400: {"description": "Invalid Order"}, + }, + tags=["store"], + summary="Place an order for a pet", +) +async def place_order( + order: Order = Body(None, description="order placed for purchasing the pet"), +) -> Order: + ... 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 new file mode 100644 index 00000000000..8609be647d1 --- /dev/null +++ b/samples/server/petstore/python-fastapi/src/openapi_server/apis/user_api.py @@ -0,0 +1,162 @@ +# coding: utf-8 + +from typing import Dict, List # noqa: F401 + +from fastapi import ( # noqa: F401 + APIRouter, + Body, + Cookie, + Depends, + Form, + Header, + Path, + Query, + Response, + Security, + status, +) + +from openapi_server.models.extra_models import TokenModel # noqa: F401 +from openapi_server.models.user import User +from openapi_server.security_api import get_token_api_key + +router = APIRouter() + + +@router.post( + "/user", + responses={ + 200: {"description": "successful operation"}, + }, + tags=["user"], + summary="Create user", +) +async def create_user( + user: User = Body(None, description="Created user object"), + token_api_key: TokenModel = Security( + get_token_api_key + ), +) -> None: + """This can only be done by the logged in user.""" + ... + + +@router.post( + "/user/createWithArray", + responses={ + 200: {"description": "successful operation"}, + }, + tags=["user"], + summary="Creates list of users with given input array", +) +async def create_users_with_array_input( + user: List[User] = Body(None, description="List of user object"), + token_api_key: TokenModel = Security( + get_token_api_key + ), +) -> None: + ... + + +@router.post( + "/user/createWithList", + responses={ + 200: {"description": "successful operation"}, + }, + tags=["user"], + summary="Creates list of users with given input array", +) +async def create_users_with_list_input( + user: List[User] = Body(None, description="List of user object"), + token_api_key: TokenModel = Security( + get_token_api_key + ), +) -> None: + ... + + +@router.delete( + "/user/{username}", + responses={ + 400: {"description": "Invalid username supplied"}, + 404: {"description": "User not found"}, + }, + tags=["user"], + summary="Delete user", +) +async def delete_user( + username: str = Path(None, description="The name that needs to be deleted"), + token_api_key: TokenModel = Security( + get_token_api_key + ), +) -> None: + """This can only be done by the logged in user.""" + ... + + +@router.get( + "/user/{username}", + responses={ + 200: {"model": User, "description": "successful operation"}, + 400: {"description": "Invalid username supplied"}, + 404: {"description": "User not found"}, + }, + tags=["user"], + summary="Get user by user name", +) +async def get_user_by_name( + username: str = Path(None, description="The name that needs to be fetched. Use user1 for testing."), +) -> User: + ... + + +@router.get( + "/user/login", + responses={ + 200: {"model": str, "description": "successful operation"}, + 400: {"description": "Invalid username/password supplied"}, + }, + tags=["user"], + summary="Logs user into the system", +) +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"), +) -> str: + ... + + +@router.get( + "/user/logout", + responses={ + 200: {"description": "successful operation"}, + }, + tags=["user"], + summary="Logs out current logged in user session", +) +async def logout_user( + token_api_key: TokenModel = Security( + get_token_api_key + ), +) -> None: + ... + + +@router.put( + "/user/{username}", + responses={ + 400: {"description": "Invalid user supplied"}, + 404: {"description": "User not found"}, + }, + tags=["user"], + summary="Updated user", +) +async def update_user( + username: str = Path(None, description="name that need to be deleted"), + user: User = Body(None, description="Updated user object"), + token_api_key: TokenModel = Security( + get_token_api_key + ), +) -> None: + """This can only be done by the logged in user.""" + ... diff --git a/samples/server/petstore/python-fastapi/src/openapi_server/main.py b/samples/server/petstore/python-fastapi/src/openapi_server/main.py new file mode 100644 index 00000000000..eec13ca5eba --- /dev/null +++ b/samples/server/petstore/python-fastapi/src/openapi_server/main.py @@ -0,0 +1,27 @@ +# coding: utf-8 + +""" + 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 +""" + + +from fastapi import FastAPI + +from openapi_server.apis.pet_api import router as PetApiRouter +from openapi_server.apis.store_api import router as StoreApiRouter +from openapi_server.apis.user_api import router as UserApiRouter + +app = FastAPI( + 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.", + version="1.0.0", +) + +app.include_router(PetApiRouter) +app.include_router(StoreApiRouter) +app.include_router(UserApiRouter) diff --git a/samples/server/petstore/python-fastapi/src/openapi_server/models/__init__.py b/samples/server/petstore/python-fastapi/src/openapi_server/models/__init__.py new file mode 100644 index 00000000000..e69de29bb2d diff --git a/samples/server/petstore/python-fastapi/src/openapi_server/models/api_response.py b/samples/server/petstore/python-fastapi/src/openapi_server/models/api_response.py new file mode 100644 index 00000000000..fce5f94edc0 --- /dev/null +++ b/samples/server/petstore/python-fastapi/src/openapi_server/models/api_response.py @@ -0,0 +1,28 @@ +# coding: utf-8 + +from __future__ import annotations +from datetime import date, datetime # noqa: F401 + +import re # noqa: F401 +from typing import Any, Dict, List, Optional # noqa: F401 + +from pydantic import AnyUrl, BaseModel, EmailStr, validator # noqa: F401 + + +class ApiResponse(BaseModel): + """NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + + Do not edit the class manually. + + ApiResponse - a model defined in OpenAPI + + code: The code of this ApiResponse [Optional]. + type: The type of this ApiResponse [Optional]. + message: The message of this ApiResponse [Optional]. + """ + + code: Optional[int] = None + type: Optional[str] = None + message: Optional[str] = None + +ApiResponse.update_forward_refs() diff --git a/samples/server/petstore/python-fastapi/src/openapi_server/models/category.py b/samples/server/petstore/python-fastapi/src/openapi_server/models/category.py new file mode 100644 index 00000000000..de57bf2d2ee --- /dev/null +++ b/samples/server/petstore/python-fastapi/src/openapi_server/models/category.py @@ -0,0 +1,31 @@ +# coding: utf-8 + +from __future__ import annotations +from datetime import date, datetime # noqa: F401 + +import re # noqa: F401 +from typing import Any, Dict, List, Optional # noqa: F401 + +from pydantic import AnyUrl, BaseModel, EmailStr, validator # noqa: F401 + + +class Category(BaseModel): + """NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + + Do not edit the class manually. + + Category - a model defined in OpenAPI + + id: The id of this Category [Optional]. + name: The name of this Category [Optional]. + """ + + id: Optional[int] = None + name: Optional[str] = None + + @validator("name") + def name_pattern(cls, value): + assert value is not None and re.match(r"^[a-zA-Z0-9]+[a-zA-Z0-9\.\-_]*[a-zA-Z0-9]+$", value) + return value + +Category.update_forward_refs() diff --git a/samples/server/petstore/python-fastapi/src/openapi_server/models/extra_models.py b/samples/server/petstore/python-fastapi/src/openapi_server/models/extra_models.py new file mode 100644 index 00000000000..a3a283fb842 --- /dev/null +++ b/samples/server/petstore/python-fastapi/src/openapi_server/models/extra_models.py @@ -0,0 +1,8 @@ +# coding: utf-8 + +from pydantic import BaseModel + +class TokenModel(BaseModel): + """Defines a token model.""" + + sub: str diff --git a/samples/server/petstore/python-fastapi/src/openapi_server/models/order.py b/samples/server/petstore/python-fastapi/src/openapi_server/models/order.py new file mode 100644 index 00000000000..384fec2a3a1 --- /dev/null +++ b/samples/server/petstore/python-fastapi/src/openapi_server/models/order.py @@ -0,0 +1,34 @@ +# coding: utf-8 + +from __future__ import annotations +from datetime import date, datetime # noqa: F401 + +import re # noqa: F401 +from typing import Any, Dict, List, Optional # noqa: F401 + +from pydantic import AnyUrl, BaseModel, EmailStr, validator # noqa: F401 + + +class Order(BaseModel): + """NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + + Do not edit the class manually. + + Order - a model defined in OpenAPI + + id: The id of this Order [Optional]. + pet_id: The pet_id of this Order [Optional]. + quantity: The quantity of this Order [Optional]. + ship_date: The ship_date of this Order [Optional]. + status: The status of this Order [Optional]. + complete: The complete of this Order [Optional]. + """ + + id: Optional[int] = None + pet_id: Optional[int] = None + quantity: Optional[int] = None + ship_date: Optional[datetime] = None + status: Optional[str] = None + complete: Optional[bool] = None + +Order.update_forward_refs() diff --git a/samples/server/petstore/python-fastapi/src/openapi_server/models/pet.py b/samples/server/petstore/python-fastapi/src/openapi_server/models/pet.py new file mode 100644 index 00000000000..c44c38079ac --- /dev/null +++ b/samples/server/petstore/python-fastapi/src/openapi_server/models/pet.py @@ -0,0 +1,36 @@ +# coding: utf-8 + +from __future__ import annotations +from datetime import date, datetime # noqa: F401 + +import re # noqa: F401 +from typing import Any, Dict, List, Optional # noqa: F401 + +from pydantic import AnyUrl, BaseModel, EmailStr, validator # noqa: F401 +from openapi_server.models.category import Category +from openapi_server.models.tag import Tag + + +class Pet(BaseModel): + """NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + + Do not edit the class manually. + + Pet - a model defined in OpenAPI + + id: The id of this Pet [Optional]. + category: The category of this Pet [Optional]. + name: The name of this Pet. + photo_urls: The photo_urls of this Pet. + tags: The tags of this Pet [Optional]. + status: The status of this Pet [Optional]. + """ + + id: Optional[int] = None + category: Optional[Category] = None + name: str + photo_urls: List[str] + tags: Optional[List[Tag]] = None + status: Optional[str] = None + +Pet.update_forward_refs() diff --git a/samples/server/petstore/python-fastapi/src/openapi_server/models/tag.py b/samples/server/petstore/python-fastapi/src/openapi_server/models/tag.py new file mode 100644 index 00000000000..3e0b45cd787 --- /dev/null +++ b/samples/server/petstore/python-fastapi/src/openapi_server/models/tag.py @@ -0,0 +1,26 @@ +# coding: utf-8 + +from __future__ import annotations +from datetime import date, datetime # noqa: F401 + +import re # noqa: F401 +from typing import Any, Dict, List, Optional # noqa: F401 + +from pydantic import AnyUrl, BaseModel, EmailStr, validator # noqa: F401 + + +class Tag(BaseModel): + """NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + + Do not edit the class manually. + + Tag - a model defined in OpenAPI + + id: The id of this Tag [Optional]. + name: The name of this Tag [Optional]. + """ + + id: Optional[int] = None + name: Optional[str] = None + +Tag.update_forward_refs() diff --git a/samples/server/petstore/python-fastapi/src/openapi_server/models/user.py b/samples/server/petstore/python-fastapi/src/openapi_server/models/user.py new file mode 100644 index 00000000000..1c75b77dbfc --- /dev/null +++ b/samples/server/petstore/python-fastapi/src/openapi_server/models/user.py @@ -0,0 +1,38 @@ +# coding: utf-8 + +from __future__ import annotations +from datetime import date, datetime # noqa: F401 + +import re # noqa: F401 +from typing import Any, Dict, List, Optional # noqa: F401 + +from pydantic import AnyUrl, BaseModel, EmailStr, validator # noqa: F401 + + +class User(BaseModel): + """NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + + Do not edit the class manually. + + User - a model defined in OpenAPI + + id: The id of this User [Optional]. + username: The username of this User [Optional]. + first_name: The first_name of this User [Optional]. + last_name: The last_name of this User [Optional]. + email: The email of this User [Optional]. + password: The password of this User [Optional]. + phone: The phone of this User [Optional]. + user_status: The user_status of this User [Optional]. + """ + + id: Optional[int] = None + username: Optional[str] = None + first_name: Optional[str] = None + last_name: Optional[str] = None + email: Optional[str] = None + password: Optional[str] = None + phone: Optional[str] = None + user_status: Optional[int] = None + +User.update_forward_refs() diff --git a/samples/server/petstore/python-fastapi/src/openapi_server/security_api.py b/samples/server/petstore/python-fastapi/src/openapi_server/security_api.py new file mode 100644 index 00000000000..38eb60eb167 --- /dev/null +++ b/samples/server/petstore/python-fastapi/src/openapi_server/security_api.py @@ -0,0 +1,83 @@ +# coding: utf-8 + +from typing import List + +from fastapi import Depends, Security # noqa: F401 +from fastapi.openapi.models import OAuthFlowImplicit, OAuthFlows # noqa: F401 +from fastapi.security import ( # noqa: F401 + HTTPAuthorizationCredentials, + HTTPBasic, + HTTPBasicCredentials, + HTTPBearer, + OAuth2, + OAuth2AuthorizationCodeBearer, + OAuth2PasswordBearer, + SecurityScopes, +) +from fastapi.security.api_key import APIKeyCookie, APIKeyHeader, APIKeyQuery # noqa: F401 + +from openapi_server.models.extra_models import TokenModel + + +def get_token_api_key( + token_api_key_header: str = Security( + APIKeyHeader(name="api_key", auto_error=False) + ), +) -> TokenModel: + """ + Check and retrieve authentication information from api_key. + + :param token_api_key_header API key provided by Authorization[api_key] header + + + :type token_api_key_header: str + :return: Information attached to provided api_key or None if api_key is invalid or does not allow access to called API + :rtype: TokenModel | None + """ + + ... + +oauth2_implicit = OAuth2( + flows=OAuthFlows( + implicit=OAuthFlowImplicit( + authorizationUrl="http://petstore.swagger.io/api/oauth/dialog", + scopes={ + "write:pets": "modify pets in your account", + "read:pets": "read your pets", + } + ) + ) +) + + +def get_token_petstore_auth( + security_scopes: SecurityScopes, token: str = Depends(oauth2_implicit) +) -> TokenModel: + """ + Validate and decode token. + + :param token Token provided by Authorization header + :type token: str + :return: Decoded token information or None if token is invalid + :rtype: TokenModel | None + """ + + ... + + +def validate_scope_petstore_auth( + required_scopes: SecurityScopes, token_scopes: List[str] +) -> bool: + """ + 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 False + diff --git a/samples/server/petstore/python-fastapi/tests/conftest.py b/samples/server/petstore/python-fastapi/tests/conftest.py new file mode 100644 index 00000000000..cbde552c9c0 --- /dev/null +++ b/samples/server/petstore/python-fastapi/tests/conftest.py @@ -0,0 +1,17 @@ +import pytest +from fastapi import FastAPI +from fastapi.testclient import TestClient + +from openapi_server.main import app as application + + +@pytest.fixture +def app() -> FastAPI: + application.dependency_overrides = {} + + return application + + +@pytest.fixture +def client(app) -> TestClient: + return TestClient(app) diff --git a/samples/server/petstore/python-fastapi/tests/test_pet_api.py b/samples/server/petstore/python-fastapi/tests/test_pet_api.py new file mode 100644 index 00000000000..ec60e332ef1 --- /dev/null +++ b/samples/server/petstore/python-fastapi/tests/test_pet_api.py @@ -0,0 +1,177 @@ +# coding: utf-8 + +from fastapi.testclient import TestClient + + +from openapi_server.models.api_response import ApiResponse # noqa: F401 +from openapi_server.models.pet import Pet # noqa: F401 + + +def test_add_pet(client: TestClient): + """Test case for add_pet + + Add a new pet to the store + """ + pet = {"photo_urls":["photoUrls","photoUrls"],"name":"doggie","id":0,"category":{"name":"name","id":6},"tags":[{"name":"name","id":1},{"name":"name","id":1}],"status":"available"} + + headers = { + "Authorization": "Bearer special-key", + } + response = client.request( + "POST", + "/pet", + headers=headers, + json=pet, + ) + + # uncomment below to assert the status code of the HTTP response + #assert response.status_code == 200 + + +def test_delete_pet(client: TestClient): + """Test case for delete_pet + + Deletes a pet + """ + + headers = { + "api_key": 'api_key_example', + "Authorization": "Bearer special-key", + } + response = client.request( + "DELETE", + "/pet/{petId}".format(petId=56), + headers=headers, + ) + + # uncomment below to assert the status code of the HTTP response + #assert response.status_code == 200 + + +def test_find_pets_by_status(client: TestClient): + """Test case for find_pets_by_status + + Finds Pets by status + """ + params = [("status", ['status_example'])] + headers = { + "Authorization": "Bearer special-key", + } + response = client.request( + "GET", + "/pet/findByStatus", + headers=headers, + params=params, + ) + + # uncomment below to assert the status code of the HTTP response + #assert response.status_code == 200 + + +def test_find_pets_by_tags(client: TestClient): + """Test case for find_pets_by_tags + + Finds Pets by tags + """ + params = [("tags", ['tags_example'])] + headers = { + "Authorization": "Bearer special-key", + } + response = client.request( + "GET", + "/pet/findByTags", + headers=headers, + params=params, + ) + + # uncomment below to assert the status code of the HTTP response + #assert response.status_code == 200 + + +def test_get_pet_by_id(client: TestClient): + """Test case for get_pet_by_id + + Find pet by ID + """ + + headers = { + "api_key": "special-key", + } + response = client.request( + "GET", + "/pet/{petId}".format(petId=56), + headers=headers, + ) + + # uncomment below to assert the status code of the HTTP response + #assert response.status_code == 200 + + +def test_update_pet(client: TestClient): + """Test case for update_pet + + Update an existing pet + """ + pet = {"photo_urls":["photoUrls","photoUrls"],"name":"doggie","id":0,"category":{"name":"name","id":6},"tags":[{"name":"name","id":1},{"name":"name","id":1}],"status":"available"} + + headers = { + "Authorization": "Bearer special-key", + } + response = client.request( + "PUT", + "/pet", + headers=headers, + json=pet, + ) + + # uncomment below to assert the status code of the HTTP response + #assert response.status_code == 200 + + +def test_update_pet_with_form(client: TestClient): + """Test case for update_pet_with_form + + Updates a pet in the store with form data + """ + + headers = { + "Authorization": "Bearer special-key", + } + data = { + "name": 'name_example', + "status": 'status_example' + } + response = client.request( + "POST", + "/pet/{petId}".format(petId=56), + headers=headers, + data=data, + ) + + # uncomment below to assert the status code of the HTTP response + #assert response.status_code == 200 + + +def test_upload_file(client: TestClient): + """Test case for upload_file + + uploads an image + """ + + headers = { + "Authorization": "Bearer special-key", + } + data = { + "additional_metadata": 'additional_metadata_example', + "file": '/path/to/file' + } + response = client.request( + "POST", + "/pet/{petId}/uploadImage".format(petId=56), + headers=headers, + data=data, + ) + + # uncomment below to assert the status code of the HTTP response + #assert response.status_code == 200 + diff --git a/samples/server/petstore/python-fastapi/tests/test_store_api.py b/samples/server/petstore/python-fastapi/tests/test_store_api.py new file mode 100644 index 00000000000..4f41a35e1f4 --- /dev/null +++ b/samples/server/petstore/python-fastapi/tests/test_store_api.py @@ -0,0 +1,82 @@ +# coding: utf-8 + +from fastapi.testclient import TestClient + + +from openapi_server.models.order import Order # noqa: F401 + + +def test_delete_order(client: TestClient): + """Test case for delete_order + + Delete purchase order by ID + """ + + headers = { + } + response = client.request( + "DELETE", + "/store/order/{orderId}".format(orderId='order_id_example'), + headers=headers, + ) + + # uncomment below to assert the status code of the HTTP response + #assert response.status_code == 200 + + +def test_get_inventory(client: TestClient): + """Test case for get_inventory + + Returns pet inventories by status + """ + + headers = { + "api_key": "special-key", + } + response = client.request( + "GET", + "/store/inventory", + headers=headers, + ) + + # uncomment below to assert the status code of the HTTP response + #assert response.status_code == 200 + + +def test_get_order_by_id(client: TestClient): + """Test case for get_order_by_id + + Find purchase order by ID + """ + + headers = { + } + response = client.request( + "GET", + "/store/order/{orderId}".format(orderId=56), + headers=headers, + ) + + # uncomment below to assert the status code of the HTTP response + #assert response.status_code == 200 + + +def test_place_order(client: TestClient): + """Test case for place_order + + Place an order for a pet + """ + order = {"pet_id":6,"quantity":1,"id":0,"ship_date":"2000-01-23T04:56:07.000+00:00","complete":0,"status":"placed"} + + headers = { + } + response = client.request( + "POST", + "/store/order", + headers=headers, + json=order, + ) + + # uncomment below to assert the status code of the HTTP response + #assert response.status_code == 200 + diff --git a/samples/server/petstore/python-fastapi/tests/test_user_api.py b/samples/server/petstore/python-fastapi/tests/test_user_api.py new file mode 100644 index 00000000000..08c99c92bdb --- /dev/null +++ b/samples/server/petstore/python-fastapi/tests/test_user_api.py @@ -0,0 +1,166 @@ +# coding: utf-8 + +from fastapi.testclient import TestClient + + +from openapi_server.models.user import User # noqa: F401 + + +def test_create_user(client: TestClient): + """Test case for create_user + + Create user + """ + user = {"first_name":"firstName","last_name":"lastName","password":"password","user_status":6,"phone":"phone","id":0,"email":"email","username":"username"} + + headers = { + "api_key": "special-key", + } + response = client.request( + "POST", + "/user", + headers=headers, + json=user, + ) + + # uncomment below to assert the status code of the HTTP response + #assert response.status_code == 200 + + +def test_create_users_with_array_input(client: TestClient): + """Test case for create_users_with_array_input + + Creates list of users with given input array + """ + user = [{"first_name":"firstName","last_name":"lastName","password":"password","user_status":6,"phone":"phone","id":0,"email":"email","username":"username"}] + + headers = { + "api_key": "special-key", + } + response = client.request( + "POST", + "/user/createWithArray", + headers=headers, + json=user, + ) + + # uncomment below to assert the status code of the HTTP response + #assert response.status_code == 200 + + +def test_create_users_with_list_input(client: TestClient): + """Test case for create_users_with_list_input + + Creates list of users with given input array + """ + user = [{"first_name":"firstName","last_name":"lastName","password":"password","user_status":6,"phone":"phone","id":0,"email":"email","username":"username"}] + + headers = { + "api_key": "special-key", + } + response = client.request( + "POST", + "/user/createWithList", + headers=headers, + json=user, + ) + + # uncomment below to assert the status code of the HTTP response + #assert response.status_code == 200 + + +def test_delete_user(client: TestClient): + """Test case for delete_user + + Delete user + """ + + headers = { + "api_key": "special-key", + } + response = client.request( + "DELETE", + "/user/{username}".format(username='username_example'), + headers=headers, + ) + + # uncomment below to assert the status code of the HTTP response + #assert response.status_code == 200 + + +def test_get_user_by_name(client: TestClient): + """Test case for get_user_by_name + + Get user by user name + """ + + headers = { + } + response = client.request( + "GET", + "/user/{username}".format(username='username_example'), + headers=headers, + ) + + # uncomment below to assert the status code of the HTTP response + #assert response.status_code == 200 + + +def test_login_user(client: TestClient): + """Test case for login_user + + Logs user into the system + """ + params = [("username", 'username_example'), ("password", 'password_example')] + headers = { + } + response = client.request( + "GET", + "/user/login", + headers=headers, + params=params, + ) + + # uncomment below to assert the status code of the HTTP response + #assert response.status_code == 200 + + +def test_logout_user(client: TestClient): + """Test case for logout_user + + Logs out current logged in user session + """ + + headers = { + "api_key": "special-key", + } + response = client.request( + "GET", + "/user/logout", + headers=headers, + ) + + # uncomment below to assert the status code of the HTTP response + #assert response.status_code == 200 + + +def test_update_user(client: TestClient): + """Test case for update_user + + Updated user + """ + user = {"first_name":"firstName","last_name":"lastName","password":"password","user_status":6,"phone":"phone","id":0,"email":"email","username":"username"} + + headers = { + "api_key": "special-key", + } + response = client.request( + "PUT", + "/user/{username}".format(username='username_example'), + headers=headers, + json=user, + ) + + # uncomment below to assert the status code of the HTTP response + #assert response.status_code == 200 + diff --git a/samples/server/petstore/python-flask/.openapi-generator/VERSION b/samples/server/petstore/python-flask/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/server/petstore/python-flask/.openapi-generator/VERSION +++ b/samples/server/petstore/python-flask/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x 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 5f68295fc19..e8415097f3a 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,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x 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 5f68295fc19..e8415097f3a 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,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x 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 5f68295fc19..e8415097f3a 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,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x 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 5f68295fc19..e8415097f3a 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,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x 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 5f68295fc19..e8415097f3a 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,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x 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 5f68295fc19..e8415097f3a 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,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x 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 5f68295fc19..e8415097f3a 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,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/server/petstore/spring-mvc-default-value/.openapi-generator/VERSION b/samples/server/petstore/spring-mvc-default-value/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/server/petstore/spring-mvc-default-value/.openapi-generator/VERSION +++ b/samples/server/petstore/spring-mvc-default-value/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/server/petstore/spring-mvc-default-value/src/main/java/org/openapitools/api/TestHeadersApi.java b/samples/server/petstore/spring-mvc-default-value/src/main/java/org/openapitools/api/TestHeadersApi.java index 85e2db8065b..e81001ded17 100644 --- a/samples/server/petstore/spring-mvc-default-value/src/main/java/org/openapitools/api/TestHeadersApi.java +++ b/samples/server/petstore/spring-mvc-default-value/src/main/java/org/openapitools/api/TestHeadersApi.java @@ -1,5 +1,9 @@ /** +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (6.0.0-SNAPSHOT). +======= + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.3.0-SNAPSHOT). +>>>>>>> origin/5.3.x * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/spring-mvc-default-value/src/main/java/org/openapitools/api/TestQueryParamsApi.java b/samples/server/petstore/spring-mvc-default-value/src/main/java/org/openapitools/api/TestQueryParamsApi.java index 8bb61fd16e1..5a11043a6ae 100644 --- a/samples/server/petstore/spring-mvc-default-value/src/main/java/org/openapitools/api/TestQueryParamsApi.java +++ b/samples/server/petstore/spring-mvc-default-value/src/main/java/org/openapitools/api/TestQueryParamsApi.java @@ -1,5 +1,9 @@ /** +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (6.0.0-SNAPSHOT). +======= + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.3.0-SNAPSHOT). +>>>>>>> origin/5.3.x * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/spring-mvc-j8-async/.openapi-generator/VERSION b/samples/server/petstore/spring-mvc-j8-async/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/server/petstore/spring-mvc-j8-async/.openapi-generator/VERSION +++ b/samples/server/petstore/spring-mvc-j8-async/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/org/openapitools/api/AnotherFakeApi.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/org/openapitools/api/AnotherFakeApi.java index aec668984f0..96322995115 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/org/openapitools/api/AnotherFakeApi.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/org/openapitools/api/AnotherFakeApi.java @@ -1,5 +1,9 @@ /** +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (6.0.0-SNAPSHOT). +======= + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.3.0-SNAPSHOT). +>>>>>>> origin/5.3.x * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/org/openapitools/api/FakeApi.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/org/openapitools/api/FakeApi.java index a22c4668657..69fd1de78b5 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/org/openapitools/api/FakeApi.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/org/openapitools/api/FakeApi.java @@ -1,5 +1,9 @@ /** +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (6.0.0-SNAPSHOT). +======= + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.3.0-SNAPSHOT). +>>>>>>> origin/5.3.x * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/org/openapitools/api/FakeClassnameTestApi.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/org/openapitools/api/FakeClassnameTestApi.java index 1f859ad0744..a7d623dfc06 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/org/openapitools/api/FakeClassnameTestApi.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/org/openapitools/api/FakeClassnameTestApi.java @@ -1,5 +1,9 @@ /** +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (6.0.0-SNAPSHOT). +======= + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.3.0-SNAPSHOT). +>>>>>>> origin/5.3.x * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/org/openapitools/api/PetApi.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/org/openapitools/api/PetApi.java index dab68aed8b1..87c2bf62e1a 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/org/openapitools/api/PetApi.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/org/openapitools/api/PetApi.java @@ -1,5 +1,9 @@ /** +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (6.0.0-SNAPSHOT). +======= + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.3.0-SNAPSHOT). +>>>>>>> origin/5.3.x * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/org/openapitools/api/StoreApi.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/org/openapitools/api/StoreApi.java index 126b9e38c23..d68594abde2 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/org/openapitools/api/StoreApi.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/org/openapitools/api/StoreApi.java @@ -1,5 +1,9 @@ /** +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (6.0.0-SNAPSHOT). +======= + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.3.0-SNAPSHOT). +>>>>>>> origin/5.3.x * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/org/openapitools/api/UserApi.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/org/openapitools/api/UserApi.java index b54f4d06195..bedad994840 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/org/openapitools/api/UserApi.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/org/openapitools/api/UserApi.java @@ -1,5 +1,9 @@ /** +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (6.0.0-SNAPSHOT). +======= + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.3.0-SNAPSHOT). +>>>>>>> origin/5.3.x * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/org/openapitools/model/FormatTest.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/org/openapitools/model/FormatTest.java index 72f64c2b370..e894f561fc6 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/org/openapitools/model/FormatTest.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/org/openapitools/model/FormatTest.java @@ -44,7 +44,7 @@ public class FormatTest { private byte[] _byte; @JsonProperty("binary") - private org.springframework.web.multipart.MultipartFile binary; + private org.springframework.core.io.Resource binary; @JsonProperty("date") @org.springframework.format.annotation.DateTimeFormat(iso = org.springframework.format.annotation.DateTimeFormat.ISO.DATE) @@ -236,7 +236,7 @@ public class FormatTest { this._byte = _byte; } - public FormatTest binary(org.springframework.web.multipart.MultipartFile binary) { + public FormatTest binary(org.springframework.core.io.Resource binary) { this.binary = binary; return this; } @@ -249,11 +249,11 @@ public class FormatTest { @Valid - public org.springframework.web.multipart.MultipartFile getBinary() { + public org.springframework.core.io.Resource getBinary() { return binary; } - public void setBinary(org.springframework.web.multipart.MultipartFile binary) { + public void setBinary(org.springframework.core.io.Resource binary) { this.binary = binary; } diff --git a/samples/server/petstore/spring-mvc-j8-localdatetime/.openapi-generator/VERSION b/samples/server/petstore/spring-mvc-j8-localdatetime/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/server/petstore/spring-mvc-j8-localdatetime/.openapi-generator/VERSION +++ b/samples/server/petstore/spring-mvc-j8-localdatetime/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/server/petstore/spring-mvc-j8-localdatetime/src/main/java/org/openapitools/api/AnotherFakeApi.java b/samples/server/petstore/spring-mvc-j8-localdatetime/src/main/java/org/openapitools/api/AnotherFakeApi.java index 67df1501f09..3ee84f0dcc3 100644 --- a/samples/server/petstore/spring-mvc-j8-localdatetime/src/main/java/org/openapitools/api/AnotherFakeApi.java +++ b/samples/server/petstore/spring-mvc-j8-localdatetime/src/main/java/org/openapitools/api/AnotherFakeApi.java @@ -1,5 +1,9 @@ /** +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (6.0.0-SNAPSHOT). +======= + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.3.0-SNAPSHOT). +>>>>>>> origin/5.3.x * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/spring-mvc-j8-localdatetime/src/main/java/org/openapitools/api/FakeApi.java b/samples/server/petstore/spring-mvc-j8-localdatetime/src/main/java/org/openapitools/api/FakeApi.java index efc20852e16..b37b2a56ce8 100644 --- a/samples/server/petstore/spring-mvc-j8-localdatetime/src/main/java/org/openapitools/api/FakeApi.java +++ b/samples/server/petstore/spring-mvc-j8-localdatetime/src/main/java/org/openapitools/api/FakeApi.java @@ -1,5 +1,9 @@ /** +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (6.0.0-SNAPSHOT). +======= + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.3.0-SNAPSHOT). +>>>>>>> origin/5.3.x * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/spring-mvc-j8-localdatetime/src/main/java/org/openapitools/api/FakeClassnameTestApi.java b/samples/server/petstore/spring-mvc-j8-localdatetime/src/main/java/org/openapitools/api/FakeClassnameTestApi.java index 7adfddb01e7..f4bbfdc593a 100644 --- a/samples/server/petstore/spring-mvc-j8-localdatetime/src/main/java/org/openapitools/api/FakeClassnameTestApi.java +++ b/samples/server/petstore/spring-mvc-j8-localdatetime/src/main/java/org/openapitools/api/FakeClassnameTestApi.java @@ -1,5 +1,9 @@ /** +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (6.0.0-SNAPSHOT). +======= + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.3.0-SNAPSHOT). +>>>>>>> origin/5.3.x * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/spring-mvc-j8-localdatetime/src/main/java/org/openapitools/api/PetApi.java b/samples/server/petstore/spring-mvc-j8-localdatetime/src/main/java/org/openapitools/api/PetApi.java index f4f5c97755f..90b15210bc8 100644 --- a/samples/server/petstore/spring-mvc-j8-localdatetime/src/main/java/org/openapitools/api/PetApi.java +++ b/samples/server/petstore/spring-mvc-j8-localdatetime/src/main/java/org/openapitools/api/PetApi.java @@ -1,5 +1,9 @@ /** +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (6.0.0-SNAPSHOT). +======= + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.3.0-SNAPSHOT). +>>>>>>> origin/5.3.x * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/spring-mvc-j8-localdatetime/src/main/java/org/openapitools/api/StoreApi.java b/samples/server/petstore/spring-mvc-j8-localdatetime/src/main/java/org/openapitools/api/StoreApi.java index a12dc1250c2..c3534db4fe8 100644 --- a/samples/server/petstore/spring-mvc-j8-localdatetime/src/main/java/org/openapitools/api/StoreApi.java +++ b/samples/server/petstore/spring-mvc-j8-localdatetime/src/main/java/org/openapitools/api/StoreApi.java @@ -1,5 +1,9 @@ /** +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (6.0.0-SNAPSHOT). +======= + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.3.0-SNAPSHOT). +>>>>>>> origin/5.3.x * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/spring-mvc-j8-localdatetime/src/main/java/org/openapitools/api/UserApi.java b/samples/server/petstore/spring-mvc-j8-localdatetime/src/main/java/org/openapitools/api/UserApi.java index da836caf4bf..c231313c77f 100644 --- a/samples/server/petstore/spring-mvc-j8-localdatetime/src/main/java/org/openapitools/api/UserApi.java +++ b/samples/server/petstore/spring-mvc-j8-localdatetime/src/main/java/org/openapitools/api/UserApi.java @@ -1,5 +1,9 @@ /** +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (6.0.0-SNAPSHOT). +======= + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.3.0-SNAPSHOT). +>>>>>>> origin/5.3.x * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/spring-mvc-j8-localdatetime/src/main/java/org/openapitools/model/FormatTest.java b/samples/server/petstore/spring-mvc-j8-localdatetime/src/main/java/org/openapitools/model/FormatTest.java index 9efca6d654b..04e164b1c52 100644 --- a/samples/server/petstore/spring-mvc-j8-localdatetime/src/main/java/org/openapitools/model/FormatTest.java +++ b/samples/server/petstore/spring-mvc-j8-localdatetime/src/main/java/org/openapitools/model/FormatTest.java @@ -44,7 +44,7 @@ public class FormatTest { private byte[] _byte; @JsonProperty("binary") - private org.springframework.web.multipart.MultipartFile binary; + private org.springframework.core.io.Resource binary; @JsonProperty("date") @org.springframework.format.annotation.DateTimeFormat(iso = org.springframework.format.annotation.DateTimeFormat.ISO.DATE) @@ -236,7 +236,7 @@ public class FormatTest { this._byte = _byte; } - public FormatTest binary(org.springframework.web.multipart.MultipartFile binary) { + public FormatTest binary(org.springframework.core.io.Resource binary) { this.binary = binary; return this; } @@ -249,11 +249,11 @@ public class FormatTest { @Valid - public org.springframework.web.multipart.MultipartFile getBinary() { + public org.springframework.core.io.Resource getBinary() { return binary; } - public void setBinary(org.springframework.web.multipart.MultipartFile binary) { + public void setBinary(org.springframework.core.io.Resource binary) { this.binary = binary; } diff --git a/samples/server/petstore/spring-mvc-no-nullable/.openapi-generator/VERSION b/samples/server/petstore/spring-mvc-no-nullable/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/server/petstore/spring-mvc-no-nullable/.openapi-generator/VERSION +++ b/samples/server/petstore/spring-mvc-no-nullable/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/server/petstore/spring-mvc-no-nullable/src/main/java/org/openapitools/api/AnotherFakeApi.java b/samples/server/petstore/spring-mvc-no-nullable/src/main/java/org/openapitools/api/AnotherFakeApi.java index 67df1501f09..3ee84f0dcc3 100644 --- a/samples/server/petstore/spring-mvc-no-nullable/src/main/java/org/openapitools/api/AnotherFakeApi.java +++ b/samples/server/petstore/spring-mvc-no-nullable/src/main/java/org/openapitools/api/AnotherFakeApi.java @@ -1,5 +1,9 @@ /** +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (6.0.0-SNAPSHOT). +======= + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.3.0-SNAPSHOT). +>>>>>>> origin/5.3.x * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/spring-mvc-no-nullable/src/main/java/org/openapitools/api/FakeApi.java b/samples/server/petstore/spring-mvc-no-nullable/src/main/java/org/openapitools/api/FakeApi.java index 4227fb26a50..fa4d1f4009b 100644 --- a/samples/server/petstore/spring-mvc-no-nullable/src/main/java/org/openapitools/api/FakeApi.java +++ b/samples/server/petstore/spring-mvc-no-nullable/src/main/java/org/openapitools/api/FakeApi.java @@ -1,5 +1,9 @@ /** +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (6.0.0-SNAPSHOT). +======= + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.3.0-SNAPSHOT). +>>>>>>> origin/5.3.x * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/spring-mvc-no-nullable/src/main/java/org/openapitools/api/FakeClassnameTestApi.java b/samples/server/petstore/spring-mvc-no-nullable/src/main/java/org/openapitools/api/FakeClassnameTestApi.java index 7adfddb01e7..f4bbfdc593a 100644 --- a/samples/server/petstore/spring-mvc-no-nullable/src/main/java/org/openapitools/api/FakeClassnameTestApi.java +++ b/samples/server/petstore/spring-mvc-no-nullable/src/main/java/org/openapitools/api/FakeClassnameTestApi.java @@ -1,5 +1,9 @@ /** +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (6.0.0-SNAPSHOT). +======= + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.3.0-SNAPSHOT). +>>>>>>> origin/5.3.x * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/spring-mvc-no-nullable/src/main/java/org/openapitools/api/PetApi.java b/samples/server/petstore/spring-mvc-no-nullable/src/main/java/org/openapitools/api/PetApi.java index f4f5c97755f..90b15210bc8 100644 --- a/samples/server/petstore/spring-mvc-no-nullable/src/main/java/org/openapitools/api/PetApi.java +++ b/samples/server/petstore/spring-mvc-no-nullable/src/main/java/org/openapitools/api/PetApi.java @@ -1,5 +1,9 @@ /** +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (6.0.0-SNAPSHOT). +======= + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.3.0-SNAPSHOT). +>>>>>>> origin/5.3.x * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/spring-mvc-no-nullable/src/main/java/org/openapitools/api/StoreApi.java b/samples/server/petstore/spring-mvc-no-nullable/src/main/java/org/openapitools/api/StoreApi.java index a12dc1250c2..c3534db4fe8 100644 --- a/samples/server/petstore/spring-mvc-no-nullable/src/main/java/org/openapitools/api/StoreApi.java +++ b/samples/server/petstore/spring-mvc-no-nullable/src/main/java/org/openapitools/api/StoreApi.java @@ -1,5 +1,9 @@ /** +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (6.0.0-SNAPSHOT). +======= + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.3.0-SNAPSHOT). +>>>>>>> origin/5.3.x * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/spring-mvc-no-nullable/src/main/java/org/openapitools/api/UserApi.java b/samples/server/petstore/spring-mvc-no-nullable/src/main/java/org/openapitools/api/UserApi.java index da836caf4bf..c231313c77f 100644 --- a/samples/server/petstore/spring-mvc-no-nullable/src/main/java/org/openapitools/api/UserApi.java +++ b/samples/server/petstore/spring-mvc-no-nullable/src/main/java/org/openapitools/api/UserApi.java @@ -1,5 +1,9 @@ /** +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (6.0.0-SNAPSHOT). +======= + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.3.0-SNAPSHOT). +>>>>>>> origin/5.3.x * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/spring-mvc-no-nullable/src/main/java/org/openapitools/model/FormatTest.java b/samples/server/petstore/spring-mvc-no-nullable/src/main/java/org/openapitools/model/FormatTest.java index 06978db9b9e..0962957d79f 100644 --- a/samples/server/petstore/spring-mvc-no-nullable/src/main/java/org/openapitools/model/FormatTest.java +++ b/samples/server/petstore/spring-mvc-no-nullable/src/main/java/org/openapitools/model/FormatTest.java @@ -43,7 +43,7 @@ public class FormatTest { private byte[] _byte; @JsonProperty("binary") - private org.springframework.web.multipart.MultipartFile binary; + private org.springframework.core.io.Resource binary; @JsonProperty("date") @org.springframework.format.annotation.DateTimeFormat(iso = org.springframework.format.annotation.DateTimeFormat.ISO.DATE) @@ -235,7 +235,7 @@ public class FormatTest { this._byte = _byte; } - public FormatTest binary(org.springframework.web.multipart.MultipartFile binary) { + public FormatTest binary(org.springframework.core.io.Resource binary) { this.binary = binary; return this; } @@ -248,11 +248,11 @@ public class FormatTest { @Valid - public org.springframework.web.multipart.MultipartFile getBinary() { + public org.springframework.core.io.Resource getBinary() { return binary; } - public void setBinary(org.springframework.web.multipart.MultipartFile binary) { + public void setBinary(org.springframework.core.io.Resource binary) { this.binary = binary; } diff --git a/samples/server/petstore/spring-mvc-spring-pageable/.openapi-generator/VERSION b/samples/server/petstore/spring-mvc-spring-pageable/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/server/petstore/spring-mvc-spring-pageable/.openapi-generator/VERSION +++ b/samples/server/petstore/spring-mvc-spring-pageable/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/server/petstore/spring-mvc-spring-pageable/src/main/java/org/openapitools/api/AnotherFakeApi.java b/samples/server/petstore/spring-mvc-spring-pageable/src/main/java/org/openapitools/api/AnotherFakeApi.java index 67df1501f09..3ee84f0dcc3 100644 --- a/samples/server/petstore/spring-mvc-spring-pageable/src/main/java/org/openapitools/api/AnotherFakeApi.java +++ b/samples/server/petstore/spring-mvc-spring-pageable/src/main/java/org/openapitools/api/AnotherFakeApi.java @@ -1,5 +1,9 @@ /** +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (6.0.0-SNAPSHOT). +======= + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.3.0-SNAPSHOT). +>>>>>>> origin/5.3.x * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/spring-mvc-spring-pageable/src/main/java/org/openapitools/api/FakeApi.java b/samples/server/petstore/spring-mvc-spring-pageable/src/main/java/org/openapitools/api/FakeApi.java index cdf16fc14a7..25b8b894ed0 100644 --- a/samples/server/petstore/spring-mvc-spring-pageable/src/main/java/org/openapitools/api/FakeApi.java +++ b/samples/server/petstore/spring-mvc-spring-pageable/src/main/java/org/openapitools/api/FakeApi.java @@ -1,5 +1,9 @@ /** +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (6.0.0-SNAPSHOT). +======= + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.3.0-SNAPSHOT). +>>>>>>> origin/5.3.x * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/spring-mvc-spring-pageable/src/main/java/org/openapitools/api/FakeClassnameTestApi.java b/samples/server/petstore/spring-mvc-spring-pageable/src/main/java/org/openapitools/api/FakeClassnameTestApi.java index 7adfddb01e7..f4bbfdc593a 100644 --- a/samples/server/petstore/spring-mvc-spring-pageable/src/main/java/org/openapitools/api/FakeClassnameTestApi.java +++ b/samples/server/petstore/spring-mvc-spring-pageable/src/main/java/org/openapitools/api/FakeClassnameTestApi.java @@ -1,5 +1,9 @@ /** +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (6.0.0-SNAPSHOT). +======= + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.3.0-SNAPSHOT). +>>>>>>> origin/5.3.x * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/spring-mvc-spring-pageable/src/main/java/org/openapitools/api/PetApi.java b/samples/server/petstore/spring-mvc-spring-pageable/src/main/java/org/openapitools/api/PetApi.java index c4f0ea452d1..99609959e7a 100644 --- a/samples/server/petstore/spring-mvc-spring-pageable/src/main/java/org/openapitools/api/PetApi.java +++ b/samples/server/petstore/spring-mvc-spring-pageable/src/main/java/org/openapitools/api/PetApi.java @@ -1,5 +1,9 @@ /** +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (6.0.0-SNAPSHOT). +======= + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.3.0-SNAPSHOT). +>>>>>>> origin/5.3.x * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/spring-mvc-spring-pageable/src/main/java/org/openapitools/api/StoreApi.java b/samples/server/petstore/spring-mvc-spring-pageable/src/main/java/org/openapitools/api/StoreApi.java index a12dc1250c2..c3534db4fe8 100644 --- a/samples/server/petstore/spring-mvc-spring-pageable/src/main/java/org/openapitools/api/StoreApi.java +++ b/samples/server/petstore/spring-mvc-spring-pageable/src/main/java/org/openapitools/api/StoreApi.java @@ -1,5 +1,9 @@ /** +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (6.0.0-SNAPSHOT). +======= + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.3.0-SNAPSHOT). +>>>>>>> origin/5.3.x * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/spring-mvc-spring-pageable/src/main/java/org/openapitools/api/UserApi.java b/samples/server/petstore/spring-mvc-spring-pageable/src/main/java/org/openapitools/api/UserApi.java index da836caf4bf..c231313c77f 100644 --- a/samples/server/petstore/spring-mvc-spring-pageable/src/main/java/org/openapitools/api/UserApi.java +++ b/samples/server/petstore/spring-mvc-spring-pageable/src/main/java/org/openapitools/api/UserApi.java @@ -1,5 +1,9 @@ /** +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (6.0.0-SNAPSHOT). +======= + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.3.0-SNAPSHOT). +>>>>>>> origin/5.3.x * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/spring-mvc-spring-pageable/src/main/java/org/openapitools/model/FormatTest.java b/samples/server/petstore/spring-mvc-spring-pageable/src/main/java/org/openapitools/model/FormatTest.java index 72f64c2b370..e894f561fc6 100644 --- a/samples/server/petstore/spring-mvc-spring-pageable/src/main/java/org/openapitools/model/FormatTest.java +++ b/samples/server/petstore/spring-mvc-spring-pageable/src/main/java/org/openapitools/model/FormatTest.java @@ -44,7 +44,7 @@ public class FormatTest { private byte[] _byte; @JsonProperty("binary") - private org.springframework.web.multipart.MultipartFile binary; + private org.springframework.core.io.Resource binary; @JsonProperty("date") @org.springframework.format.annotation.DateTimeFormat(iso = org.springframework.format.annotation.DateTimeFormat.ISO.DATE) @@ -236,7 +236,7 @@ public class FormatTest { this._byte = _byte; } - public FormatTest binary(org.springframework.web.multipart.MultipartFile binary) { + public FormatTest binary(org.springframework.core.io.Resource binary) { this.binary = binary; return this; } @@ -249,11 +249,11 @@ public class FormatTest { @Valid - public org.springframework.web.multipart.MultipartFile getBinary() { + public org.springframework.core.io.Resource getBinary() { return binary; } - public void setBinary(org.springframework.web.multipart.MultipartFile binary) { + public void setBinary(org.springframework.core.io.Resource binary) { this.binary = binary; } diff --git a/samples/server/petstore/spring-mvc/.openapi-generator/VERSION b/samples/server/petstore/spring-mvc/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/server/petstore/spring-mvc/.openapi-generator/VERSION +++ b/samples/server/petstore/spring-mvc/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/api/AnotherFakeApi.java b/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/api/AnotherFakeApi.java index 67df1501f09..3ee84f0dcc3 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/api/AnotherFakeApi.java +++ b/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/api/AnotherFakeApi.java @@ -1,5 +1,9 @@ /** +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (6.0.0-SNAPSHOT). +======= + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.3.0-SNAPSHOT). +>>>>>>> origin/5.3.x * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/api/FakeApi.java b/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/api/FakeApi.java index 4227fb26a50..fa4d1f4009b 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/api/FakeApi.java +++ b/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/api/FakeApi.java @@ -1,5 +1,9 @@ /** +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (6.0.0-SNAPSHOT). +======= + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.3.0-SNAPSHOT). +>>>>>>> origin/5.3.x * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/api/FakeClassnameTestApi.java b/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/api/FakeClassnameTestApi.java index 7adfddb01e7..f4bbfdc593a 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/api/FakeClassnameTestApi.java +++ b/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/api/FakeClassnameTestApi.java @@ -1,5 +1,9 @@ /** +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (6.0.0-SNAPSHOT). +======= + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.3.0-SNAPSHOT). +>>>>>>> origin/5.3.x * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/api/PetApi.java b/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/api/PetApi.java index f4f5c97755f..90b15210bc8 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/api/PetApi.java +++ b/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/api/PetApi.java @@ -1,5 +1,9 @@ /** +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (6.0.0-SNAPSHOT). +======= + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.3.0-SNAPSHOT). +>>>>>>> origin/5.3.x * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/api/StoreApi.java b/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/api/StoreApi.java index a12dc1250c2..c3534db4fe8 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/api/StoreApi.java +++ b/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/api/StoreApi.java @@ -1,5 +1,9 @@ /** +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (6.0.0-SNAPSHOT). +======= + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.3.0-SNAPSHOT). +>>>>>>> origin/5.3.x * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/api/UserApi.java b/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/api/UserApi.java index da836caf4bf..c231313c77f 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/api/UserApi.java +++ b/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/api/UserApi.java @@ -1,5 +1,9 @@ /** +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (6.0.0-SNAPSHOT). +======= + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.3.0-SNAPSHOT). +>>>>>>> origin/5.3.x * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/model/FormatTest.java b/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/model/FormatTest.java index 2a1722c3190..80ea59cef11 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/model/FormatTest.java +++ b/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/model/FormatTest.java @@ -46,7 +46,7 @@ public class FormatTest { private byte[] _byte; @JsonProperty("binary") - private org.springframework.web.multipart.MultipartFile binary; + private org.springframework.core.io.Resource binary; @JsonProperty("date") @org.springframework.format.annotation.DateTimeFormat(iso = org.springframework.format.annotation.DateTimeFormat.ISO.DATE) @@ -238,7 +238,7 @@ public class FormatTest { this._byte = _byte; } - public FormatTest binary(org.springframework.web.multipart.MultipartFile binary) { + public FormatTest binary(org.springframework.core.io.Resource binary) { this.binary = binary; return this; } @@ -251,11 +251,11 @@ public class FormatTest { @Valid - public org.springframework.web.multipart.MultipartFile getBinary() { + public org.springframework.core.io.Resource getBinary() { return binary; } - public void setBinary(org.springframework.web.multipart.MultipartFile binary) { + public void setBinary(org.springframework.core.io.Resource binary) { this.binary = binary; } 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 5f68295fc19..e8415097f3a 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,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x 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 9e8eda9066f..6c2e7b60bdd 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,9 @@ /** +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (6.0.0-SNAPSHOT). +======= + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.3.0-SNAPSHOT). +>>>>>>> origin/5.3.x * 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 d9119ee3ba4..b9ec57fc660 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,9 @@ /** +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (6.0.0-SNAPSHOT). +======= + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.3.0-SNAPSHOT). +>>>>>>> origin/5.3.x * 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 980ac9450f3..780881750bc 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,9 @@ /** +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (6.0.0-SNAPSHOT). +======= + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.3.0-SNAPSHOT). +>>>>>>> origin/5.3.x * 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 c4dcefbba25..e4df95143d9 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,9 @@ /** +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (6.0.0-SNAPSHOT). +======= + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.3.0-SNAPSHOT). +>>>>>>> origin/5.3.x * 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 afad5769803..a550834adb8 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,9 @@ /** +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (6.0.0-SNAPSHOT). +======= + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.3.0-SNAPSHOT). +>>>>>>> origin/5.3.x * 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 20446a44497..74963cebcf6 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,9 @@ /** +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (6.0.0-SNAPSHOT). +======= + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.3.0-SNAPSHOT). +>>>>>>> origin/5.3.x * 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/model/FormatTest.java b/samples/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/model/FormatTest.java index 99f755655a9..60247deff4c 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 @@ -43,7 +43,7 @@ public class FormatTest { private byte[] _byte; @JsonProperty("binary") - private org.springframework.web.multipart.MultipartFile binary; + private org.springframework.core.io.Resource binary; @JsonProperty("date") @org.springframework.format.annotation.DateTimeFormat(iso = org.springframework.format.annotation.DateTimeFormat.ISO.DATE) @@ -235,7 +235,7 @@ public class FormatTest { this._byte = _byte; } - public FormatTest binary(org.springframework.web.multipart.MultipartFile binary) { + public FormatTest binary(org.springframework.core.io.Resource binary) { this.binary = binary; return this; } @@ -248,11 +248,11 @@ public class FormatTest { @Valid - public org.springframework.web.multipart.MultipartFile getBinary() { + public org.springframework.core.io.Resource getBinary() { return binary; } - public void setBinary(org.springframework.web.multipart.MultipartFile binary) { + public void setBinary(org.springframework.core.io.Resource binary) { this.binary = binary; } diff --git a/samples/server/petstore/springboot-beanvalidation/.openapi-generator/VERSION b/samples/server/petstore/springboot-beanvalidation/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/server/petstore/springboot-beanvalidation/.openapi-generator/VERSION +++ b/samples/server/petstore/springboot-beanvalidation/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x 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 67df1501f09..3ee84f0dcc3 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,9 @@ /** +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (6.0.0-SNAPSHOT). +======= + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.3.0-SNAPSHOT). +>>>>>>> origin/5.3.x * 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 4227fb26a50..fa4d1f4009b 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,9 @@ /** +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (6.0.0-SNAPSHOT). +======= + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.3.0-SNAPSHOT). +>>>>>>> origin/5.3.x * 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 7adfddb01e7..f4bbfdc593a 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,9 @@ /** +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (6.0.0-SNAPSHOT). +======= + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.3.0-SNAPSHOT). +>>>>>>> origin/5.3.x * 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 f4f5c97755f..90b15210bc8 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,9 @@ /** +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (6.0.0-SNAPSHOT). +======= + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.3.0-SNAPSHOT). +>>>>>>> origin/5.3.x * 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 a12dc1250c2..c3534db4fe8 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,9 @@ /** +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (6.0.0-SNAPSHOT). +======= + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.3.0-SNAPSHOT). +>>>>>>> origin/5.3.x * 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 da836caf4bf..c231313c77f 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,9 @@ /** +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (6.0.0-SNAPSHOT). +======= + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.3.0-SNAPSHOT). +>>>>>>> origin/5.3.x * https://openapi-generator.tech * Do not edit the class manually. */ 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 72f64c2b370..e894f561fc6 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 @@ -44,7 +44,7 @@ public class FormatTest { private byte[] _byte; @JsonProperty("binary") - private org.springframework.web.multipart.MultipartFile binary; + private org.springframework.core.io.Resource binary; @JsonProperty("date") @org.springframework.format.annotation.DateTimeFormat(iso = org.springframework.format.annotation.DateTimeFormat.ISO.DATE) @@ -236,7 +236,7 @@ public class FormatTest { this._byte = _byte; } - public FormatTest binary(org.springframework.web.multipart.MultipartFile binary) { + public FormatTest binary(org.springframework.core.io.Resource binary) { this.binary = binary; return this; } @@ -249,11 +249,11 @@ public class FormatTest { @Valid - public org.springframework.web.multipart.MultipartFile getBinary() { + public org.springframework.core.io.Resource getBinary() { return binary; } - public void setBinary(org.springframework.web.multipart.MultipartFile binary) { + public void setBinary(org.springframework.core.io.Resource binary) { this.binary = binary; } diff --git a/samples/server/petstore/springboot-delegate-j8/.openapi-generator/VERSION b/samples/server/petstore/springboot-delegate-j8/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/server/petstore/springboot-delegate-j8/.openapi-generator/VERSION +++ b/samples/server/petstore/springboot-delegate-j8/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x 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 c95e8d5ae7a..6d74f1f2928 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,9 @@ /** +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (6.0.0-SNAPSHOT). +======= + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.3.0-SNAPSHOT). +>>>>>>> origin/5.3.x * 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 19a5ac37fbf..f5fe4e2947d 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,9 @@ /** +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (6.0.0-SNAPSHOT). +======= + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.3.0-SNAPSHOT). +>>>>>>> origin/5.3.x * 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 30fb4866522..6fc8b7f87ba 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,9 @@ /** +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (6.0.0-SNAPSHOT). +======= + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.3.0-SNAPSHOT). +>>>>>>> origin/5.3.x * 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 74eea454d7f..33df790a66a 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,9 @@ /** +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (6.0.0-SNAPSHOT). +======= + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.3.0-SNAPSHOT). +>>>>>>> origin/5.3.x * 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 cf465fac207..71184e1fbab 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,9 @@ /** +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (6.0.0-SNAPSHOT). +======= + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.3.0-SNAPSHOT). +>>>>>>> origin/5.3.x * 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 27833c4ef16..3b02594b37f 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,9 @@ /** +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (6.0.0-SNAPSHOT). +======= + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.3.0-SNAPSHOT). +>>>>>>> origin/5.3.x * https://openapi-generator.tech * Do not edit the class manually. */ 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 72f64c2b370..e894f561fc6 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 @@ -44,7 +44,7 @@ public class FormatTest { private byte[] _byte; @JsonProperty("binary") - private org.springframework.web.multipart.MultipartFile binary; + private org.springframework.core.io.Resource binary; @JsonProperty("date") @org.springframework.format.annotation.DateTimeFormat(iso = org.springframework.format.annotation.DateTimeFormat.ISO.DATE) @@ -236,7 +236,7 @@ public class FormatTest { this._byte = _byte; } - public FormatTest binary(org.springframework.web.multipart.MultipartFile binary) { + public FormatTest binary(org.springframework.core.io.Resource binary) { this.binary = binary; return this; } @@ -249,11 +249,11 @@ public class FormatTest { @Valid - public org.springframework.web.multipart.MultipartFile getBinary() { + public org.springframework.core.io.Resource getBinary() { return binary; } - public void setBinary(org.springframework.web.multipart.MultipartFile binary) { + public void setBinary(org.springframework.core.io.Resource binary) { this.binary = binary; } diff --git a/samples/server/petstore/springboot-delegate/.openapi-generator/VERSION b/samples/server/petstore/springboot-delegate/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/server/petstore/springboot-delegate/.openapi-generator/VERSION +++ b/samples/server/petstore/springboot-delegate/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x 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 c95e8d5ae7a..6d74f1f2928 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,9 @@ /** +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (6.0.0-SNAPSHOT). +======= + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.3.0-SNAPSHOT). +>>>>>>> origin/5.3.x * 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 19a5ac37fbf..f5fe4e2947d 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,9 @@ /** +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (6.0.0-SNAPSHOT). +======= + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.3.0-SNAPSHOT). +>>>>>>> origin/5.3.x * 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 30fb4866522..6fc8b7f87ba 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,9 @@ /** +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (6.0.0-SNAPSHOT). +======= + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.3.0-SNAPSHOT). +>>>>>>> origin/5.3.x * 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 74eea454d7f..33df790a66a 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,9 @@ /** +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (6.0.0-SNAPSHOT). +======= + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.3.0-SNAPSHOT). +>>>>>>> origin/5.3.x * 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 cf465fac207..71184e1fbab 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,9 @@ /** +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (6.0.0-SNAPSHOT). +======= + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.3.0-SNAPSHOT). +>>>>>>> origin/5.3.x * 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 27833c4ef16..3b02594b37f 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,9 @@ /** +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (6.0.0-SNAPSHOT). +======= + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.3.0-SNAPSHOT). +>>>>>>> origin/5.3.x * https://openapi-generator.tech * Do not edit the class manually. */ 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 72f64c2b370..e894f561fc6 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 @@ -44,7 +44,7 @@ public class FormatTest { private byte[] _byte; @JsonProperty("binary") - private org.springframework.web.multipart.MultipartFile binary; + private org.springframework.core.io.Resource binary; @JsonProperty("date") @org.springframework.format.annotation.DateTimeFormat(iso = org.springframework.format.annotation.DateTimeFormat.ISO.DATE) @@ -236,7 +236,7 @@ public class FormatTest { this._byte = _byte; } - public FormatTest binary(org.springframework.web.multipart.MultipartFile binary) { + public FormatTest binary(org.springframework.core.io.Resource binary) { this.binary = binary; return this; } @@ -249,11 +249,11 @@ public class FormatTest { @Valid - public org.springframework.web.multipart.MultipartFile getBinary() { + public org.springframework.core.io.Resource getBinary() { return binary; } - public void setBinary(org.springframework.web.multipart.MultipartFile binary) { + public void setBinary(org.springframework.core.io.Resource binary) { this.binary = binary; } diff --git a/samples/server/petstore/springboot-implicitHeaders/.openapi-generator/VERSION b/samples/server/petstore/springboot-implicitHeaders/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/server/petstore/springboot-implicitHeaders/.openapi-generator/VERSION +++ b/samples/server/petstore/springboot-implicitHeaders/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x 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 75bdb0b8539..a2c54553dd4 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,9 @@ /** +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (6.0.0-SNAPSHOT). +======= + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.3.0-SNAPSHOT). +>>>>>>> origin/5.3.x * 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 1cebeb454b4..f014549bf12 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,9 @@ /** +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (6.0.0-SNAPSHOT). +======= + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.3.0-SNAPSHOT). +>>>>>>> origin/5.3.x * 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 d92c57b392a..c7faab93552 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,9 @@ /** +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (6.0.0-SNAPSHOT). +======= + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.3.0-SNAPSHOT). +>>>>>>> origin/5.3.x * 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 68efcd6434f..c9d16545968 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,9 @@ /** +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (6.0.0-SNAPSHOT). +======= + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.3.0-SNAPSHOT). +>>>>>>> origin/5.3.x * 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 f3a868e4b3d..5f0e4db290a 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,9 @@ /** +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (6.0.0-SNAPSHOT). +======= + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.3.0-SNAPSHOT). +>>>>>>> origin/5.3.x * 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 d9fda863c7d..2194adce4c5 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,9 @@ /** +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (6.0.0-SNAPSHOT). +======= + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.3.0-SNAPSHOT). +>>>>>>> origin/5.3.x * https://openapi-generator.tech * Do not edit the class manually. */ 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 72f64c2b370..e894f561fc6 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 @@ -44,7 +44,7 @@ public class FormatTest { private byte[] _byte; @JsonProperty("binary") - private org.springframework.web.multipart.MultipartFile binary; + private org.springframework.core.io.Resource binary; @JsonProperty("date") @org.springframework.format.annotation.DateTimeFormat(iso = org.springframework.format.annotation.DateTimeFormat.ISO.DATE) @@ -236,7 +236,7 @@ public class FormatTest { this._byte = _byte; } - public FormatTest binary(org.springframework.web.multipart.MultipartFile binary) { + public FormatTest binary(org.springframework.core.io.Resource binary) { this.binary = binary; return this; } @@ -249,11 +249,11 @@ public class FormatTest { @Valid - public org.springframework.web.multipart.MultipartFile getBinary() { + public org.springframework.core.io.Resource getBinary() { return binary; } - public void setBinary(org.springframework.web.multipart.MultipartFile binary) { + public void setBinary(org.springframework.core.io.Resource binary) { this.binary = binary; } diff --git a/samples/server/petstore/springboot-reactive/.openapi-generator/VERSION b/samples/server/petstore/springboot-reactive/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/server/petstore/springboot-reactive/.openapi-generator/VERSION +++ b/samples/server/petstore/springboot-reactive/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x 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 bdf4300d636..c7526b2b31d 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,9 @@ /** +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (6.0.0-SNAPSHOT). +======= + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.3.0-SNAPSHOT). +>>>>>>> origin/5.3.x * 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 c34d973f330..856dbdfce15 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,9 @@ /** +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (6.0.0-SNAPSHOT). +======= + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.3.0-SNAPSHOT). +>>>>>>> origin/5.3.x * 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 5307e824fff..8e60df9d824 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,9 @@ /** +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (6.0.0-SNAPSHOT). +======= + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.3.0-SNAPSHOT). +>>>>>>> origin/5.3.x * 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 ce0a1a31881..9f0bff4f857 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,9 @@ /** +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (6.0.0-SNAPSHOT). +======= + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.3.0-SNAPSHOT). +>>>>>>> origin/5.3.x * 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 62f6b2da0f5..92716796c80 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,9 @@ /** +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (6.0.0-SNAPSHOT). +======= + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.3.0-SNAPSHOT). +>>>>>>> origin/5.3.x * 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 35b75fe3e68..b1fd2d37dd3 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,9 @@ /** +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (6.0.0-SNAPSHOT). +======= + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.3.0-SNAPSHOT). +>>>>>>> origin/5.3.x * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-reactive/src/main/java/org/openapitools/configuration/HomeController.java b/samples/server/petstore/springboot-reactive/src/main/java/org/openapitools/configuration/HomeController.java index 5e4aeb0ea86..b1e5bfc21ee 100644 --- a/samples/server/petstore/springboot-reactive/src/main/java/org/openapitools/configuration/HomeController.java +++ b/samples/server/petstore/springboot-reactive/src/main/java/org/openapitools/configuration/HomeController.java @@ -3,7 +3,7 @@ package org.openapitools.configuration; import com.fasterxml.jackson.dataformat.yaml.YAMLMapper; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; -import org.springframework.web.multipart.MultipartFile; +import org.springframework.core.io.Resource; import org.springframework.stereotype.Controller; import org.springframework.util.StreamUtils; import org.springframework.web.bind.annotation.GetMapping; 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 72f64c2b370..e894f561fc6 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 @@ -44,7 +44,7 @@ public class FormatTest { private byte[] _byte; @JsonProperty("binary") - private org.springframework.web.multipart.MultipartFile binary; + private org.springframework.core.io.Resource binary; @JsonProperty("date") @org.springframework.format.annotation.DateTimeFormat(iso = org.springframework.format.annotation.DateTimeFormat.ISO.DATE) @@ -236,7 +236,7 @@ public class FormatTest { this._byte = _byte; } - public FormatTest binary(org.springframework.web.multipart.MultipartFile binary) { + public FormatTest binary(org.springframework.core.io.Resource binary) { this.binary = binary; return this; } @@ -249,11 +249,11 @@ public class FormatTest { @Valid - public org.springframework.web.multipart.MultipartFile getBinary() { + public org.springframework.core.io.Resource getBinary() { return binary; } - public void setBinary(org.springframework.web.multipart.MultipartFile binary) { + public void setBinary(org.springframework.core.io.Resource binary) { this.binary = binary; } 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 5f68295fc19..e8415097f3a 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,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x 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 9e8eda9066f..6c2e7b60bdd 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,9 @@ /** +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (6.0.0-SNAPSHOT). +======= + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.3.0-SNAPSHOT). +>>>>>>> origin/5.3.x * 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 70a9f1aebc2..8f6590220dc 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,9 @@ /** +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (6.0.0-SNAPSHOT). +======= + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.3.0-SNAPSHOT). +>>>>>>> origin/5.3.x * 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 980ac9450f3..780881750bc 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,9 @@ /** +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (6.0.0-SNAPSHOT). +======= + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.3.0-SNAPSHOT). +>>>>>>> origin/5.3.x * 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 4822e83b42a..6260b18265a 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,9 @@ /** +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (6.0.0-SNAPSHOT). +======= + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.3.0-SNAPSHOT). +>>>>>>> origin/5.3.x * 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 afad5769803..a550834adb8 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,9 @@ /** +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (6.0.0-SNAPSHOT). +======= + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.3.0-SNAPSHOT). +>>>>>>> origin/5.3.x * 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 20446a44497..74963cebcf6 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,9 @@ /** +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (6.0.0-SNAPSHOT). +======= + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.3.0-SNAPSHOT). +>>>>>>> origin/5.3.x * 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/FormatTest.java b/samples/server/petstore/springboot-spring-pageable-delegatePattern-without-j8/src/main/java/org/openapitools/model/FormatTest.java index 354373c3d6c..dedb11fe758 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 @@ -44,7 +44,7 @@ public class FormatTest { private byte[] _byte; @JsonProperty("binary") - private org.springframework.web.multipart.MultipartFile binary; + private org.springframework.core.io.Resource binary; @JsonProperty("date") @org.springframework.format.annotation.DateTimeFormat(iso = org.springframework.format.annotation.DateTimeFormat.ISO.DATE) @@ -236,7 +236,7 @@ public class FormatTest { this._byte = _byte; } - public FormatTest binary(org.springframework.web.multipart.MultipartFile binary) { + public FormatTest binary(org.springframework.core.io.Resource binary) { this.binary = binary; return this; } @@ -249,11 +249,11 @@ public class FormatTest { @Valid - public org.springframework.web.multipart.MultipartFile getBinary() { + public org.springframework.core.io.Resource getBinary() { return binary; } - public void setBinary(org.springframework.web.multipart.MultipartFile binary) { + public void setBinary(org.springframework.core.io.Resource binary) { this.binary = binary; } 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 5f68295fc19..e8415097f3a 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,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x 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 c95e8d5ae7a..6d74f1f2928 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,9 @@ /** +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (6.0.0-SNAPSHOT). +======= + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.3.0-SNAPSHOT). +>>>>>>> origin/5.3.x * 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 34dcbf602e4..a9bf8cdbe14 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,9 @@ /** +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (6.0.0-SNAPSHOT). +======= + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.3.0-SNAPSHOT). +>>>>>>> origin/5.3.x * 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 30fb4866522..6fc8b7f87ba 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,9 @@ /** +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (6.0.0-SNAPSHOT). +======= + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.3.0-SNAPSHOT). +>>>>>>> origin/5.3.x * 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 26a89838161..efd513205e3 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,9 @@ /** +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (6.0.0-SNAPSHOT). +======= + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.3.0-SNAPSHOT). +>>>>>>> origin/5.3.x * 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 cf465fac207..71184e1fbab 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,9 @@ /** +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (6.0.0-SNAPSHOT). +======= + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.3.0-SNAPSHOT). +>>>>>>> origin/5.3.x * 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 27833c4ef16..3b02594b37f 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,9 @@ /** +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (6.0.0-SNAPSHOT). +======= + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.3.0-SNAPSHOT). +>>>>>>> origin/5.3.x * 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/FormatTest.java b/samples/server/petstore/springboot-spring-pageable-delegatePattern/src/main/java/org/openapitools/model/FormatTest.java index 72f64c2b370..e894f561fc6 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 @@ -44,7 +44,7 @@ public class FormatTest { private byte[] _byte; @JsonProperty("binary") - private org.springframework.web.multipart.MultipartFile binary; + private org.springframework.core.io.Resource binary; @JsonProperty("date") @org.springframework.format.annotation.DateTimeFormat(iso = org.springframework.format.annotation.DateTimeFormat.ISO.DATE) @@ -236,7 +236,7 @@ public class FormatTest { this._byte = _byte; } - public FormatTest binary(org.springframework.web.multipart.MultipartFile binary) { + public FormatTest binary(org.springframework.core.io.Resource binary) { this.binary = binary; return this; } @@ -249,11 +249,11 @@ public class FormatTest { @Valid - public org.springframework.web.multipart.MultipartFile getBinary() { + public org.springframework.core.io.Resource getBinary() { return binary; } - public void setBinary(org.springframework.web.multipart.MultipartFile binary) { + public void setBinary(org.springframework.core.io.Resource binary) { this.binary = binary; } 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 5f68295fc19..e8415097f3a 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,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x 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 9e8eda9066f..6c2e7b60bdd 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,9 @@ /** +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (6.0.0-SNAPSHOT). +======= + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.3.0-SNAPSHOT). +>>>>>>> origin/5.3.x * 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 70a9f1aebc2..8f6590220dc 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,9 @@ /** +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (6.0.0-SNAPSHOT). +======= + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.3.0-SNAPSHOT). +>>>>>>> origin/5.3.x * 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 980ac9450f3..780881750bc 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,9 @@ /** +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (6.0.0-SNAPSHOT). +======= + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.3.0-SNAPSHOT). +>>>>>>> origin/5.3.x * 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 4822e83b42a..6260b18265a 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,9 @@ /** +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (6.0.0-SNAPSHOT). +======= + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.3.0-SNAPSHOT). +>>>>>>> origin/5.3.x * 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 afad5769803..a550834adb8 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,9 @@ /** +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (6.0.0-SNAPSHOT). +======= + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.3.0-SNAPSHOT). +>>>>>>> origin/5.3.x * 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 20446a44497..74963cebcf6 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,9 @@ /** +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (6.0.0-SNAPSHOT). +======= + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.3.0-SNAPSHOT). +>>>>>>> origin/5.3.x * 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/FormatTest.java b/samples/server/petstore/springboot-spring-pageable-without-j8/src/main/java/org/openapitools/model/FormatTest.java index 354373c3d6c..dedb11fe758 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 @@ -44,7 +44,7 @@ public class FormatTest { private byte[] _byte; @JsonProperty("binary") - private org.springframework.web.multipart.MultipartFile binary; + private org.springframework.core.io.Resource binary; @JsonProperty("date") @org.springframework.format.annotation.DateTimeFormat(iso = org.springframework.format.annotation.DateTimeFormat.ISO.DATE) @@ -236,7 +236,7 @@ public class FormatTest { this._byte = _byte; } - public FormatTest binary(org.springframework.web.multipart.MultipartFile binary) { + public FormatTest binary(org.springframework.core.io.Resource binary) { this.binary = binary; return this; } @@ -249,11 +249,11 @@ public class FormatTest { @Valid - public org.springframework.web.multipart.MultipartFile getBinary() { + public org.springframework.core.io.Resource getBinary() { return binary; } - public void setBinary(org.springframework.web.multipart.MultipartFile binary) { + public void setBinary(org.springframework.core.io.Resource binary) { this.binary = binary; } diff --git a/samples/server/petstore/springboot-spring-pageable/.openapi-generator/VERSION b/samples/server/petstore/springboot-spring-pageable/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/server/petstore/springboot-spring-pageable/.openapi-generator/VERSION +++ b/samples/server/petstore/springboot-spring-pageable/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x 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 67df1501f09..3ee84f0dcc3 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,9 @@ /** +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (6.0.0-SNAPSHOT). +======= + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.3.0-SNAPSHOT). +>>>>>>> origin/5.3.x * 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 cdf16fc14a7..25b8b894ed0 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,9 @@ /** +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (6.0.0-SNAPSHOT). +======= + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.3.0-SNAPSHOT). +>>>>>>> origin/5.3.x * 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 7adfddb01e7..f4bbfdc593a 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,9 @@ /** +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (6.0.0-SNAPSHOT). +======= + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.3.0-SNAPSHOT). +>>>>>>> origin/5.3.x * 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 c4f0ea452d1..99609959e7a 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,9 @@ /** +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (6.0.0-SNAPSHOT). +======= + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.3.0-SNAPSHOT). +>>>>>>> origin/5.3.x * 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 a12dc1250c2..c3534db4fe8 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,9 @@ /** +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (6.0.0-SNAPSHOT). +======= + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.3.0-SNAPSHOT). +>>>>>>> origin/5.3.x * 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 da836caf4bf..c231313c77f 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,9 @@ /** +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (6.0.0-SNAPSHOT). +======= + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.3.0-SNAPSHOT). +>>>>>>> origin/5.3.x * 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/FormatTest.java b/samples/server/petstore/springboot-spring-pageable/src/main/java/org/openapitools/model/FormatTest.java index 72f64c2b370..e894f561fc6 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 @@ -44,7 +44,7 @@ public class FormatTest { private byte[] _byte; @JsonProperty("binary") - private org.springframework.web.multipart.MultipartFile binary; + private org.springframework.core.io.Resource binary; @JsonProperty("date") @org.springframework.format.annotation.DateTimeFormat(iso = org.springframework.format.annotation.DateTimeFormat.ISO.DATE) @@ -236,7 +236,7 @@ public class FormatTest { this._byte = _byte; } - public FormatTest binary(org.springframework.web.multipart.MultipartFile binary) { + public FormatTest binary(org.springframework.core.io.Resource binary) { this.binary = binary; return this; } @@ -249,11 +249,11 @@ public class FormatTest { @Valid - public org.springframework.web.multipart.MultipartFile getBinary() { + public org.springframework.core.io.Resource getBinary() { return binary; } - public void setBinary(org.springframework.web.multipart.MultipartFile binary) { + public void setBinary(org.springframework.core.io.Resource binary) { this.binary = binary; } diff --git a/samples/server/petstore/springboot-useoptional/.openapi-generator/VERSION b/samples/server/petstore/springboot-useoptional/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/server/petstore/springboot-useoptional/.openapi-generator/VERSION +++ b/samples/server/petstore/springboot-useoptional/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x 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 67df1501f09..3ee84f0dcc3 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,9 @@ /** +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (6.0.0-SNAPSHOT). +======= + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.3.0-SNAPSHOT). +>>>>>>> origin/5.3.x * 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 1d0a086cada..e4e555de534 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,9 @@ /** +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (6.0.0-SNAPSHOT). +======= + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.3.0-SNAPSHOT). +>>>>>>> origin/5.3.x * https://openapi-generator.tech * Do not edit the class manually. */ 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 7adfddb01e7..f4bbfdc593a 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,9 @@ /** +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (6.0.0-SNAPSHOT). +======= + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.3.0-SNAPSHOT). +>>>>>>> origin/5.3.x * 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 e1569c5d992..8e22d83cb32 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,9 @@ /** +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (6.0.0-SNAPSHOT). +======= + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.3.0-SNAPSHOT). +>>>>>>> origin/5.3.x * 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 a12dc1250c2..c3534db4fe8 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,9 @@ /** +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (6.0.0-SNAPSHOT). +======= + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.3.0-SNAPSHOT). +>>>>>>> origin/5.3.x * 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 da836caf4bf..c231313c77f 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,9 @@ /** +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (6.0.0-SNAPSHOT). +======= + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.3.0-SNAPSHOT). +>>>>>>> origin/5.3.x * https://openapi-generator.tech * Do not edit the class manually. */ 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 72f64c2b370..e894f561fc6 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 @@ -44,7 +44,7 @@ public class FormatTest { private byte[] _byte; @JsonProperty("binary") - private org.springframework.web.multipart.MultipartFile binary; + private org.springframework.core.io.Resource binary; @JsonProperty("date") @org.springframework.format.annotation.DateTimeFormat(iso = org.springframework.format.annotation.DateTimeFormat.ISO.DATE) @@ -236,7 +236,7 @@ public class FormatTest { this._byte = _byte; } - public FormatTest binary(org.springframework.web.multipart.MultipartFile binary) { + public FormatTest binary(org.springframework.core.io.Resource binary) { this.binary = binary; return this; } @@ -249,11 +249,11 @@ public class FormatTest { @Valid - public org.springframework.web.multipart.MultipartFile getBinary() { + public org.springframework.core.io.Resource getBinary() { return binary; } - public void setBinary(org.springframework.web.multipart.MultipartFile binary) { + public void setBinary(org.springframework.core.io.Resource binary) { this.binary = binary; } diff --git a/samples/server/petstore/springboot-virtualan/.openapi-generator/VERSION b/samples/server/petstore/springboot-virtualan/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/server/petstore/springboot-virtualan/.openapi-generator/VERSION +++ b/samples/server/petstore/springboot-virtualan/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x diff --git a/samples/server/petstore/springboot-virtualan/pom.xml b/samples/server/petstore/springboot-virtualan/pom.xml index 3dceb8a963e..8dc39bea12e 100644 --- a/samples/server/petstore/springboot-virtualan/pom.xml +++ b/samples/server/petstore/springboot-virtualan/pom.xml @@ -75,18 +75,13 @@ io.virtualan virtualan-plugin - 2.1.7 + 2.2.1 org.hsqldb hsqldb - 2.3.2 - - - org.springframework.boot - spring-boot-starter-data-jpa - 1.5.9.RELEASE + 2.5.0 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 a214e7eb369..800ca008b56 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,9 @@ /** +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (6.0.0-SNAPSHOT). +======= + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.3.0-SNAPSHOT). +>>>>>>> origin/5.3.x * 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 dcbf03c7152..e1fae24730a 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,9 @@ /** +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (6.0.0-SNAPSHOT). +======= + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.3.0-SNAPSHOT). +>>>>>>> origin/5.3.x * 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 a844ea2c160..60875426010 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,9 @@ /** +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (6.0.0-SNAPSHOT). +======= + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.3.0-SNAPSHOT). +>>>>>>> origin/5.3.x * 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 14564c051ff..43e4dd5a398 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,9 @@ /** +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (6.0.0-SNAPSHOT). +======= + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.3.0-SNAPSHOT). +>>>>>>> origin/5.3.x * 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 884a34a4f85..008abad61ac 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,9 @@ /** +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (6.0.0-SNAPSHOT). +======= + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.3.0-SNAPSHOT). +>>>>>>> origin/5.3.x * 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 57c7e4624ce..9e4d04d36be 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,9 @@ /** +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (6.0.0-SNAPSHOT). +======= + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.3.0-SNAPSHOT). +>>>>>>> origin/5.3.x * https://openapi-generator.tech * Do not edit the class manually. */ 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 07241a089c8..d58e787c368 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 @@ -44,7 +44,7 @@ public class FormatTest { private byte[] _byte; @JsonProperty("binary") - private org.springframework.web.multipart.MultipartFile binary; + private org.springframework.core.io.Resource binary; @JsonProperty("date") @org.springframework.format.annotation.DateTimeFormat(iso = org.springframework.format.annotation.DateTimeFormat.ISO.DATE) @@ -236,7 +236,7 @@ public class FormatTest { this._byte = _byte; } - public FormatTest binary(org.springframework.web.multipart.MultipartFile binary) { + public FormatTest binary(org.springframework.core.io.Resource binary) { this.binary = binary; return this; } @@ -249,11 +249,11 @@ public class FormatTest { @Valid - public org.springframework.web.multipart.MultipartFile getBinary() { + public org.springframework.core.io.Resource getBinary() { return binary; } - public void setBinary(org.springframework.web.multipart.MultipartFile binary) { + public void setBinary(org.springframework.core.io.Resource binary) { this.binary = binary; } diff --git a/samples/server/petstore/springboot-virtualan/src/main/resources/application.properties b/samples/server/petstore/springboot-virtualan/src/main/resources/application.properties index cf5e33b6869..64073b52f1e 100644 --- a/samples/server/petstore/springboot-virtualan/src/main/resources/application.properties +++ b/samples/server/petstore/springboot-virtualan/src/main/resources/application.properties @@ -2,7 +2,7 @@ springfox.documentation.swagger.v2.path=/api-docs server.port=80 spring.jackson.date-format=org.openapitools.RFC3339DateFormat spring.jackson.serialization.WRITE_DATES_AS_TIMESTAMPS=false -virtual.datasource.driver-class-name=org.hsqldb.jdbcDriver -virtual.datasource.jdbcurl=jdbc:hsqldb:mem:dataSource -virtual.datasource.username=sa -virtual.datasource.password= +virtualan.datasource.driver-class-name=org.hsqldb.jdbcDriver +virtualan.datasource.jdbcurl=jdbc:hsqldb:mem:dataSource +virtualan.datasource.username=sa +virtualan.datasource.password= diff --git a/samples/server/petstore/springboot/.openapi-generator/VERSION b/samples/server/petstore/springboot/.openapi-generator/VERSION index 5f68295fc19..e8415097f3a 100644 --- a/samples/server/petstore/springboot/.openapi-generator/VERSION +++ b/samples/server/petstore/springboot/.openapi-generator/VERSION @@ -1 +1,5 @@ -6.0.0-SNAPSHOT \ No newline at end of file +<<<<<<< HEAD +6.0.0-SNAPSHOT +======= +5.3.0-SNAPSHOT +>>>>>>> origin/5.3.x 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 67df1501f09..3ee84f0dcc3 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,9 @@ /** +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (6.0.0-SNAPSHOT). +======= + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.3.0-SNAPSHOT). +>>>>>>> origin/5.3.x * 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 4227fb26a50..fa4d1f4009b 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,9 @@ /** +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (6.0.0-SNAPSHOT). +======= + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.3.0-SNAPSHOT). +>>>>>>> origin/5.3.x * 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 7adfddb01e7..f4bbfdc593a 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,9 @@ /** +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (6.0.0-SNAPSHOT). +======= + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.3.0-SNAPSHOT). +>>>>>>> origin/5.3.x * 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 f4f5c97755f..90b15210bc8 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,9 @@ /** +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (6.0.0-SNAPSHOT). +======= + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.3.0-SNAPSHOT). +>>>>>>> origin/5.3.x * 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 a12dc1250c2..c3534db4fe8 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,9 @@ /** +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (6.0.0-SNAPSHOT). +======= + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.3.0-SNAPSHOT). +>>>>>>> origin/5.3.x * 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 da836caf4bf..c231313c77f 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,9 @@ /** +<<<<<<< HEAD * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (6.0.0-SNAPSHOT). +======= + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (5.3.0-SNAPSHOT). +>>>>>>> origin/5.3.x * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot/src/main/java/org/openapitools/model/FormatTest.java b/samples/server/petstore/springboot/src/main/java/org/openapitools/model/FormatTest.java index 72f64c2b370..e894f561fc6 100644 --- a/samples/server/petstore/springboot/src/main/java/org/openapitools/model/FormatTest.java +++ b/samples/server/petstore/springboot/src/main/java/org/openapitools/model/FormatTest.java @@ -44,7 +44,7 @@ public class FormatTest { private byte[] _byte; @JsonProperty("binary") - private org.springframework.web.multipart.MultipartFile binary; + private org.springframework.core.io.Resource binary; @JsonProperty("date") @org.springframework.format.annotation.DateTimeFormat(iso = org.springframework.format.annotation.DateTimeFormat.ISO.DATE) @@ -236,7 +236,7 @@ public class FormatTest { this._byte = _byte; } - public FormatTest binary(org.springframework.web.multipart.MultipartFile binary) { + public FormatTest binary(org.springframework.core.io.Resource binary) { this.binary = binary; return this; } @@ -249,11 +249,11 @@ public class FormatTest { @Valid - public org.springframework.web.multipart.MultipartFile getBinary() { + public org.springframework.core.io.Resource getBinary() { return binary; } - public void setBinary(org.springframework.web.multipart.MultipartFile binary) { + public void setBinary(org.springframework.core.io.Resource binary) { this.binary = binary; } diff --git a/shippable.yml b/shippable.yml index 5dc40c6fa41..009806b31a3 100644 --- a/shippable.yml +++ b/shippable.yml @@ -21,7 +21,6 @@ build: - export PATH=/opt/gradle/gradle-5.6.4/bin:$PATH - gradle -v - java -version - - mvn --no-snapshot-updates --quiet clean install -Dmaven.javadoc.skip=true # ensure all modifications created by 'mature' generators are in the git repo # below move to CircleCI ./bin/utils/ensure-up-to-date # prepare environment for tests @@ -49,12 +48,3 @@ build: - mix --version # test samples defined in pom.xml - mvn --no-snapshot-updates --quiet verify -P samples.shippable -Dmaven.javadoc.skip=true - # test maven plugin - - mvn --no-snapshot-updates --quiet clean compile -f modules/openapi-generator-maven-plugin/examples/java-client.xml -Dorg.slf4j.simpleLogger.defaultLogLevel=error - - mvn --no-snapshot-updates --quiet clean compile -f modules/openapi-generator-maven-plugin/examples/multi-module/pom.xml -Dorg.slf4j.simpleLogger.defaultLogLevel=error - - mvn --no-snapshot-updates --quiet clean compile -f modules/openapi-generator-maven-plugin/examples/kotlin.xml -Dorg.slf4j.simpleLogger.defaultLogLevel=error - - mvn --no-snapshot-updates --quiet clean compile -f modules/openapi-generator-maven-plugin/examples/spring.xml -Dorg.slf4j.simpleLogger.defaultLogLevel=error - # test gradle plugin - - (cd modules/openapi-generator-gradle-plugin/samples/local-spec && ./gradlew buildGoSdk) - - (cd modules/openapi-generator-gradle-plugin/samples/local-spec && ./gradlew openApiGenerate) - diff --git a/website/src/dynamic/users.yml b/website/src/dynamic/users.yml index 7b955bfe337..c8ff21541f9 100644 --- a/website/src/dynamic/users.yml +++ b/website/src/dynamic/users.yml @@ -1,3 +1,8 @@ +- + caption: "Aalborg University" + image: "img/companies/aalborg_university.png" + infoLink: "https://www.aau.dk/" + pinned: false - caption: "Adaptant Solutions AG" image: "img/companies/adaptant.png" diff --git a/website/static/img/companies/aalborg_university.png b/website/static/img/companies/aalborg_university.png new file mode 100644 index 00000000000..5fcf0511d47 Binary files /dev/null and b/website/static/img/companies/aalborg_university.png differ